From 3ae2e21c0889471a59da7e4854aaa7097b743007 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund Date: Tue, 24 Nov 2026 19:04:20 -0500 Subject: [PATCH 01/57] Publish the working VIctory prologue snapshot. Source only: the x16 adapter pick and the shader fixes that rendered the world. No game data, textures, or executable. Co-authored-by: Cursor --- .cargo/config.toml | 2 + .gitattributes | 4 + .githooks/pre-commit | 3 + .github/workflows/ci.yml | 33 + .gitignore | 78 + .victory-root | 5 + Cargo.lock | 914 ++ Cargo.toml | 78 + LICENSE | 674 + README.md | 217 + apps/victory/Cargo.toml | 34 + apps/victory/src/census.rs | 124 + apps/victory/src/inspect.rs | 153 + apps/victory/src/main.rs | 222 + apps/victory/src/run.rs | 344 + apps/victory/src/shader.rs | 227 + apps/victory/src/translate.rs | 785 ++ crates/victory-core/Cargo.toml | 25 + crates/victory-core/src/config.rs | 217 + crates/victory-core/src/lib.rs | 13 + crates/victory-core/src/logging.rs | 35 + crates/victory-core/src/policy.rs | 159 + crates/victory-formats/Cargo.toml | 11 + crates/victory-formats/src/bcpack-tables.bin | Bin 0 -> 77982 bytes crates/victory-formats/src/bcpack.rs | 1608 +++ crates/victory-formats/src/lib.rs | 10 + crates/victory-formats/src/texture.rs | 1090 ++ crates/victory-formats/src/xma.rs | 1247 ++ crates/victory-formats/src/xma/tables.rs | 410 + crates/victory-game/Cargo.toml | 15 + crates/victory-game/src/lib.rs | 25 + crates/victory-game/src/sgd5.rs | 136 + crates/victory-gpu/Cargo.toml | 42 + crates/victory-gpu/src/capture.rs | 848 ++ crates/victory-gpu/src/console.rs | 50 + crates/victory-gpu/src/copystat.rs | 1303 ++ crates/victory-gpu/src/descriptor.rs | 1190 ++ crates/victory-gpu/src/descriptor/host.rs | 2473 ++++ crates/victory-gpu/src/device.rs | 587 + crates/victory-gpu/src/draw.rs | 2692 ++++ crates/victory-gpu/src/dxgi.rs | 341 + crates/victory-gpu/src/fence.rs | 193 + crates/victory-gpu/src/frame.rs | 246 + crates/victory-gpu/src/host.rs | 6683 +++++++++ crates/victory-gpu/src/indirect.rs | 1216 ++ crates/victory-gpu/src/inplace.rs | 1170 ++ crates/victory-gpu/src/lib.rs | 66 + crates/victory-gpu/src/list.rs | 2219 +++ crates/victory-gpu/src/memory.rs | 319 + crates/victory-gpu/src/object.rs | 384 + crates/victory-gpu/src/pipeline.rs | 843 ++ crates/victory-gpu/src/pipeline/host.rs | 931 ++ crates/victory-gpu/src/pipeline/library.rs | 838 ++ crates/victory-gpu/src/pipeline/make.rs | 399 + crates/victory-gpu/src/primitive.rs | 237 + crates/victory-gpu/src/query.rs | 72 + crates/victory-gpu/src/queue.rs | 1086 ++ crates/victory-gpu/src/resource.rs | 3410 +++++ crates/victory-gpu/src/root.rs | 324 + crates/victory-gpu/src/sampler.rs | 119 + crates/victory-gpu/src/shader_cache.rs | 415 + crates/victory-gpu/src/shadow.rs | 3186 +++++ crates/victory-gpu/src/signature.rs | 94 + crates/victory-gpu/src/texture.rs | 1167 ++ crates/victory-gpu/src/watch.rs | 1108 ++ crates/victory-hle/Cargo.toml | 55 + crates/victory-hle/src/host.rs | 148 + crates/victory-hle/src/lib.rs | 123 + crates/victory-hle/src/modules/apu.rs | 524 + crates/victory-hle/src/modules/audio.rs | 1172 ++ .../victory-hle/src/modules/audio/capture.rs | 229 + crates/victory-hle/src/modules/d3d12x.rs | 108 + crates/victory-hle/src/modules/display.rs | 195 + crates/victory-hle/src/modules/dsp.rs | 314 + crates/victory-hle/src/modules/dstorage.rs | 1555 +++ crates/victory-hle/src/modules/files.rs | 941 ++ crates/victory-hle/src/modules/gameinput.rs | 1629 +++ crates/victory-hle/src/modules/kernel.rs | 687 + crates/victory-hle/src/modules/lifecycle.rs | 438 + crates/victory-hle/src/modules/media.rs | 531 + crates/victory-hle/src/modules/mod.rs | 74 + crates/victory-hle/src/modules/net.rs | 1069 ++ crates/victory-hle/src/modules/speech.rs | 151 + crates/victory-hle/src/modules/storage.rs | 240 + crates/victory-hle/src/modules/xasync.rs | 1337 ++ crates/victory-hle/src/modules/xg.rs | 780 ++ crates/victory-hle/src/modules/xgame.rs | 241 + .../victory-hle/src/modules/xgameruntime.rs | 344 + crates/victory-hle/src/modules/xgamesave.rs | 1355 ++ crates/victory-hle/src/modules/xgameui.rs | 321 + crates/victory-hle/src/modules/xmem.rs | 1324 ++ crates/victory-hle/src/modules/xnetworking.rs | 210 + crates/victory-hle/src/modules/xpackage.rs | 371 + crates/victory-hle/src/modules/xstore.rs | 479 + crates/victory-hle/src/modules/xsystem.rs | 400 + crates/victory-hle/src/modules/xuser.rs | 425 + crates/victory-hle/src/registry.rs | 95 + crates/victory-hle/src/runtime.rs | 226 + crates/victory-hle/tests/no_dll_planting.rs | 29 + crates/victory-loader/Cargo.toml | 39 + crates/victory-loader/src/console_insn.rs | 249 + .../victory-loader/src/console_insn_decode.rs | 233 + crates/victory-loader/src/crash.rs | 1000 ++ crates/victory-loader/src/lib.rs | 62 + crates/victory-loader/src/prepare.rs | 283 + crates/victory-loader/src/resolve.rs | 33 + crates/victory-loader/src/stacks.rs | 224 + crates/victory-loader/src/threads.rs | 439 + crates/victory-loader/src/thunks.rs | 187 + crates/victory-loader/src/tls.rs | 219 + crates/victory-loader/src/windows.rs | 432 + crates/victory-loader/tests/load_probe.rs | 268 + crates/victory-loader/tests/title_dlls.rs | 16 + crates/victory-pe/Cargo.toml | 15 + crates/victory-pe/src/image.rs | 547 + crates/victory-pe/src/implib.rs | 66 + crates/victory-pe/src/layout.rs | 110 + crates/victory-pe/src/lib.rs | 35 + crates/victory-pipeline/Cargo.toml | 20 + crates/victory-pipeline/src/cache.rs | 159 + crates/victory-pipeline/src/lib.rs | 23 + crates/victory-shader/Cargo.toml | 40 + crates/victory-shader/src/bvh.rs | 696 + crates/victory-shader/src/dxbc.rs | 181 + crates/victory-shader/src/dxil.rs | 211 + crates/victory-shader/src/emit/bitcode.rs | 1235 ++ .../victory-shader/src/emit/bitcode/census.rs | 174 + crates/victory-shader/src/emit/bitcode/opt.rs | 2136 +++ crates/victory-shader/src/emit/container.rs | 419 + crates/victory-shader/src/emit/diff_tests.rs | 1287 ++ crates/victory-shader/src/emit/host.rs | 1453 ++ crates/victory-shader/src/emit/intersect.rs | 557 + .../src/emit/intersect_tests.rs | 690 + crates/victory-shader/src/emit/lower.rs | 11475 ++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 1743 +++ crates/victory-shader/src/emit/own_bits.rs | 914 ++ crates/victory-shader/src/emit/rect.rs | 484 + crates/victory-shader/src/emit/sampler.rs | 125 + crates/victory-shader/src/emit/shader.rs | 881 ++ crates/victory-shader/src/emit/threading.rs | 218 + crates/victory-shader/src/emit/validator.rs | 221 + crates/victory-shader/src/emit/valu_tests.rs | 1266 ++ .../src/emit/waterfall_tests.rs | 251 + crates/victory-shader/src/emit/wave.rs | 1064 ++ .../victory-shader/src/emit/wave64_tests.rs | 452 + crates/victory-shader/src/gfx10/fields.rs | 815 ++ crates/victory-shader/src/gfx10/mod.rs | 496 + crates/victory-shader/src/gfx10/opcodes.rs | 1333 ++ crates/victory-shader/src/gfx10/sp3.rs | 784 ++ crates/victory-shader/src/io.rs | 833 ++ crates/victory-shader/src/ir.rs | 1791 +++ crates/victory-shader/src/lib.rs | 38 + crates/victory-shader/src/native.rs | 1023 ++ crates/victory-shader/src/resource.rs | 3848 ++++++ crates/victory-shader/src/spill.rs | 380 + crates/victory-shader/src/structure.rs | 1848 +++ docs/architecture.md | 99 + docs/asset-policy.md | 60 + docs/fork-ray-tracing.md | 85 + rust-toolchain.toml | 5 + rustfmt.toml | 2 + tests/fixtures/hle-probe/Cargo.lock | 7 + tests/fixtures/hle-probe/Cargo.toml | 18 + tests/fixtures/hle-probe/build.rs | 4 + tests/fixtures/hle-probe/src/lib.rs | 123 + victory.example.toml | 19 + xtask/Cargo.toml | 16 + xtask/src/main.rs | 56 + xtask/src/policy.rs | 223 + 169 files changed, 110007 insertions(+) create mode 100644 .cargo/config.toml create mode 100644 .gitattributes create mode 100644 .githooks/pre-commit create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .victory-root create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 apps/victory/Cargo.toml create mode 100644 apps/victory/src/census.rs create mode 100644 apps/victory/src/inspect.rs create mode 100644 apps/victory/src/main.rs create mode 100644 apps/victory/src/run.rs create mode 100644 apps/victory/src/shader.rs create mode 100644 apps/victory/src/translate.rs create mode 100644 crates/victory-core/Cargo.toml create mode 100644 crates/victory-core/src/config.rs create mode 100644 crates/victory-core/src/lib.rs create mode 100644 crates/victory-core/src/logging.rs create mode 100644 crates/victory-core/src/policy.rs create mode 100644 crates/victory-formats/Cargo.toml create mode 100644 crates/victory-formats/src/bcpack-tables.bin create mode 100644 crates/victory-formats/src/bcpack.rs create mode 100644 crates/victory-formats/src/lib.rs create mode 100644 crates/victory-formats/src/texture.rs create mode 100644 crates/victory-formats/src/xma.rs create mode 100644 crates/victory-formats/src/xma/tables.rs create mode 100644 crates/victory-game/Cargo.toml create mode 100644 crates/victory-game/src/lib.rs create mode 100644 crates/victory-game/src/sgd5.rs create mode 100644 crates/victory-gpu/Cargo.toml create mode 100644 crates/victory-gpu/src/capture.rs create mode 100644 crates/victory-gpu/src/console.rs create mode 100644 crates/victory-gpu/src/copystat.rs create mode 100644 crates/victory-gpu/src/descriptor.rs create mode 100644 crates/victory-gpu/src/descriptor/host.rs create mode 100644 crates/victory-gpu/src/device.rs create mode 100644 crates/victory-gpu/src/draw.rs create mode 100644 crates/victory-gpu/src/dxgi.rs create mode 100644 crates/victory-gpu/src/fence.rs create mode 100644 crates/victory-gpu/src/frame.rs create mode 100644 crates/victory-gpu/src/host.rs create mode 100644 crates/victory-gpu/src/indirect.rs create mode 100644 crates/victory-gpu/src/inplace.rs create mode 100644 crates/victory-gpu/src/lib.rs create mode 100644 crates/victory-gpu/src/list.rs create mode 100644 crates/victory-gpu/src/memory.rs create mode 100644 crates/victory-gpu/src/object.rs create mode 100644 crates/victory-gpu/src/pipeline.rs create mode 100644 crates/victory-gpu/src/pipeline/host.rs create mode 100644 crates/victory-gpu/src/pipeline/library.rs create mode 100644 crates/victory-gpu/src/pipeline/make.rs create mode 100644 crates/victory-gpu/src/primitive.rs create mode 100644 crates/victory-gpu/src/query.rs create mode 100644 crates/victory-gpu/src/queue.rs create mode 100644 crates/victory-gpu/src/resource.rs create mode 100644 crates/victory-gpu/src/root.rs create mode 100644 crates/victory-gpu/src/sampler.rs create mode 100644 crates/victory-gpu/src/shader_cache.rs create mode 100644 crates/victory-gpu/src/shadow.rs create mode 100644 crates/victory-gpu/src/signature.rs create mode 100644 crates/victory-gpu/src/texture.rs create mode 100644 crates/victory-gpu/src/watch.rs create mode 100644 crates/victory-hle/Cargo.toml create mode 100644 crates/victory-hle/src/host.rs create mode 100644 crates/victory-hle/src/lib.rs create mode 100644 crates/victory-hle/src/modules/apu.rs create mode 100644 crates/victory-hle/src/modules/audio.rs create mode 100644 crates/victory-hle/src/modules/audio/capture.rs create mode 100644 crates/victory-hle/src/modules/d3d12x.rs create mode 100644 crates/victory-hle/src/modules/display.rs create mode 100644 crates/victory-hle/src/modules/dsp.rs create mode 100644 crates/victory-hle/src/modules/dstorage.rs create mode 100644 crates/victory-hle/src/modules/files.rs create mode 100644 crates/victory-hle/src/modules/gameinput.rs create mode 100644 crates/victory-hle/src/modules/kernel.rs create mode 100644 crates/victory-hle/src/modules/lifecycle.rs create mode 100644 crates/victory-hle/src/modules/media.rs create mode 100644 crates/victory-hle/src/modules/mod.rs create mode 100644 crates/victory-hle/src/modules/net.rs create mode 100644 crates/victory-hle/src/modules/speech.rs create mode 100644 crates/victory-hle/src/modules/storage.rs create mode 100644 crates/victory-hle/src/modules/xasync.rs create mode 100644 crates/victory-hle/src/modules/xg.rs create mode 100644 crates/victory-hle/src/modules/xgame.rs create mode 100644 crates/victory-hle/src/modules/xgameruntime.rs create mode 100644 crates/victory-hle/src/modules/xgamesave.rs create mode 100644 crates/victory-hle/src/modules/xgameui.rs create mode 100644 crates/victory-hle/src/modules/xmem.rs create mode 100644 crates/victory-hle/src/modules/xnetworking.rs create mode 100644 crates/victory-hle/src/modules/xpackage.rs create mode 100644 crates/victory-hle/src/modules/xstore.rs create mode 100644 crates/victory-hle/src/modules/xsystem.rs create mode 100644 crates/victory-hle/src/modules/xuser.rs create mode 100644 crates/victory-hle/src/registry.rs create mode 100644 crates/victory-hle/src/runtime.rs create mode 100644 crates/victory-hle/tests/no_dll_planting.rs create mode 100644 crates/victory-loader/Cargo.toml create mode 100644 crates/victory-loader/src/console_insn.rs create mode 100644 crates/victory-loader/src/console_insn_decode.rs create mode 100644 crates/victory-loader/src/crash.rs create mode 100644 crates/victory-loader/src/lib.rs create mode 100644 crates/victory-loader/src/prepare.rs create mode 100644 crates/victory-loader/src/resolve.rs create mode 100644 crates/victory-loader/src/stacks.rs create mode 100644 crates/victory-loader/src/threads.rs create mode 100644 crates/victory-loader/src/thunks.rs create mode 100644 crates/victory-loader/src/tls.rs create mode 100644 crates/victory-loader/src/windows.rs create mode 100644 crates/victory-loader/tests/load_probe.rs create mode 100644 crates/victory-loader/tests/title_dlls.rs create mode 100644 crates/victory-pe/Cargo.toml create mode 100644 crates/victory-pe/src/image.rs create mode 100644 crates/victory-pe/src/implib.rs create mode 100644 crates/victory-pe/src/layout.rs create mode 100644 crates/victory-pe/src/lib.rs create mode 100644 crates/victory-pipeline/Cargo.toml create mode 100644 crates/victory-pipeline/src/cache.rs create mode 100644 crates/victory-pipeline/src/lib.rs create mode 100644 crates/victory-shader/Cargo.toml create mode 100644 crates/victory-shader/src/bvh.rs create mode 100644 crates/victory-shader/src/dxbc.rs create mode 100644 crates/victory-shader/src/dxil.rs create mode 100644 crates/victory-shader/src/emit/bitcode.rs create mode 100644 crates/victory-shader/src/emit/bitcode/census.rs create mode 100644 crates/victory-shader/src/emit/bitcode/opt.rs create mode 100644 crates/victory-shader/src/emit/container.rs create mode 100644 crates/victory-shader/src/emit/diff_tests.rs create mode 100644 crates/victory-shader/src/emit/host.rs create mode 100644 crates/victory-shader/src/emit/intersect.rs create mode 100644 crates/victory-shader/src/emit/intersect_tests.rs create mode 100644 crates/victory-shader/src/emit/lower.rs create mode 100644 crates/victory-shader/src/emit/mod.rs create mode 100644 crates/victory-shader/src/emit/own_bits.rs create mode 100644 crates/victory-shader/src/emit/rect.rs create mode 100644 crates/victory-shader/src/emit/sampler.rs create mode 100644 crates/victory-shader/src/emit/shader.rs create mode 100644 crates/victory-shader/src/emit/threading.rs create mode 100644 crates/victory-shader/src/emit/validator.rs create mode 100644 crates/victory-shader/src/emit/valu_tests.rs create mode 100644 crates/victory-shader/src/emit/waterfall_tests.rs create mode 100644 crates/victory-shader/src/emit/wave.rs create mode 100644 crates/victory-shader/src/emit/wave64_tests.rs create mode 100644 crates/victory-shader/src/gfx10/fields.rs create mode 100644 crates/victory-shader/src/gfx10/mod.rs create mode 100644 crates/victory-shader/src/gfx10/opcodes.rs create mode 100644 crates/victory-shader/src/gfx10/sp3.rs create mode 100644 crates/victory-shader/src/io.rs create mode 100644 crates/victory-shader/src/ir.rs create mode 100644 crates/victory-shader/src/lib.rs create mode 100644 crates/victory-shader/src/native.rs create mode 100644 crates/victory-shader/src/resource.rs create mode 100644 crates/victory-shader/src/spill.rs create mode 100644 crates/victory-shader/src/structure.rs create mode 100644 docs/architecture.md create mode 100644 docs/asset-policy.md create mode 100644 docs/fork-ray-tracing.md create mode 100644 rust-toolchain.toml create mode 100644 rustfmt.toml create mode 100644 tests/fixtures/hle-probe/Cargo.lock create mode 100644 tests/fixtures/hle-probe/Cargo.toml create mode 100644 tests/fixtures/hle-probe/build.rs create mode 100644 tests/fixtures/hle-probe/src/lib.rs create mode 100644 victory.example.toml create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/main.rs create mode 100644 xtask/src/policy.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 000000000..9741f113e --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --quiet --package xtask --" diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..e06f16ef0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# The repository is text-only by policy (see docs/asset-policy.md). +* text=auto eol=lf +*.cmd text eol=crlf +*.ps1 text eol=crlf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 000000000..1b89c975a --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,3 @@ +#!/bin/sh +# Enforces the asset policy on every commit. Install with: cargo xtask install-hooks +exec cargo xtask policy --staged diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..80e6a359e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v5 + # The version and components pinned in rust-toolchain.toml. + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + - name: Clippy + run: cargo clippy --workspace --all-targets --locked -- -D warnings + - name: Clippy, diagnostics build + run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings + # Includes xtask's repository_passes_policy, the asset-policy check. + - name: Tests + run: cargo test --workspace --locked diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..ac9edc3ad --- /dev/null +++ b/.gitignore @@ -0,0 +1,78 @@ +# --------------------------------------------------------------------------- +# RULE #1: nothing from the game (or any other proprietary source) is ever +# committed. +# Everything is built from files the user supplies at runtime. +# This file is the first line of defence; `cargo xtask policy` (also run by +# the pre-commit hook in .githooks/) is the second and is authoritative. +# See docs/asset-policy.md. +# --------------------------------------------------------------------------- + +# Build output +/target/ +/tests/fixtures/*/target/ + +# Local configuration (contains paths to YOUR files) +/victory.toml + +# Places people tend to drop data into. Keep data outside the repo instead. +/game/ +/games/ +/assets/ +/data/ +/dump/ +/dumps/ +/extracted/ +/cache/ +/out/ + +# Executables, libraries, symbols +*.exe +*.dll +*.pdb +*.lib +*.sys +*.obj +*.exp +*.ilk + +# Console packages and containers +*.xvd +*.xvc +*.msixvc +*.xsp +*.cab +*.msi + +# Typical game data (non-exhaustive on purpose; the policy check is an allowlist) +*.bin +# The one exception (docs/asset-policy.md): the BCPack format's constant tables. +!/crates/victory-formats/src/bcpack-tables.bin +*.dat +*.pak +*.rpf +*.dds +*.ktx +*.ktx2 +*.dxbc +*.dxil +*.cso +*.spv +*.wav +*.xma +*.ogg +*.opus +*.mp3 +*.mp4 +*.bik +*.bk2 +*.awc +*.zip +*.7z +*.rar + +# Editor / OS noise +.vs/ +.idea/ +*.swp +Thumbs.db +.DS_Store diff --git a/.victory-root b/.victory-root new file mode 100644 index 000000000..b4827501d --- /dev/null +++ b/.victory-root @@ -0,0 +1,5 @@ +This marker file identifies the root of the VIctory source tree. + +Tools refuse to write game-derived output (caches, converted assets, prepared +images, logs containing game data) anywhere below a directory that contains +this file. See docs/asset-policy.md. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 000000000..bab4a7e1a --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,914 @@ +# This file is automatically @generated by Cargo. +# 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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "object" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11dbdb66876026054e4ffc8d757d862bdf5df5aebd5c0b95a41f17832a94f7d2" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opus-pure" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccd077a3f06e5fc42b04bb59f70d5fe0cdb2c119eef0e240af7e287180ee23ba" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "toml" +version = "1.2.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "victory" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "clap", + "memchr", + "victory-core", + "victory-game", + "victory-hle", + "victory-loader", + "victory-pe", + "victory-shader", + "walkdir", +] + +[[package]] +name = "victory-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "serde", + "tempfile", + "thiserror", + "toml", + "tracing-subscriber", +] + +[[package]] +name = "victory-formats" +version = "0.1.0" + +[[package]] +name = "victory-game" +version = "0.1.0" +dependencies = [ + "memchr", + "miniz_oxide", +] + +[[package]] +name = "victory-gpu" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "miniz_oxide", + "tempfile", + "tracing", + "victory-formats", + "victory-pipeline", + "victory-shader", + "windows", + "windows-sys", +] + +[[package]] +name = "victory-hle" +version = "0.1.0" +dependencies = [ + "miniz_oxide", + "opus-pure", + "tempfile", + "tracing", + "victory-formats", + "victory-gpu", + "victory-loader", + "victory-pe", + "windows", + "windows-core", + "windows-sys", +] + +[[package]] +name = "victory-loader" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "tempfile", + "thiserror", + "tracing", + "victory-core", + "victory-pe", + "windows-sys", +] + +[[package]] +name = "victory-pe" +version = "0.1.0" +dependencies = [ + "object", + "thiserror", +] + +[[package]] +name = "victory-pipeline" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "tempfile", + "tracing", + "victory-core", +] + +[[package]] +name = "victory-shader" +version = "0.1.0" +dependencies = [ + "miniz_oxide", + "thiserror", + "windows", + "windows-sys", +] + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "walkdir", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 000000000..c3efa8f98 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,78 @@ +[workspace] +resolver = "3" +members = ["crates/*", "apps/*", "xtask"] +# Fixtures are standalone crates built on demand by integration tests. +exclude = ["tests/fixtures"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +license = "GPL-3.0-or-later" +publish = false + +[workspace.dependencies] +# Internal crates +victory-core = { path = "crates/victory-core" } +victory-pe = { path = "crates/victory-pe" } +victory-loader = { path = "crates/victory-loader" } +victory-hle = { path = "crates/victory-hle" } +victory-gpu = { path = "crates/victory-gpu" } +victory-shader = { path = "crates/victory-shader" } +victory-formats = { path = "crates/victory-formats" } +victory-pipeline = { path = "crates/victory-pipeline" } +victory-game = { path = "crates/victory-game" } + +# External crates +anyhow = "1.0.104" +thiserror = "2.0.21" +clap = { version = "4.6.9", features = ["derive"] } +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +serde = { version = "1.0.229", features = ["derive"] } +toml = "1.2.2" +object = { version = "0.41.0", default-features = false, features = ["read_core", "pe", "coff", "archive", "std"] } +windows-sys = "0.61.2" +windows = "0.62.2" +windows-core = "0.62.2" +blake3 = "1.8.7" +memchr = "2.8.3" +miniz_oxide = "0.9.1" +walkdir = "2.5.1" +tempfile = "3.27.0" +# Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). +opus-pure = "0.2.4" + +[workspace.lints.rust] +unsafe_op_in_unsafe_fn = "deny" +unused_must_use = "deny" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } +# 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 +# gigabytes of game data; keep them fast even in debug builds. +opt-level = 2 + +[profile.release] +debug = "line-tables-only" + +# The development build: release code generation plus the `diagnostics` +# feature (`cargo build --profile diag -p victory --features diagnostics`), +# kept in its own folder so it does not evict the plain release build. +[profile.diag] +inherits = "release" diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 000000000..c00d99282 --- /dev/null +++ b/README.md @@ -0,0 +1,217 @@ +# victory-gta6 + +A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), the +compatibility layer that runs the Xbox Series build of Grand Theft Auto VI +natively on Windows from files the user supplies. This fork follows upstream +`main` and adds fixes aimed at one goal: getting the game's world to render +correctly and playably on one particular PC. + +**This repository contains no game files, code or assets.** You need your own +copy of the game. It is not affiliated with or endorsed by Rockstar Games or +Take-Two Interactive. + +## Credits + +- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its + contributors is the base of everything here: the loader, the runtime + services, the Direct3D 12 back end and the shader recompiler. Licensed + GPL-3.0-or-later; so is this fork. Upstream's history is kept intact below + the single commit that carries this fork's changes. +- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors + (GPL-2.0-only) was used as a reference for how the same title behaves under + another layer. Fixes inspired by it were written anew in VIctory's code. +- This fork's changes were developed with [Claude Code](https://claude.com/claude-code). + +## Status of this fork (2026-11-25) + +**Not playable yet: 2.5 to 4 frames per second, and shadowed areas are black.** +Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, +32 GB RAM. The Series X profile is used throughout. + +| Stage | State in this fork | +|-------|--------------------| +| Boot, menus, start screen | works, 30 fps (as upstream) | +| Opening cutscene | plays from start to finish, in order, lit: title cards, credits cards, night and dusk shots | +| Saves | the game autosaves a checkpoint and loads it again | +| First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work | +| Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black | +| Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame | +| Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) | + +### What this fork changed (summary) + +Rendering: +- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed. +- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed. +- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer. +- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed. +- Gathers at a named mip level (with and without an offset) read level 0; fixed. +- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed. +- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs. +- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU), and 59 of the 64 trace programs translate. Nothing is lit by it yet. See [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md). + +Speed and memory: +- Waits for memory values, write-watch queries and page queries no longer walk page tables per call. +- Large title buffers get a copy in card memory, with shader writes found by hashing on the card. +- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`VICTORY_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). +- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. +- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. + +- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`VICTORY_SHADER_OPT=0` turns them off). + +Most of the newer speed changes sit behind environment switches that are off +by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`, +`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...). +Each is described in a comment where it is read. + +### Known problems + +- Everything in shadow is black (see above). +- The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. +- Around 24 GB of memory is in use during play. +- A few style lints are switched off for this fork in the workspace `Cargo.toml` until the newer code is tidied. +- Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does. + +Everything below this line is upstream VIctory's own README, unchanged; its +status section describes upstream, not this fork. + +--- + +# VIctory + +Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files +the user supplies. + +The title's x86-64 code runs unchanged inside our process; VIctory supplies +the platform underneath it and converts the title's data, ahead of time where +it can and on first use where it must (shaders). See +[docs/architecture.md](docs/architecture.md). + +## Status (2026-11-23) + +**Not playable yet.** The title boots, runs its menus at its own 30 fps and +loads the world, where rendering fails. + +| Stage | State | +|-------|-------| +| Boot, first-boot screens (accessibility, language, settings, legal) | works, 30 fps | +| Intro video with sound | works | +| Start screen, profile and saves | works | +| Loading into the world (about 50 s) | works | +| The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame | + +Tested on one machine: Windows 11, AMD RX 6700 XT. + +> **Warning.** Entering the world on a real GPU can currently hang it, and +> Windows then resets the display driver (every monitor goes black for a +> moment). To look further, use a diagnostics build with +> `VICTORY_D3D12_WARP=1`, which renders on the software adapter. + +What each part does today and what it still needs: + +| Subsystem | Today | Needs | +|-----------|-------|-------| +| Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | +| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog | Speech is silent; the dialog and relaunch are untested live | +| Network | Offline by design: the title cannot reach the network | – | +| Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | +| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | +| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | +| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | +| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing | +| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | +| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | +| Series S mode | Runs through the menus to the loading screen | The world, as above | + +## Getting started + +Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with +shader model 6.6 (and mesh shaders for the world), Rust (pinned in +`rust-toolchain.toml`). + +The title also needs several GiB of available Windows commit at startup. +Check **Committed** under **Task Manager → Performance → Memory**. If +`crashes.log` reports Windows error 1455, close other applications or increase +the Windows paging file size, then retry. + +```powershell +cargo xtask install-hooks # asset-policy check on every commit +copy victory.example.toml victory.toml # then set your paths (outside the repo) +cargo test --workspace # needs no game data +cargo run -p victory -- config # check your paths +``` + +Run the title: + +```powershell +cargo build --release -p victory +target\release\victory.exe run \ --execute +``` + +The window caption shows the framerate. Saves, settings and `crashes.log` +are kept under the data folder (default `%LOCALAPPDATA%\victory\data`), derived +data under the cache folder. + +Input: XInput pads. With none connected the keyboard is a pad while the +title's window has focus: + +| Keys | Pad | +|------|-----| +| W A S D / I J K L | left / right stick | +| arrows | D-pad | +| Enter, Backspace, X, Y | A, B, X, Y | +| Q / E, Z / C | shoulders, triggers | +| F / H | stick clicks | +| Esc, Tab | Menu, View | + +## Commands + +``` +victory inspect [--imports] [--exports] +victory census [paths...] [--missing] [--strict] +victory lib-exports [--list] +victory shader-info [paths...] [--verbose] [--disasm] +victory translate [paths...] [--validate] [--pipelines] [--list] [--jobs N] +victory run [--execute] [--unimplemented trap|zero] [--strict] + [--console series-x|series-s] [-- ] +victory config +``` + +Logging: `VICTORY_LOG=victory_loader=trace,info` (a release build logs +info and above). + +## Debugging + +A release build has no debugging aids. Build them in with + +```powershell +cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe +``` + +| Variable | Effect | +|----------|--------| +| `VICTORY_LOG=<target>=debug,...` | debug and trace output | +| `VICTORY_STACKS=20,60` | every thread's stack at those seconds | +| `VICTORY_WATCH=<rva>,...` | logs a title u32 when it changes | +| `VICTORY_KEYS=30:Enter,35:X` | presses keys at those seconds, focus or not | +| `VICTORY_CRASH_SAVE=<rva>:<len>,...` | saves title memory to the cache folder on a crash | +| `VICTORY_CAPTURE=<dir>` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=<list>`) | +| `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | +| `VICTORY_D3D12_DEBUG=1` | host debug layer | +| `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | +| `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | +| `VICTORY_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready | +| `VICTORY_SKIP_PIPELINES=<hash>,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | +| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | +| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | +| `VICTORY_SHADER_LOOP_LIMIT=<n>` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | +| `VICTORY_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) | +| `VICTORY_XMA_DUMP=<dir>` | saves the first 32 XMA voices' context and input | + +Every build appends crashes and host GPU failures to `crashes.log` in the +title's data folder. + +## License + +GPL-3.0-or-later. See [LICENSE](LICENSE). diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml new file mode 100644 index 000000000..5fddd5b22 --- /dev/null +++ b/apps/victory/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "victory" +description = "Command-line front end: inspect, census, convert, run." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-core.workspace = true +victory-pe.workspace = true +victory-loader.workspace = true +victory-hle.workspace = true +victory-shader = { workspace = true, features = ["host"] } +victory-game.workspace = true +anyhow.workspace = true +blake3.workspace = true +memchr.workspace = true +clap.workspace = true +walkdir.workspace = true + +[features] +# Debug-level logs and the debugging switches (frame capture, stack dumps, +# the host debug layer, scripted keys). Off in a plain release build. +diagnostics = [ + "victory-core/diagnostics", + "victory-hle/diagnostics", + "victory-loader/diagnostics", + "victory-shader/diagnostics", +] + +[lints] +workspace = true diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs new file mode 100644 index 000000000..93987197d --- /dev/null +++ b/apps/victory/src/census.rs @@ -0,0 +1,124 @@ +//! Which imports do titles need, and which do we cover? + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Read; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use victory_hle::{HleResolver, HostPolicy}; +use victory_loader::Provenance; +use victory_pe::{ImageInfo, ImportSymbol}; + +#[derive(Default)] +struct DllStats { + functions: BTreeSet<ImportSymbol>, + hle: usize, + host: usize, + missing: usize, + images: BTreeSet<PathBuf>, +} + +pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()> { + let paths = crate::default_paths(paths)?; + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + + let mut images = 0usize; + let mut failed = Vec::new(); + let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new(); + let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new(); + + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + let path = entry.path(); + if !entry.file_type().is_file() || !looks_like_pe(path) { + continue; + } + let info = match std::fs::read(path) + .map_err(anyhow::Error::from) + .and_then(|d| ImageInfo::parse(&d).map_err(anyhow::Error::from)) + { + Ok(info) => info, + Err(e) => { + failed.push((path.to_path_buf(), e.to_string())); + continue; + } + }; + images += 1; + for module in info.imports.iter().chain(&info.delay_imports) { + let key = module.dll.to_ascii_lowercase(); + let stats = dlls.entry(key.clone()).or_default(); + stats.images.insert(path.to_path_buf()); + for e in &module.entries { + let class = resolver.classify(&module.dll, &e.symbol); + if class.is_none() { + missing + .entry((key.clone(), e.symbol.to_string())) + .or_default() + .insert(path.to_path_buf()); + } + // Count each dll!function once across all images. + if stats.functions.insert(e.symbol.clone()) { + match class { + Some(Provenance::Hle) => stats.hle += 1, + Some(Provenance::Host) => stats.host += 1, + Some(Provenance::Title) => unreachable!("census maps no title DLLs"), + None => stats.missing += 1, + } + } + } + } + } + } + + println!("{images} images scanned, {} unreadable", failed.len()); + for (p, e) in &failed { + println!(" skipped {}: {e}", p.display()); + } + println!( + "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", + "dll", "funcs", "hle", "host", "missing", "images" + ); + let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0); + for (dll, s) in &dlls { + println!( + "{dll:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", + s.functions.len(), + s.hle, + s.host, + s.missing, + s.images.len() + ); + f += s.functions.len(); + h += s.hle; + o += s.host; + m += s.missing; + } + println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL"); + + if list_missing { + let mut rows: Vec<_> = missing.into_iter().collect(); + rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0))); + println!("\nmissing (by number of images using it)"); + for ((dll, sym), users) in rows { + println!(" {:>4} {dll}!{sym}", users.len()); + } + } + Ok(()) +} + +/// Cheap pre-filter: an `MZ` header, regardless of extension (console +/// packages do not always use .exe/.dll). +fn looks_like_pe(path: &Path) -> bool { + let mut magic = [0u8; 2]; + std::fs::File::open(path) + .and_then(|mut f| f.read_exact(&mut magic)) + .is_ok() + && &magic == b"MZ" +} diff --git a/apps/victory/src/inspect.rs b/apps/victory/src/inspect.rs new file mode 100644 index 000000000..3991d704a --- /dev/null +++ b/apps/victory/src/inspect.rs @@ -0,0 +1,153 @@ +use std::collections::BTreeMap; +use std::path::Path; + +use anyhow::{Context, Result}; +use victory_pe::implib::ImportLibrary; +use victory_pe::{ImageInfo, layout}; + +pub fn run(file: &Path, list_imports: bool, list_exports: bool) -> Result<()> { + let data = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?; + let info = ImageInfo::parse(&data).with_context(|| format!("parsing {}", file.display()))?; + + println!("file {}", file.display()); + println!("blake3 {}", blake3::hash(&data).to_hex()); + if let Some(cv) = &info.codeview { + println!("pdb {} (key {})", cv.pdb_path, cv.symbol_key()); + } + println!( + "kind {}", + if info.is_dll() { "dll" } else { "exe" } + ); + println!( + "subsystem {} ({})", + info.subsystem, + info.subsystem_name() + ); + println!( + "image base {:#x} size {:#x}", + info.image_base, info.size_of_image + ); + println!("entry rva {:#x}", info.entry_rva); + println!( + "stack reserve {:#x} commit {:#x}", + info.stack_reserve, info.stack_commit + ); + println!( + "dll flags {:#06x}{}", + info.dll_characteristics, + dll_flags(info.dll_characteristics) + ); + println!( + "relocations {} exception table {} load config {}", + yes(info.has_relocations), + yes(info.has_exception_table), + yes(info.has_load_config) + ); + if let Some(tls) = &info.tls { + println!("tls {} callback(s)", tls.callback_rvas.len()); + } + + println!("\nsections"); + for s in &info.sections { + println!( + " {:<8} rva {:#010x} vsize {:#010x} raw {:#010x} flags {:#010x}", + s.name.trim_end_matches('\0'), + s.rva, + s.virtual_size, + s.file_size, + s.characteristics + ); + } + + println!( + "\nimports {} functions from {} DLLs", + info.import_count(), + info.imports.len() + ); + for m in &info.imports { + println!(" {:<48} {:>5}", m.dll, m.entries.len()); + if list_imports { + for e in &m.entries { + println!(" {}", e.symbol); + } + } + } + if !info.delay_imports.is_empty() { + println!("\ndelay-load imports"); + for m in &info.delay_imports { + println!(" {:<48} {:>5}", m.dll, m.entries.len()); + if list_imports { + for e in &m.entries { + println!(" {}", e.symbol); + } + } + } + } + + println!("\nexports {}", info.exports.len()); + if list_exports { + for e in &info.exports { + let name = e.name.as_deref().unwrap_or("(by ordinal)"); + match (&e.rva, &e.forward) { + (_, Some(fwd)) => println!(" {:>5} {name} -> {fwd}", e.ordinal), + (Some(rva), _) => println!(" {:>5} {name} {rva:#x}", e.ordinal), + _ => println!(" {:>5} {name}", e.ordinal), + } + } + } + Ok(()) +} + +pub fn lib_exports(lib: &Path, list: bool) -> Result<()> { + let data = std::fs::read(lib).with_context(|| format!("reading {}", lib.display()))?; + let parsed = + ImportLibrary::parse(&data).with_context(|| format!("parsing {}", lib.display()))?; + let mut by_dll: BTreeMap<String, Vec<String>> = BTreeMap::new(); + for i in &parsed.imports { + by_dll + .entry(i.dll.to_ascii_lowercase()) + .or_default() + .push(i.export.to_string()); + } + println!( + "{} exports from {} DLLs ({} other members)", + parsed.imports.len(), + by_dll.len(), + parsed.other_members + ); + for (dll, names) in &by_dll { + println!("{dll:<60} {:>5}", names.len()); + if list { + for n in names { + println!(" {n}"); + } + } + } + Ok(()) +} + +fn yes(b: bool) -> &'static str { + if b { "yes" } else { "no" } +} + +fn dll_flags(v: u16) -> String { + use layout::dll_flags::*; + let names = [ + (HIGH_ENTROPY_VA, "high-entropy-va"), + (DYNAMIC_BASE, "dynamic-base"), + (FORCE_INTEGRITY, "force-integrity"), + (NX_COMPAT, "nx"), + (APPCONTAINER, "appcontainer"), + (GUARD_CF, "cfg"), + ]; + let set: Vec<_> = names + .iter() + .filter(|(f, _)| v & f != 0) + .map(|(_, n)| *n) + .collect(); + if set.is_empty() { + String::new() + } else { + format!(" ({})", set.join(", ")) + } +} diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs new file mode 100644 index 000000000..842ce7739 --- /dev/null +++ b/apps/victory/src/main.rs @@ -0,0 +1,222 @@ +//! `victory`: the command-line front end. +//! +//! Every command reads the user's own files and writes only to stdout or to +//! the user's cache directory (outside the repository). + +mod census; +mod inspect; +mod run; +mod shader; +mod translate; + +use std::path::PathBuf; + +use anyhow::Result; +use clap::{Parser, Subcommand, ValueEnum}; + +#[derive(Parser)] +#[command( + name = "victory", + version, + about = "Run an Xbox Series title natively on Windows" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Summarise one PE image: headers, sections, imports, TLS, build id. + Inspect { + file: PathBuf, + /// List every imported function. + #[arg(long)] + imports: bool, + /// List every exported function. + #[arg(long)] + exports: bool, + }, + /// Aggregate the imports of every PE image under the given paths and + /// show which ones our runtime covers. Defaults to the configured + /// game and test-title directories. + Census { + paths: Vec<PathBuf>, + /// Do not count host pass-through as covered. + #[arg(long)] + strict: bool, + /// List every missing `dll!function`, most used first. + #[arg(long)] + missing: bool, + }, + /// List the `dll!export` pairs an import library describes. + LibExports { + lib: PathBuf, + /// List every export, not just per-DLL counts. + #[arg(long)] + list: bool, + }, + /// Find shader containers in files or directories (also inside engine + /// archives, if uncompressed) and report their layout. + ShaderInfo { + paths: Vec<PathBuf>, + /// Print one line per container found. + #[arg(long)] + verbose: bool, + /// Also list the decoded native instructions (implies --verbose). + #[arg(long)] + disasm: bool, + }, + /// Run every shader found (containers, SGD5 files) through the + /// translator and report what it cannot handle yet. + Translate { + paths: Vec<PathBuf>, + /// Check emitted DXIL with dxil.dll's validator (`VICTORY_DXIL`, + /// else the newest Windows SDK's). + #[arg(long)] + validate: bool, + /// Also create a host D3D12 pipeline for each emitted shader. + #[arg(long)] + pipelines: bool, + /// Print one line per program and outcome. + #[arg(long)] + list: bool, + /// Worker threads (default: every logical core). + #[arg(long)] + jobs: Option<usize>, + }, + /// Prepare, map and bind a title executable; with --execute, run it. + Run { + exe: PathBuf, + /// What unimplemented imports do when called. + #[arg(long, value_enum, default_value_t = Unimplemented::Trap)] + unimplemented: Unimplemented, + /// Disable host pass-through (everything must be implemented by us). + #[arg(long)] + strict: bool, + /// Actually start the title. Without it, stop after binding. + #[arg(long)] + execute: bool, + /// The console model the title sees (device type, memory). + #[arg(long, value_enum, default_value_t = Console::SeriesX)] + console: Console, + /// Arguments for the title, after `--` (it reads the whole command + /// line; a title that relaunches itself passes some). + #[arg(last = true)] + title_args: Vec<String>, + }, + /// Show the resolved configuration and check it. + Config, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Unimplemented { + Trap, + Zero, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Console { + SeriesX, + SeriesS, +} + +fn main() -> Result<()> { + victory_core::logging::init("info"); + // The audio recorder `run` starts for `VICTORY_AUDIO_CAPTURE`. + #[cfg(all(windows, feature = "diagnostics"))] + if victory_hle::modules::audio::capture::child() { + return Ok(()); + } + let cli = Cli::parse(); + match cli.command { + Command::Inspect { + file, + imports, + exports, + } => inspect::run(&file, imports, exports), + Command::Census { + paths, + strict, + missing, + } => census::run(paths, strict, missing), + Command::LibExports { lib, list } => inspect::lib_exports(&lib, list), + Command::ShaderInfo { + paths, + verbose, + disasm, + } => shader::run(paths, verbose || disasm, disasm), + Command::Translate { + paths, + validate, + pipelines, + list, + jobs, + } => { + // `VICTORY_VIEW_LIMIT=<null slot>`: 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, + strict, + execute, + console, + title_args: _, + } => run::run(&exe, unimplemented, strict, execute, console), + Command::Config => show_config(), + } +} + +fn show_config() -> Result<()> { + let cfg = victory_core::Config::load()?; + let status = |p: &Option<PathBuf>| match p { + Some(p) if p.exists() => format!("{}", p.display()), + Some(p) => format!("{} (does not exist)", p.display()), + None => "(not set)".to_owned(), + }; + println!( + "config file : {}", + cfg.source + .as_ref() + .map_or("(none)".into(), |p| p.display().to_string()) + ); + println!("game_dir : {}", status(&cfg.game_dir)); + println!("cache_dir : {}", cfg.cache_dir.display()); + println!("data_dir : {}", cfg.data_dir.display()); + for t in &cfg.test_titles { + println!("test_title : {}", status(&Some(t.clone()))); + } + for p in cfg + .game_dir + .iter() + .chain(&cfg.test_titles) + .chain([&cfg.cache_dir, &cfg.data_dir]) + { + if let Err(e) = victory_core::ensure_outside_repo(p) { + println!("POLICY VIOLATION: {e}"); + } + } + Ok(()) +} + +/// Paths given on the command line, or the configured game + test titles. +pub(crate) fn default_paths(paths: Vec<PathBuf>) -> Result<Vec<PathBuf>> { + if !paths.is_empty() { + return Ok(paths); + } + let cfg = victory_core::Config::load()?; + let all: Vec<PathBuf> = cfg.game_dir.into_iter().chain(cfg.test_titles).collect(); + anyhow::ensure!( + !all.is_empty(), + "no paths given and none configured (see victory.example.toml)" + ); + Ok(all) +} diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs new file mode 100644 index 000000000..a73aecbea --- /dev/null +++ b/apps/victory/src/run.rs @@ -0,0 +1,344 @@ +use std::path::Path; + +use anyhow::{Context, Result}; + +use crate::{Console, Unimplemented}; + +#[cfg(windows)] +pub fn run( + exe: &Path, + unimplemented: Unimplemented, + strict: bool, + execute: bool, + console: Console, +) -> Result<()> { + use std::sync::Arc; + use victory_hle::{HleResolver, HostPolicy}; + use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls}; + + // A title that relaunched itself: the old process must be gone first. + victory_hle::modules::lifecycle::wait_for_previous(); + let cfg = victory_core::Config::load()?; + let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; + let prepared = victory_loader::prepare(&original)?; + let hash = prepared.original_hash.to_hex(); + match victory_game::identify(&hash) { + Some(build) => println!("build {} ({hash})", build.label), + None => println!("build unknown ({hash})"), + } + + 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 Grand Theft Auto VI, 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!( + "mapped at {:#x} (preferred {:#x})", + image.base(), + image.info().image_base + ); + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + let wanted = |dll: &str| title_dll(&resolver.host, dll); + let title_dir = exe.parent().unwrap_or(Path::new(".")); + // A missing manifest leaves id 0 and no storage quota. + let manifest = + std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default(); + let title = victory_hle::runtime::Title::from_manifest(&manifest); + let storage = cfg.data_subdir(&format!("{:08X}/storage", title.id))?; + println!( + "title {:08X}, storage {} ({} MB)", + title.id, + storage.display(), + title.storage_bytes >> 20 + ); + // The console's fixed drives: the package as `G:`, temporary files `T:`. + victory_hle::modules::files::mount_at('G', title_dir); + let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?; + victory_hle::modules::files::mount_at('T', &temp); + victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title }); + victory_hle::console::set(match console { + Console::SeriesX => victory_hle::console::Console::SeriesX, + Console::SeriesS => victory_hle::console::Console::SeriesS, + }); + println!("console {}", victory_hle::console::current().name()); + let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?; + for (name, dll) in &dlls { + println!("title dll {name} at {:#x}", dll.base()); + victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); + } + + let policy = match unimplemented { + Unimplemented::Trap => UnimplementedPolicy::Trap, + Unimplemented::Zero => UnimplementedPolicy::ReturnZero, + }; + let with_dlls = WithTitleDlls { + inner: &resolver, + dlls: &dlls, + }; + let show = |name: &str, report: BindReport| { + println!( + "bound {name}: {} hle, {} host, {} title, {} missing", + report.hle, + report.host, + report.title, + report.missing.len() + ); + for m in &report.missing { + println!(" missing {}!{}", m.dll, m.symbol); + } + }; + for (name, dll) in &dlls { + show(name, dll.bind_imports(&with_dlls, policy)?); + } + let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); + show(&exe_name, image.bind_imports(&with_dlls, policy)?); + if !execute { + println!("not executing (pass --execute to start the title)"); + return Ok(()); + } + victory_loader::report_crashes(); + victory_loader::log_crashes_to(temp.with_file_name("crashes.log")); + victory_hle::runtime::use_console_timers(); + #[cfg(feature = "diagnostics")] + diagnostics(&image, &cfg); + let late = LateDlls { + host: resolver.host.clone(), + title_dir: title_dir.to_owned(), + cache_dir: images, + policy, + mapped: std::sync::Mutex::new(dlls.clone()), + lock: LoaderLock::default(), + }; + victory_hle::runtime::set_title_dll_loader(Box::new(move |file| { + late.load(file, show).map_err(|e| format!("{e:#}")) + })); + // SAFETY: imports are bound; from here on we run title code. + let main = unsafe { Arc::new(image).spawn_main(dlls)? }; + let code = main + .join() + .map_err(|_| anyhow::anyhow!("title main thread panicked"))??; + println!("title exited with {code}"); + Ok(()) +} + +/// The debugging aids (README): scheduled stack dumps, watched values and +/// memory saved on a crash. +#[cfg(all(windows, feature = "diagnostics"))] +fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) { + victory_loader::dump_stacks_on_schedule(); + victory_hle::modules::audio::capture::start(); + watch(image.base(), image.info().size_of_image as usize); + // Debugging aid: `VICTORY_CRASH_SAVE=<rva>:<len>,...` (hex) writes those + // title ranges to `crash-<rva>.bin` in the cache dir on a crash. + let size = image.info().size_of_image as usize; + let ranges = std::env::var("VICTORY_CRASH_SAVE").unwrap_or_default(); + let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok(); + victory_loader::save_on_crash( + ranges + .split(',') + .filter_map(|r| r.split_once(':')) + .filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?))) + .filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size)) + .map(|(rva, len)| { + let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin")); + (image.base() + rva, len, file) + }) + .collect(), + ); +} + +/// Debugging aid: `VICTORY_WATCH=<rva>,...` (hex) logs the u32 at each +/// title+rva whenever it changes, polled every 5 ms (an engine's state, say). +#[cfg(all(windows, feature = "diagnostics"))] +fn watch(base: usize, size: usize) { + let Ok(list) = std::env::var("VICTORY_WATCH") else { + return; + }; + let rvas: Vec<usize> = list + .split(',') + .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok()) + .filter(|&rva| rva + 4 <= size) + .collect(); + std::thread::spawn(move || { + let mut seen = vec![None; rvas.len()]; + loop { + for (&rva, seen) in rvas.iter().zip(&mut seen) { + // SAFETY: four bytes inside the mapped image, checked above. + let value = unsafe { ((base + rva) as *const u32).read_volatile() }; + if *seen != Some(value) { + eprintln!("VIctory: title+{rva:#x} = {value:#x}"); + *seen = Some(value); + } + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + }); +} + +/// DLLs the host or our runtime provide are never taken from the title. +#[cfg(windows)] +fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { + !host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll)) +} + +/// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports, +/// e.g. Grand Theft Auto VI's upscaler behind its FidelityFX loader. +#[cfg(windows)] +struct LateDlls { + host: victory_hle::HostPolicy, + title_dir: std::path::PathBuf, + cache_dir: std::path::PathBuf, + policy: victory_loader::UnimplementedPolicy, + /// Every title DLL mapped so far, to bind new ones against. + mapped: std::sync::Mutex<Vec<(String, victory_loader::LoadedImage)>>, + lock: LoaderLock, +} + +#[cfg(windows)] +impl LateDlls { + /// Every `LoadLibrary` of the title comes here first. Returns a title + /// image called `file`, mapping it and the title DLLs it needs first, + /// binding them and running their `DllMain` on the calling thread, as + /// the Windows loader would; `None` if `file` is no title image. + fn load( + &self, + file: &str, + show: impl Fn(&str, victory_loader::BindReport), + ) -> Result<Option<usize>> { + use victory_hle::runtime::{forget_image, image_named, set_image_path}; + // Waits while another thread initialises a DLL; a `DllMain` that + // loads another DLL re-enters. + self.lock.hold(|| { + if let Some(base) = image_named(file) { + return Ok(Some(base)); + } + let new = { + let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner()); + let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none(); + let new = victory_loader::load_title_dll( + file, + &self.title_dir, + &self.cache_dir, + &wanted, + )?; + let hle = victory_hle::HleResolver::new(self.host.clone()); + let old = victory_loader::WithTitleDlls { + inner: &hle, + dlls: &mapped, + }; + let resolver = victory_loader::WithTitleDlls { + inner: &old, + dlls: &new, + }; + for (name, dll) in &new { + println!( + "title dll {name} at {:#x} (loaded by the title)", + dll.base() + ); + show(name, dll.bind_imports(&resolver, self.policy)?); + set_image_path(dll.base(), &self.title_dir.join(name)); + } + // Visible before their `DllMain`s run, which may load more. + mapped.extend(new.iter().cloned()); + new + }; + let failed = new.iter().enumerate().find_map(|(i, (name, dll))| { + // SAFETY: bound above, dependencies attached first. + let attached = unsafe { dll.attach() }; + attached + .err() + .map(|e| (i, e.context(format!("attaching {name}")))) + }); + let Some((i, error)) = failed else { + return Ok(new.last().map(|(_, dll)| dll.base())); + }; + // As `LoadLibrary` does when a `DllMain` fails: detach what this + // load attached (the failed one too) and unmap all of it. + let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect(); + self.mapped + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|(_, d)| !bases.contains(&d.base())); + for (_, done) in new[..=i].iter().rev() { + // SAFETY: attached (or failing to) on this thread just now. + unsafe { done.detach() }; + } + for (_, dll) in new { + forget_image(dll.base()); + // SAFETY: detached, and no title code holds it yet. + unsafe { dll.unload() }; + } + Err(error) + }) + } +} + +/// The Windows loader lock's shape: one thread at a time, re-entered by +/// the thread that holds it. +#[cfg(windows)] +#[derive(Default)] +struct LoaderLock { + owner: std::sync::Mutex<(Option<std::thread::ThreadId>, usize)>, + free: std::sync::Condvar, +} + +#[cfg(windows)] +impl LoaderLock { + fn hold<T>(&self, f: impl FnOnce() -> T) -> T { + let me = std::thread::current().id(); + let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut owner = lock(); + while owner.0.is_some_and(|o| o != me) { + owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner()); + } + *owner = (Some(me), owner.1 + 1); + } + let result = f(); + let mut owner = lock(); + owner.1 -= 1; + if owner.1 == 0 { + owner.0 = None; + self.free.notify_one(); + } + result + } +} + +#[cfg(all(test, windows))] +mod tests { + use std::sync::{Arc, Mutex}; + + #[test] + fn loader_lock_is_reentrant_and_exclusive() { + let lock = Arc::new(super::LoaderLock::default()); + assert_eq!(lock.hold(|| lock.hold(|| 7)), 7); + let order = Arc::new(Mutex::new(Vec::new())); + let other = lock.hold(|| { + let (theirs, their_order) = (lock.clone(), order.clone()); + let other = std::thread::spawn(move || { + theirs.hold(|| their_order.lock().unwrap().push(2)); + }); + std::thread::sleep(std::time::Duration::from_millis(50)); + order.lock().unwrap().push(1); + other + }); + other.join().unwrap(); + assert_eq!(*order.lock().unwrap(), [1, 2]); + } +} + +#[cfg(not(windows))] +pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> { + anyhow::bail!("running titles requires Windows") +} diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs new file mode 100644 index 000000000..49180eac3 --- /dev/null +++ b/apps/victory/src/shader.rs @@ -0,0 +1,227 @@ +//! 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}; + +/// 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<Cow<'_, [u8]>> { + 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<Source<'_>> { + let mut out: Vec<Source<'_>> = 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 { + containers: usize, + with_dxil_part: usize, + with_bitcode: usize, + standard_layout: usize, + xdat: usize, + xbop: usize, + kinds: BTreeMap<String, usize>, + with_native: usize, + native_stages: BTreeMap<HwStage, usize>, + native_errors: BTreeMap<String, usize>, + decoded: usize, + instructions: usize, + unnamed: BTreeMap<String, usize>, + decode_errors: BTreeMap<&'static str, usize>, + files_with_shaders: usize, +} + +pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> { + let paths = crate::default_paths(paths)?; + let mut t = Totals::default(); + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() { + 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; + 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; + } + 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}"); + } + } + } + t.files_with_shaders += usize::from(found_here > 0); + } + } + println!( + "containers found {} (in {} files)", + t.containers, t.files_with_shaders + ); + println!(" with DXIL part {}", t.with_dxil_part); + println!(" with LLVM bitcode {}", t.with_bitcode); + println!(" PC-standard layout {}", t.standard_layout); + println!(" XDAT prefix {}", t.xdat); + println!(" xbop trailer {}", t.xbop); + for (k, n) in &t.kinds { + println!(" {k:<20} {n}"); + } + println!(" with native code {}", t.with_native); + for (stage, n) in &t.native_stages { + println!(" {:<18} {n}", format!("{stage:?}")); + } + for (e, n) in &t.native_errors { + println!(" native unreadable {n}: {e}"); + } + if t.with_native > 0 { + println!( + " decoded programs {} ({} instructions)", + t.decoded, t.instructions + ); + for (e, n) in &t.decode_errors { + println!(" decode failed {n}: {e}"); + } + let mut unnamed: Vec<_> = t.unnamed.iter().collect(); + unnamed.sort_by_key(|&(_, n)| std::cmp::Reverse(*n)); + for (op, n) in unnamed.iter().take(10) { + println!(" opcode not in table {op} x{n}"); + } + } + if t.containers == 0 { + println!("(none found: shaders may sit in compressed or encrypted archives)"); + } + Ok(()) +} + +fn format_instruction(i: &Instruction, wave64: bool) -> String { + let words: Vec<_> = i.words.iter().map(|w| format!("{w:08X}")).collect(); + let text = match i.name() { + Some(_) => i.text(wave64), + None => format!("<{:?} {:#x}>", i.encoding, i.opcode), + }; + format!(" {:06x}: {:<44} {text}", i.offset, words.join(" ")) +} diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs new file mode 100644 index 000000000..1d13ae2cf --- /dev/null +++ b/apps/victory/src/translate.rs @@ -0,0 +1,785 @@ +//! The offline batch: every shader found goes through the translator, and +//! what it cannot handle yet is tallied (decision 0003). + +use std::collections::{BTreeMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use anyhow::Result; +use victory_shader::emit::host::{self, Host}; +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::{MAX_FILE, Source, sources}; + +#[derive(Default)] +struct Tally { + containers: usize, + duplicates: usize, + programs: usize, + translated: usize, + instructions: usize, + structured: usize, + vector: usize, + guarded: usize, + /// Guards that read a mask the pass cannot see into. + opaque: usize, + lane_branches: usize, + uniform_branches: usize, + tracked: usize, + loaded: usize, + built: usize, + constant: usize, + /// Descriptors and scalar accesses with a computed address term. + dynamic: usize, + scalar: usize, + used: usize, + /// Used-resource entries whose root parameter no descriptor traces + /// to, by resource and root type. + untraced_used: BTreeMap<String, usize>, + /// Root parameters descriptors trace to that no used entry names. + unlisted: usize, + /// Vertex and pixel programs, and those whose I/O was raised. + io_programs: usize, + io_raised: usize, + interpolated: usize, + vertex_values: usize, + /// Exports by target kind. + exports: BTreeMap<&'static str, usize>, + /// Exports still packed as f16 pairs after the export patch. + compressed: usize, + /// Vertex and pixel programs every earlier stage handled, and how far + /// emission got with them. + emit_programs: usize, + emitted: usize, + validated: usize, + pipelines: usize, + /// The same for compute programs. + cs_programs: usize, + cs_emitted: usize, + cs_validated: usize, + cs_pipelines: usize, + /// The same for mesh programs. + ms_programs: usize, + ms_emitted: usize, + ms_validated: usize, + ms_pipelines: usize, + /// Reason → programs stopped by it, and the first one. + failed: BTreeMap<String, (usize, String)>, + /// With `--list`: one line per program and outcome. + list: bool, + lines: Vec<String>, +} + +impl Tally { + fn fail(&mut self, reason: String, example: impl FnOnce() -> String) { + if self.list { + let e = example(); + self.lines.push(format!("{e} {reason}")); + self.failed.entry(reason).or_insert((0, e)).0 += 1; + return; + } + self.failed + .entry(reason) + .or_insert_with(|| (0, example())) + .0 += 1; + } + + fn merge(&mut self, other: Tally) { + self.containers += other.containers; + self.duplicates += other.duplicates; + self.programs += other.programs; + self.translated += other.translated; + self.instructions += other.instructions; + self.structured += other.structured; + self.vector += other.vector; + self.guarded += other.guarded; + self.opaque += other.opaque; + self.lane_branches += other.lane_branches; + self.uniform_branches += other.uniform_branches; + self.tracked += other.tracked; + self.loaded += other.loaded; + self.built += other.built; + self.constant += other.constant; + self.dynamic += other.dynamic; + self.scalar += other.scalar; + self.used += other.used; + for (k, n) in other.untraced_used { + *self.untraced_used.entry(k).or_default() += n; + } + self.unlisted += other.unlisted; + self.io_programs += other.io_programs; + self.io_raised += other.io_raised; + self.interpolated += other.interpolated; + self.vertex_values += other.vertex_values; + self.compressed += other.compressed; + self.emit_programs += other.emit_programs; + self.emitted += other.emitted; + self.validated += other.validated; + self.pipelines += other.pipelines; + self.cs_programs += other.cs_programs; + self.cs_emitted += other.cs_emitted; + self.cs_validated += other.cs_validated; + self.cs_pipelines += other.cs_pipelines; + self.ms_programs += other.ms_programs; + self.ms_emitted += other.ms_emitted; + self.ms_validated += other.ms_validated; + self.ms_pipelines += other.ms_pipelines; + for (k, n) in other.exports { + *self.exports.entry(k).or_default() += n; + } + self.lines.extend(other.lines); + for (reason, (n, example)) in other.failed { + self.failed.entry(reason).or_insert((0, example)).0 += n; + } + } +} + +/// Emitted shaders by label, shared between threads. +type Kept = std::sync::Arc<Mutex<Vec<(String, emit::HostShader)>>>; + +/// The optional checks after emission, one set per thread. +struct Checks { + /// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings), + /// kept to build those pipelines after the walk. + keep: Option<Kept>, + validator: Option<Validator>, + host: Option<(Host, emit::HostShader)>, +} + +pub fn run( + paths: Vec<PathBuf>, + validate: bool, + pipelines: bool, + list: bool, + jobs: Option<usize>, +) -> Result<()> { + let paths = crate::default_paths(paths)?; + // `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)?; + println!( + "validator {}", + dll.as_ref() + .map_or("dxil.dll".into(), |p| p.display().to_string()) + ); + } + if pipelines { + Host::new(false).map_err(anyhow::Error::msg)?; + } + let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS") + .unwrap_or_default() + .split(',') + .filter_map(|p| p.split_once('+')) + .map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned())) + .collect(); + 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())); + let seen = Mutex::new(HashSet::new()); + let total = Mutex::new(Tally::default()); + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + 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); + }); + } + }); + } + } + let t = total.into_inner().unwrap_or_else(|e| e.into_inner()); + println!( + "containers {} ({} duplicates skipped)", + t.containers, t.duplicates + ); + println!( + "programs {} translated of {} ({} IR instructions)", + t.translated, t.programs, t.instructions + ); + println!( + "structured {} of {} ({} vector instructions, {} guarded, {} on opaque masks; \ + branches {} per lane, {} uniform)", + t.structured, + t.translated, + t.vector, + t.guarded, + t.opaque, + t.lane_branches, + t.uniform_branches + ); + println!( + "resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \ + {} scalar accesses; {} with a computed term)", + t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic + ); + println!( + " used-resource entries {}: {} not traced {:?}; {} traced parameters not listed", + t.used, + t.untraced_used.values().sum::<usize>(), + t.untraced_used, + t.unlisted + ); + println!( + "I/O {} of {} vertex and pixel programs raised ({} interpolations, \ + {} vertex values; exports {:?}, {} still f16 pairs)", + t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed + ); + println!( + "DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines", + t.emitted, t.emit_programs, t.validated, t.pipelines + ); + println!( + " {} emitted of {} compute programs; {} validated, {} pipelines", + t.cs_emitted, t.cs_programs, t.cs_validated, t.cs_pipelines + ); + println!( + " {} emitted of {} mesh programs; {} validated, {} pipelines", + t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines + ); + if !pairs.is_empty() { + 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}"); + } + } + let mut lines = t.lines; + lines.sort(); + for l in lines { + println!("{l}"); + } + let mut failed: Vec<_> = t.failed.into_iter().collect(); + failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n)); + for (reason, (n, example)) in failed { + println!(" {n:>7} {reason} (e.g. {example})"); + } + Ok(()) +} + +fn translate( + source: &Source, + path: &Path, + seen: &Mutex<HashSet<blake3::Hash>>, + t: &mut Tally, + checks: &mut Checks, +) { + let example = || format!("{}{}", path.display(), source.label()); + 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=<hash prefix>,...` translates + // those containers alone. + static ONLY: std::sync::OnceLock<Vec<String>> = 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); + }; + let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { + return t.fail("no DXIL part (SM5 or older)".into(), example); + }; + // `~`: 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=<dir>;<text>|<text>...`: 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=<dir>`: 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<BTreeMap<String, usize>> = 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<NativeProgram>, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) { + for p in programs { + t.programs += 1; + match victory_shader::spill::build(&p) { + Ok(program) => { + t.translated += 1; + t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>(); + // Per-lane descriptors are traced on the per-lane form; its + // failure is listed after the resources' and I/O's. + let structured = structure::structure(&program); + let lanes = structured.as_ref().ok(); + let res = match resource::track(&program, &p.layout, p.stage, lanes) { + Ok(r) => { + tally_resources(&p, &r, t); + Some(r) + } + Err(ShaderError::Unsupported { offset, what }) => { + t.fail(format!("resources: {what}"), || { + format!("{} {:?} at {offset:#x}", example(), p.stage) + }); + None + } + Err(e) => { + t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)); + None + } + }; + let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps); + let compute = p.stage == HwStage::Cs; + let mut raised = None; + if graphics || compute || p.stage == HwStage::Ms { + t.io_programs += usize::from(graphics); + match io::raise(&program, &p) { + Ok(r) => { + if graphics { + tally_io(&r, t); + } + raised = Some(r); + } + Err(ShaderError::Unsupported { offset, what }) => t + .fail(format!("I/O: {what}"), || { + format!("{} {:?} at {offset:#x}", example(), p.stage) + }), + Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)), + } + } + let structured = match structured { + Ok(s) => { + tally_structured(&program, &s, t); + Some(s) + } + Err(e) => { + let reason = match e { + ShaderError::Unsupported { what, .. } => format!("structure: {what}"), + ShaderError::Isa { reason, .. } => format!("structure: {reason}"), + e => e.to_string(), + }; + t.fail(reason, || format!("{} {:?}", example(), p.stage)); + None + } + }; + 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(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); + } + Err(ShaderError::Unsupported { offset, what }) => t + .fail(format!("emit: {what}"), || { + format!("{} at {offset:#x}", label()) + }), + Err(e) => t.fail(format!("emit: {e}"), label), + } + } + } + Err(e) => { + let reason = match e { + ShaderError::Unsupported { what, .. } => format!("unsupported: {what}"), + e => e.to_string(), + }; + t.fail(reason, || format!("{} {:?}", example(), p.stage)); + } + } + } +} + +/// `VICTORY_SHADER_CENSUS=<file>`: 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<Option<Mutex<std::fs::File>>> = 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, + t: &mut Tally, + checks: &mut Checks, + label: impl Fn() -> String, +) { + if let Some(keep) = &checks.keep { + lock(keep).push((label(), shader.clone())); + } + // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. + if t.list + && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") + { + let name: String = label() + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) + .collect(); + let _ = std::fs::write( + format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]), + &shader.dxil, + ); + } + if let Some((h, stub_ps)) = &checks.host { + let made = match shader.stage { + HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop), + HwStage::Cs => h.compute_pipeline(&shader).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)), + }; + match made { + Ok(()) => { + *counter(t, shader.stage, 3) += 1; + if t.list { + t.lines.push(format!("{} pipeline created", label())); + } + } + Err(e) => t.fail(format!("pipeline: {e}"), &label), + } + } + let Some(v) = checks.validator.as_mut() else { + return; + }; + match v.validate(&mut shader.dxil) { + Ok(()) => { + *counter(t, shader.stage, 2) += 1; + if t.list { + t.lines.push(format!("{} validated", label())); + } + } + Err(text) => { + let first = text + .lines() + .find(|l| l.contains("error")) + .unwrap_or(text.lines().next().unwrap_or("")) + .to_owned(); + if let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") { + let n = t + .failed + .get(&format!("validator: {first}")) + .map_or(0, |f| f.0); + if n < 3 { + let name = format!( + "{dir}/{}_{n}", + first + .chars() + .filter(char::is_ascii_alphanumeric) + .take(40) + .collect::<String>() + ); + let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil); + let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label())); + } + } + t.fail(format!("validator: {first}"), label); + } + } +} + +/// Emission counts of `stage`'s kind: 0 programs, 1 emitted, 2 validated, +/// 3 pipelines. +fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize { + let [a, b, c, d] = match stage { + HwStage::Cs => [ + &mut t.cs_programs, + &mut t.cs_emitted, + &mut t.cs_validated, + &mut t.cs_pipelines, + ], + HwStage::Ms => [ + &mut t.ms_programs, + &mut t.ms_emitted, + &mut t.ms_validated, + &mut t.ms_pipelines, + ], + _ => [ + &mut t.emit_programs, + &mut t.emitted, + &mut t.validated, + &mut t.pipelines, + ], + }; + [a, b, c, d].into_iter().nth(k).expect("0 to 3") +} + +fn tally_io(r: &io::Io, t: &mut Tally) { + t.io_raised += 1; + for (_, i) in &r.interps { + match i { + io::Interp::Interpolated { .. } => t.interpolated += 1, + io::Interp::Vertex { .. } => t.vertex_values += 1, + io::Interp::Weighted { .. } => t.interpolated += 1, + } + } + for e in &r.exports { + let kind = match e.target { + io::Target::Color(_) => "color", + io::Target::Depth => "depth", + io::Target::Null => "null", + io::Target::Position(_) => "position", + io::Target::Param { .. } => "param", + io::Target::Unread => "unread param", + io::Target::Primitive => "primitive", + io::Target::PrimitiveParam { .. } => "primitive param", + }; + *t.exports.entry(kind).or_default() += 1; + t.compressed += usize::from(e.compressed); + } +} + +fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { + t.tracked += 1; + t.scalar += r.scalar.len(); + t.dynamic += r.scalar.iter().filter(|s| s.1.dynamic.is_some()).count(); + let address = |load| r.scalar.iter().find(|s| s.0 == load).map(|s| s.1); + let mut traced = HashSet::new(); + for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) { + let a = match *leaf { + resource::Source::Loaded { load, .. } | resource::Source::Fetched { load, .. } => { + t.loaded += 1; + address(load) + } + resource::Source::Built { address, .. } => { + t.built += 1; + t.dynamic += usize::from(address.dynamic.is_some()); + Some(address) + } + resource::Source::Constant(_) => { + t.constant += 1; + None + } + resource::Source::Phi { .. } + | resource::Source::Select { .. } + | resource::Source::Lanes { .. } + | resource::Source::LanePhi { .. } => { + unreachable!("leaves are no phis, selects or per-lane choices") + } + }; + // Heaps hold dynamic resources, which no used entry lists; code + // tables are no root parameter. + if let Some(a) = a + && a.param != resource::CODE + && !matches!( + p.layout[a.param].root, + RootType::ResourceHeap | RootType::SamplerHeap + ) + { + traced.insert(p.layout[a.param].user_data); + } + } + // Root constants are listed as a CBV, read straight from the SGPRs. + traced.extend( + r.params + .iter() + .map(|&(_, param, _)| &p.layout[param]) + .filter(|l| l.root == RootType::Constants) + .map(|l| l.user_data), + ); + let listed: HashSet<u8> = p.used.iter().map(|u| u.user_data).collect(); + t.used += p.used.len(); + // Immediate samplers are literals in the code: the distinct sampler + // values (decoded) are matched against the listed entries, which do not + // say which value is whose. + let mut values: Vec<emit::StaticSampler> = Vec::new(); + for d in r + .descriptors + .iter() + .filter(|d| d.role == resource::Role::Sampler) + { + for leaf in d.source.leaves() { + if let resource::Source::Constant(words) = leaf + && let Ok(w) = <[u32; 4]>::try_from(&words[..words.len().min(4)]) + { + let s = emit::StaticSampler::from_words(w); + if !values.contains(&s) { + values.push(s); + } + } + } + } + // Engines often declare equal samplers at several registers, so equal + // values may stand for several entries, but never more values than + // entries. + let immediate = p + .used + .iter() + .filter(|u| u.root == RootType::ImmediateSampler) + .count(); + let samplers_match = !values.is_empty() && values.len() <= immediate; + let matched = |u: &&victory_shader::UsedResource| { + if u.root == RootType::ImmediateSampler { + samplers_match + } else { + traced.contains(&u.user_data) + } + }; + for u in p.used.iter().filter(|u| !matched(u)) { + *t.untraced_used + .entry(format!("{:?} via {:?}", u.kind, u.root)) + .or_default() += 1; + } + t.unlisted += traced.difference(&listed).count(); +} + +fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) { + t.structured += 1; + for (block, guards) in program.blocks.iter().zip(&s.guards) { + t.vector += block + .insts + .iter() + .filter(|i| i.read(ir::Reg::S(ir::EXEC)).is_some()) + .count(); + for &g in guards.iter().flatten() { + t.guarded += 1; + let support = s.bools.support(g); + t.opaque += usize::from(support.iter().any(|a| matches!(a, Atom::Opaque(_)))); + } + } + for exit in &s.exits { + if let LaneExit::Branch { when, .. } = *exit { + if s.bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { + t.uniform_branches += 1; + } else { + t.lane_branches += 1; + } + } + } +} + +fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} diff --git a/crates/victory-core/Cargo.toml b/crates/victory-core/Cargo.toml new file mode 100644 index 000000000..19f69d58b --- /dev/null +++ b/crates/victory-core/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "victory-core" +description = "Shared plumbing: configuration, paths, the asset-policy guard, logging." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow.workspace = true +thiserror.workspace = true +serde.workspace = true +toml.workspace = true +tracing-subscriber.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Lets `VICTORY_LOG` enable debug and trace output. +diagnostics = [] + +[lints] +workspace = true diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs new file mode 100644 index 000000000..72e6659ea --- /dev/null +++ b/crates/victory-core/src/config.rs @@ -0,0 +1,217 @@ +//! Where the user's files live. +//! +//! Resolution order for each value: environment variable, then the config +//! file (`VICTORY_CONFIG`, else `./victory.toml`), then the default. +//! See `victory.example.toml` at the repository root. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use serde::Deserialize; + +use crate::policy::ensure_outside_repo; + +#[derive(Debug, Default, Clone)] +pub struct Config { + /// The user's dump of Grand Theft Auto VI. + pub game_dir: Option<PathBuf>, + /// Root for all derived data. Always outside the repository. + pub cache_dir: PathBuf, + /// What titles write and must keep (persistent local storage). Never + /// inside the cache, which may be deleted at any time. + pub data_dir: PathBuf, + /// Other titles used to exercise platform-level code. + pub test_titles: Vec<PathBuf>, + /// The config file that was read, if any. + pub source: Option<PathBuf>, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct FileConfig { + #[serde(default)] + paths: FilePaths, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct FilePaths { + game_dir: Option<PathBuf>, + cache_dir: Option<PathBuf>, + data_dir: Option<PathBuf>, + #[serde(default)] + test_titles: Vec<PathBuf>, +} + +impl Config { + /// Loads configuration from the environment and the config file. + pub fn load() -> Result<Self> { + let explicit = std::env::var_os("VICTORY_CONFIG").map(PathBuf::from); + let path = explicit + .clone() + .unwrap_or_else(|| PathBuf::from("victory.toml")); + let file = if path.is_file() { + let text = std::fs::read_to_string(&path) + .with_context(|| format!("reading {}", path.display()))?; + Some((path, text)) + } else if let Some(p) = explicit { + anyhow::bail!( + "VICTORY_CONFIG points at {}, which does not exist", + p.display() + ); + } else { + None + }; + let (source, parsed) = match file { + Some((path, text)) => { + let parsed: FileConfig = + toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; + (Some(path), parsed) + } + None => (None, FileConfig::default()), + }; + Self::resolve(parsed.paths, source, |k| std::env::var_os(k)) + } + + fn resolve( + file: FilePaths, + source: Option<PathBuf>, + env: impl Fn(&str) -> Option<std::ffi::OsString>, + ) -> Result<Self> { + let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from); + let test_titles = match env("VICTORY_TEST_TITLES") { + Some(v) if !v.is_empty() => std::env::split_paths(&v) + .filter(|p| !p.as_os_str().is_empty()) + .collect(), + _ => file.test_titles, + }; + let cache_dir = env_path("VICTORY_CACHE_DIR") + .or(file.cache_dir) + .map_or_else(|| default_dir("cache"), Ok)?; + let data_dir = env_path("VICTORY_DATA_DIR") + .or(file.data_dir) + .map_or_else(|| default_dir("data"), Ok)?; + Ok(Config { + game_dir: env_path("VICTORY_GAME_DIR").or(file.game_dir), + cache_dir, + data_dir, + test_titles, + source, + }) + } + + /// The game directory, or a helpful error if it is not configured. + pub fn require_game_dir(&self) -> Result<&Path> { + self.game_dir.as_deref().context( + "no game directory configured: set VICTORY_GAME_DIR or [paths].game_dir in \ + victory.toml (see victory.example.toml)", + ) + } + + /// Returns `<cache>/<sub>`, creating it, after checking the asset policy. + pub fn cache_subdir(&self, sub: &str) -> Result<PathBuf> { + subdir(&self.cache_dir, sub) + } + + /// Returns `<data>/<sub>`, creating it, after checking the asset policy. + pub fn data_subdir(&self, sub: &str) -> Result<PathBuf> { + subdir(&self.data_dir, sub) + } +} + +fn subdir(root: &Path, sub: &str) -> Result<PathBuf> { + let dir = root.join(sub); + ensure_outside_repo(&dir)?; + std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; + Ok(dir) +} + +/// `%LOCALAPPDATA%/victory/<name>` (elsewhere the XDG or home cache). +fn default_dir(name: &str) -> Result<PathBuf> { + let base = std::env::var_os("LOCALAPPDATA") + .or_else(|| std::env::var_os("XDG_CACHE_HOME")) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) + .context("cannot determine a user directory; set VICTORY_CACHE_DIR and VICTORY_DATA_DIR")?; + Ok(base.join("victory").join(name)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsString; + + #[test] + fn environment_overrides_file() { + let file = FilePaths { + game_dir: Some("from-file".into()), + cache_dir: Some("cache-from-file".into()), + ..Default::default() + }; + let env = |k: &str| (k == "VICTORY_GAME_DIR").then(|| OsString::from("from-env")); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-env")); + assert_eq!(cfg.cache_dir, PathBuf::from("cache-from-file")); + } + + #[test] + fn empty_env_values_are_ignored() { + let file = FilePaths { + game_dir: Some("from-file".into()), + ..Default::default() + }; + let env = |k: &str| (k == "VICTORY_GAME_DIR").then(OsString::new); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file")); + } + + #[test] + fn empty_test_titles_env_is_ignored() { + let file = FilePaths { + test_titles: vec!["from-file".into()], + ..Default::default() + }; + let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(OsString::new); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.test_titles, vec![PathBuf::from("from-file")]); + } + + #[test] + fn test_titles_env_splits_paths() { + let value = std::env::join_paths(["first", "second"]).unwrap(); + let file = FilePaths::default(); + let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(|| value.clone()); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!( + cfg.test_titles, + vec![PathBuf::from("first"), PathBuf::from("second")] + ); + } + + #[test] + fn example_config_parses() { + let text = include_str!("../../../victory.example.toml"); + let parsed: FileConfig = toml::from_str(text).unwrap(); + assert!(parsed.paths.game_dir.is_some()); + } + + #[test] + fn cache_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); + let cfg = Config { + cache_dir: inside, + ..Default::default() + }; + assert!(cfg.cache_subdir("x").is_err()); + } + + #[test] + fn data_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data"); + let cfg = Config { + data_dir: inside, + ..Default::default() + }; + assert!(cfg.data_subdir("x").is_err()); + } +} diff --git a/crates/victory-core/src/lib.rs b/crates/victory-core/src/lib.rs new file mode 100644 index 000000000..011df7e12 --- /dev/null +++ b/crates/victory-core/src/lib.rs @@ -0,0 +1,13 @@ +//! Shared plumbing for every VIctory crate and tool. +//! +//! * [`config`]: where the user's files live (never inside the repository). +//! * [`policy`]: the runtime half of rule #1, refusing to write +//! game-derived data into the source tree. +//! * [`logging`]: one tracing setup for all binaries. + +pub mod config; +pub mod logging; +pub mod policy; + +pub use config::Config; +pub use policy::{PolicyError, ensure_outside_repo}; diff --git a/crates/victory-core/src/logging.rs b/crates/victory-core/src/logging.rs new file mode 100644 index 000000000..b4175420b --- /dev/null +++ b/crates/victory-core/src/logging.rs @@ -0,0 +1,35 @@ +//! One tracing setup for every binary. +//! +//! Filter with `VICTORY_LOG` (falls back to `RUST_LOG`), e.g. +//! `VICTORY_LOG=victory_loader=trace,info`. Debug and trace output exist +//! only in builds with the `diagnostics` feature; a plain release build +//! logs info and above whatever the filter asks for. + +use tracing_subscriber::EnvFilter; +use tracing_subscriber::filter::LevelFilter; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; + +/// The most verbose level this build can log. +const CAP: LevelFilter = if cfg!(feature = "diagnostics") { + LevelFilter::TRACE +} else { + LevelFilter::INFO +}; + +pub fn init(default_level: &str) { + let filter = std::env::var("VICTORY_LOG") + .or_else(|_| std::env::var("RUST_LOG")) + .ok() + .and_then(|v| EnvFilter::try_new(v).ok()) + .unwrap_or_else(|| EnvFilter::new(default_level)); + let _ = tracing_subscriber::registry() + .with(CAP) + .with(filter) + .with( + tracing_subscriber::fmt::layer() + .with_target(true) + .with_writer(std::io::stderr), + ) + .try_init(); +} diff --git a/crates/victory-core/src/policy.rs b/crates/victory-core/src/policy.rs new file mode 100644 index 000000000..b10e1c64f --- /dev/null +++ b/crates/victory-core/src/policy.rs @@ -0,0 +1,159 @@ +//! Rule #1, enforced at runtime: game-derived data never lands in the repo. +//! +//! Everything VIctory produces from the user's files (converted assets, +//! prepared images, shader caches, crash dumps) is as much "from the game" +//! as the files themselves. Every tool that writes such output must call +//! [`ensure_outside_repo`] on the destination first. The static half of the +//! rule is `cargo xtask policy`, which checks what git tracks. + +use std::path::{Component, Path, PathBuf}; + +/// Marker file at the root of the source tree. +pub const ROOT_MARKER: &str = ".victory-root"; + +/// The source tree this binary was compiled from. +fn compiled_workspace_root() -> PathBuf { + // crates/victory-core -> workspace root + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +#[derive(Debug, thiserror::Error)] +pub enum PolicyError { + #[error( + "refusing to use {path} for game-derived data: it is inside the VIctory source tree \ + ({root}). Keep game files, caches and outputs outside the repository \ + (see docs/asset-policy.md)" + )] + InsideRepo { path: PathBuf, root: PathBuf }, + #[error("cannot resolve {path}: {source}")] + Io { + path: PathBuf, + source: std::io::Error, + }, +} + +/// Returns `Ok` only if `path` is outside every VIctory source tree. +/// +/// `path` does not have to exist yet. Two checks are made: +/// 1. it is not below the source tree this binary was built from; +/// 2. none of its ancestors contains the [`ROOT_MARKER`] file (catches +/// other clones/copies of the repository). +pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> { + let resolved = resolve(path)?; + + if let Ok(root) = std::fs::canonicalize(compiled_workspace_root()) + && root.join(ROOT_MARKER).is_file() + && resolved.starts_with(&root) + { + return Err(PolicyError::InsideRepo { + path: path.to_path_buf(), + root, + }); + } + + for ancestor in resolved.ancestors() { + if ancestor.join(ROOT_MARKER).is_file() { + return Err(PolicyError::InsideRepo { + path: path.to_path_buf(), + root: ancestor.to_path_buf(), + }); + } + } + Ok(()) +} + +/// Canonicalizes the longest existing prefix of `path` and re-appends the +/// rest, so that paths which do not exist yet can still be compared. +fn resolve(path: &Path) -> Result<PathBuf, PolicyError> { + let absolute = if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map_err(|source| PolicyError::Io { + path: path.to_path_buf(), + source, + })? + .join(path) + }; + + let mut existing = absolute.as_path(); + let mut rest = Vec::new(); + loop { + match std::fs::canonicalize(existing) { + Ok(canon) => { + let mut out = canon; + for component in rest.iter().rev() { + out.push(component); + } + return Ok(normalize(&out)); + } + Err(source) => match (existing.parent(), existing.file_name()) { + (Some(parent), Some(name)) => { + rest.push(name.to_os_string()); + existing = parent; + } + _ => { + return Err(PolicyError::Io { + path: path.to_path_buf(), + source, + }); + } + }, + } + } +} + +/// Removes `.` and resolves `..` lexically (only used on the non-existing tail). +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_paths_inside_this_repo() { + let inside = compiled_workspace_root().join("cache").join("textures"); + assert!(matches!( + ensure_outside_repo(&inside), + Err(PolicyError::InsideRepo { .. }) + )); + let sneaky = std::env::temp_dir().join("..").join("x"); // sanity: no panic + let _ = ensure_outside_repo(&sneaky); + } + + #[test] + fn rejects_dotdot_escapes_back_into_repo() { + let root = compiled_workspace_root(); + let path = root + .join("crates") + .join("..") + .join("not-yet-created") + .join("out"); + assert!(ensure_outside_repo(&path).is_err()); + } + + #[test] + fn rejects_other_clones_via_marker() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join(ROOT_MARKER), "").unwrap(); + assert!(ensure_outside_repo(&tmp.path().join("cache")).is_err()); + } + + #[test] + fn accepts_unrelated_directories() { + let tmp = tempfile::tempdir().unwrap(); + ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap(); + } +} diff --git a/crates/victory-formats/Cargo.toml b/crates/victory-formats/Cargo.toml new file mode 100644 index 000000000..6f3efd957 --- /dev/null +++ b/crates/victory-formats/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "victory-formats" +description = "Platform-level data formats: texture layouts, compressed textures, audio codecs." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-formats/src/bcpack-tables.bin b/crates/victory-formats/src/bcpack-tables.bin new file mode 100644 index 0000000000000000000000000000000000000000..1e548501764588b06e2ed47aa7fed263cd797f3b GIT binary patch literal 77982 zcmb@P37lM2mH%J8+PZqH>Lq*9-3cLtJp>3LOQ+eRqW_2>=rB%HL`E4!#bss~siqw} zI;fFhBq|Oq;7mZ&h@b&c%SIvWArRI8fv^M;NPqxII^F&Meb0HXy1F|c|Ig=tANMWy z-Fx<P?z#6>nxGgIgJI<#FT3oVVGY4wezD+`;VnPvJ$vEsmVa3P(*uULeEhj9CJt|T z_|^UEhqp}My&*lk<>LcaB!;*Ab#VUhhG1YY9MLj3IAT!n|EneFu%iOss#8`UfASF( z4Z&+?uRF12|H_ujFBmxCH!YPdU-{3Mj#)CMvSs|w7tdQ#SJ`rNZ_A<0*~*qzA31#L zE5n$*bj#h1Yb(11r|<ly>@ZZpxdWFZhRfrH!EwRxmVQa>|3^#E79C}pjydr2`<*#$ zMuqNAoO|6N|G3Zhn#)~+c_)41$bo4e%@4IKJ!9<rH`-QK54GgZ%`cihWo2fl<(n5B z(eb@;-%bv-Z2xhv@JEHORxq;ach4SvcCONZZ+hU0>Ay`@pbDPdvaE5<Fz$EnekD~s ztYy{Ud-YraIM`(p`+sc-3gsgrd+ONMF{_&nX=p0z{!3FHn0VT_8yXguxj%SD-PB)C zys+UHWox)%)}Qygc*?&NPA&V(qJ?)HvaI!z`cupDSbg%nM^0#4Q}fp{k=y<uv7p#; za@8$mk!}BKY0+yFev=w9;AQ_ct9?o1hC~@vaLnqf4nIEk$qMeLZFr>Rt6{35rSMiy z)wE#}x@quedoCjnUX3L7PAx%I#bHz)R<o^odG&_eimGo#x^K*XqW&{=*Va5%H9g|~ z_NGrYezWk=x>D6c5%<d`j32kL>9+cXRo6!T^2@eMCZ9F#FZuUmuZ;*O?Z0!{=83h1 zP3cXMJidSAKO7LWbmV8GJ{Gln?1W2ZZ*1LJ`_V8q;LRWHnK!<5X71%674`Y&uid_A z-Gr-Bv&!-~q-V$c&*m4%>tbFHT>IRNC8_!f30?Zu^s2GLB=mGyKJlp0Ekas(h=QM{ zznA`6dU5)d)caB=8249Xzmz>Jdt+vO`kzvl821g;zst?e9ar^>%+k~r13tFyi?tWm zY|nin+nPGfTAnT3nSW3H^);KaS0~pSXZMVGz3GC6^XsxzuZ3T*mXA)JGhx=4Am5X1 z3J<lG&+hwr>w6|_&tH%^IN=8T+1dX#bIFv8^Z%LpYT%;3<%C;iKij&w_LMM=Iv@Y! zJqvbC`EB;cWqF+O{Ri8>*fi5@%DMmk{mB`PDQqm3;=c}@WD*@}`E!NDBAJCkT6qNP z!h6Ft;Vt3S;n%_$;g#yPK6zJib#g`Wqsgt|obWwrX-@A+ZAkqnH7)hw<e}l4;;bk0 zmCVtZ+tNEz*C*@4pR45uRUfE&K07`8So+oE1BuV5WqQrZ>fO0NR^60IrM{LpS}iN; zd+UB&yP~?7y+2u<7^jvmHSKEHoxi$vXLeEYvH%0VY~uQH?aeFeZ_mCroG;#j;L3d` zwtZ~EYx(mtGZQt|a_dn)Iq;m8J@p%san$+s>HmB5XIgK{6(R`)!LCa#YY&_H%MuBK z6Sf}J_>D+jF0;;I@-Ydy@G8!qNt~1TbmFYU#}cO`79^Sy_Xk@On-k9`HYDy&{37v{ z#N@=)!FR&$@ay5{!uN*_;kAkJiGK}FOTI6;AUQd?DZC(jG*Oi}EjTrGY-+#M>&Z(b z)t!l#f+K?~(-);rP4}mkrp`=;;U9v@!KY=H8#5osoSgo1a&zJvL2d9-?%TONRsGph zGX2T_PMjPhgKO%x)xK2ITK%Eyv&rd+DdJ~&Q)6RY;a9c0vh$MvCG$@NmrXf%;=N;z z$bUWiO2VVgKg~LBzXvDZkbff88A)K<8M%2Uw-$5Tqvu4hZS`q~PtNUAewGkM$R`n; zc5N{DvycAIXRi6t*+0DbQ*V6arT_ZyFMs|IyMOijSDyIlm=iv@J%8%qU%vZ*zd!xk z|G4tX^*?y=zkmDL=RS60_1_KrDc!ei;-fw9z4|8y{`AwWo4+#S|9or3j!#^_<kg#= zAN#po-~I8MAAirX$Bz2NzihbligEut?Vg6u|8df@{qH~i!7p9-g<pSQ%gayx>swF# zZqXrM-1(hDANh~{?pwX*nb%+Y-h>n1*Yf>&*Ui7-s;5u6bL(0EzV8{oIqBXh_n*J9 z=0ivR^`SYd&b+MtlmGlrm)~*DCHsH#n0*q>Yi3_u$YoOh*0DUh^x?I2=QVzP@gJHV ze_`r3{&I5rVYl41DS7a^uXUGdXZ`2G3vR#d=yM+ktBQX<?ufR@7tQRvb-}UYr}rK- zw=4MSX@^fc{_NAgd|vh|pKc2aiH0L)?{nNq=g&$`ZJd7W38#MQ!)JZy$P?2`nhyKY zQK^o7Px)f=e#gxD<cv>zaLgCREzNv<?4Sg=J^#_4edNDB{HY(Fea&Zn^gsXbM$h5Z zcmHbllJp55Jax=VzkKE9pa1@euO9!8KWJDs?Y&nIZ2ME+#GgL*e?E5Oj@G|>^?)nC zed)^gjD2za-+y^yea-35cBB&j{qe$YSAAgDXE#r};=3!p_2wsjJ>l~+mjC3@2T%OU z_dlIGD|6uWufM<LzC}0fdEe)L{QS}z#y$OoEq^@pl<ysL$ZO3z`=5IG!ngk8U-o_G zq<=r-$$$OD@Ba5oN3A~pk$W~gHf6v2zw^axW8K=t-#Bk-xPNi>K9{Wd=c<dpdCosw z*7nf6tLFda-mQ1eDqWYX{m_wT&iU&nFTdm9?ys%;`lc7!|MGCtVKYxY_VGXb+eOol zzUx14=^TH=ap&H)@PV$$b8lbp=L>E<sQ0VEw9^hhK5YB)>1Q|WdrJ1aFCF#8{Uogu z&pNClb>xSpADf(Y()qLZ`QVrtpBVRrrI}-z=X~<GBO0d`5}*DGvi<nj;H!sEJMHY` ztn(VOVcYSE!s%b$=hL%~`bv7qzDJ(Y_@R^bn|j3b)R#VdT+<hiJ^xdOoj9lCgioH8 zId$obPc$DhZp;@xIQHY+i@Fzf&+newJ*Rti_pI)Ny7%wiw|k%NDczI0$8|S#*LT-- zS9NE*!xMw|2PXt)1zn4}7IYombwt<UT?cg?*fpcOz5D3y!@Cdep3&XXJ-$2No$F4X z7MvV(E$lk7>)@{ay7uXs)HSiIsjI%LrYqCCsCQ29fxY|oHuTnX&h0#^b5{3)?jyPn z=x*(9?yl|*&JDWebsf?*y=!vU_^y0cwkzm8vUf&rq4Vg@BRUW4+`qH6b8_d{&U|OC zGh3=JRhJUo^STe|ZtE^|r%nyJ=5)>Mn$p$WRoj*5J+!y6b6)3Rod<Nbbx!JR=&bHc zm1;_1@8P|N^tSen?alY5dNtj2AJx5I_n7YV@j=(2T~oWpbXD~p-8-#we&->b`*u$0 zZ0xKm<x9EVqk8x6o!r~ho9?xss307b?jyUWcGsLAbj|8&=_+)Ey)!!(bRN_>wR2o& zO=nO__Rj8|+S}Y)k%h)1{n~w4_k`|5*HK;5x*B@t_m1g2vU5h~gwEPhZEt(;LA~R9 zYfEoC76{#kb~l_EbnV|Ywkz2?u5)(hw9cl^bSc$4t9L^0P)ar&X~k3bf!(!T^SfHR za=iz1>Bzv(TC7UC=wdx32UqMhpMU?o8KVUE_M^buR4Oud}%`?48>?rMIdA#XH`1 zPyhR%Yu~QA-hDa`?wr_}>0Q{{(p%0*-*KqD?4EW((ACzJ>TK_v-dR^l_wLu5``e?2 zdUQ|jYVVrRdqn4<o#RV&y@&OVSYZzJ-1}Yk#ICtrjlFH1Gdt@`LGQ%gy?1-t*6y)g zv%9K07j?FDCVLO=Eobm=J7C0%?#8YIy3(D8caAAl^-db`@?AY*(1{VHVNz>;T5EDd zN##;uDjZponWS1rqDobz^db=?lS(+OY8nl~R3Z`55VewwBocH~s~0tBQdbW_;2qCY z-BZ&wX?0JknUm6lB-IE=aHoNeO(3%QEM#a{Wlh&)#E6XqL{zf%S>S4v8p;p~t*wQ& zRyCQ|$COnyRH-lh)b3ReqAcPK8e+<_wdqtAJWj7+OeQn68IfGs%8*=RRk}J27Q=*? zgd?3xrn1Pl5*vNtO)ymGC?12Lsy?mm3>>OKkS$~d*E*_?i#d@fOe^H4<V7e*Vvd8V zLKe!9D{pib>&Z-w<<${oMxnPRQ$w;fI6;tW%9VL@s)RJC%4fy2Q6))8BUZE3$xIc5 z`B=SH*JO3GnrU<GyXFH)UGgpK&HD;&I+Zb#f>z$jK7n8yqc>4&+LIjWvw{GIvW#_~ zYsexquwW^ssUT6^oI}18$mgYs6amK+m%P2q)@R%hOb7N>RAlNh7^^Tu5DdQbrWZgo zsv?f-Tk31Z));OVIzy7xW2z<0N?L)PD`Ya&PMMx!-lTasm*eKF;Uc<bY;_`pwhDVl zCWT5KU>w^3M_Fhq2w~jUq^Y+x<7!M7*3lS24)s&&>n7A1y^*~1Dp6?7*H5Z5+)*oi z^R0QXnHcoWXbXbE)B<!NoeBnP#@CqjN%Kw=0D^{n3c1FdQNW|CBFMMYOFG~kYLoRf zW@W6vjXA(3YA4j1HXXauoeUcHZLFJASLRqRA*XSAgTxlW1-fp7Kpm?Z-Bcq&5WToi zkfFiM43Vl7_G!&eu;>ZC7{2^1Q=1mChQ)yBB>7?`5w%WV5Qtvv*K7>zUg{>+)=C`| zHMj>sS#70;^b(APw!9=6nJr+=H*(E67!o!B@D|~TH(U-H0P9!DH(yn#LVA^@Fs-3x zLaoy?#9MW9R$i!)W&fc^{p7l|ELH6S0&x5zk!z}w!$eK^okW*N)Q+z)ZJGx{gcaG2 zdrL%_x7JOrBZ6Zh>KQ|je3Pic4F|p`RduOsja#1&HiqOwRdx8L1mOzizII|Q5yo19 ztocf{X-1=I$VqVef}}iFQpa@F-TLxg9LozGfcNKZbwie@AxE?tNlB4F!PZpZT@8{% zPMCrzz^IMp`YCmeD(=ZO7;`{VzO~-ia!XNbB2eUFf+7q?x&u<}*j!rXEBVt&V+1>y zlpo7}hp?fkFqBOSf(C)aI%=X#HqC63d-`aDV$@YP5j`Coc)aBDDG6S~UA%5`N!gj^ z0FhvEU1I|5qG5UilW#@QF#JN%2ncb3p~5~5DOuDI1hXh<2#!_g9$QeOc7w9!3$(%k z@~9hMUDI6U(zSMIP*BZ;RhoHS5=O4ZH1FR8WqJ=4v{EHs`7zj{qP8F*F3jIz7*6<@ z1DkQrxT8VPjMJ2p)Fr7hOx*?zQ}cDmR|S$(;aDB36#JqUy+bL9nlYMVv4{vlXjesz zA-%<_2x`YwYl>r(jn<7yLa|Q)Uw3B1u{<Uv6B7j$iBMIH<1y7yl=D^tpt+?++JrI& z#IzJz>kJz@b{Sw%$*QD$hz8p9pIs##IYGpl*#f}wQ);ClWa_<aP#|MaBrrM9EDosB zMOL$^@H<R<kr3R-V<RrCxoK)^Z7aE)8zmHoN1=-8HJV)b@>s=(m?wq{Sz^oq&5AJG zMogH5vh`u6)}-aV%yEOJ{hD%$sYV!_n1mB`6Kn87!(@_xmPBiNOY6cZ5pM>Q4r31< z!#w1D&10Zp+^lgH`xtG-n9m>3S~IrA{Q@d{RDNo~Z6|aIg~}qsP+k~oQvhPQHSJSh zm{JQeW6!~d3Wt)fw_1|`g-KaoRo-(s6NH;f{p8xJ0%@DU#Mls%d?=ALFIBr+pdi#w ztf_8P>~lI9L#b(Nsc97#Mg)Xe8F%Pd=8LjD_?X)9wPt-hAs5a;vM{BlZk#eEe~uy4 zjLnh2M%dzjPpDVeabz}}lfp|?LlhCshRq5ar`FYssS+BSthj<!lxdpPjbmrHO5KDS z#dX~Px?CC#Zplw=HG8C!QJ9byHVC9T8WxC=!H|R3PN=aL(MfL-^^<C|b>>55zyeg= zkjdpuL)IEGDGv~6oVb#P#(nZimj%*_v99+`Z7ul&TSbt+h$wE<^e=iV3WGF@Nb?nq z=Kh7Tt+g|~FX$q*Htf?{Uq8hdh^P_({7tE<L$GEzPmDcejI4zBV2QdXs~a;u-1=yY ztXGjHOjM6yjbA2%+iX>scGl=er8HN!)>Vr#HB^L%hN-pnlX5~wrwC&ZjGsMTK{4uE zhCTkUadngN3-7FUXlR^NTTp5(PF<MRU1?@ERbXy03B(`-S1FI-*GMb?2xIqeX&l#r zU(z|Qg;wRM3jB-(qg!C}egz^T!>rxRM{__nTjy3ytG`Lg`pAEy7N|q9(mb;?ovaA9 zfH%)5)J+f<UU&hD!jwAMnQr5*Mu&#ijwhbMfguxtiMk0|3CkDMDjiwXy$H}W;KTh4 z6%%HUms!GAWoa7QQW%GZ5&~PUV-If0<%tCPPh;a6CKO~?8pIX(6~^Z3G`|f|AYp2T zY^utTBdQp)4r=neiTSpAG#^#K2MW~bIs&_4qXkh-o;%U<hscL$R;h2y)YOyWMM404 zkj&>=vbh#(EwdK{EwhtT4uLI;7BT$lrgY61%YuMs6iU`(T3f~{_R&cLpqe*LlUi$< zOb*sBYMyxHgm^BjuoS5Wy-@%xrE(E(scMTF{tV&r`6(^+M@>eX^g;hzYn!TSh+ISV z$bC&qYc@Z{EL5OP&1#i4ZM}(fAXO(pYiwz)KFF+^M{C!+>ajI852*o+ywR(%jV(?4 z!&}+AdC|~Ti~Ta#c++r|nhAAPO`Z)xs9HER&YqI5o?^EZr@Dr8E}k~&<*~JHO1`SO zhQVUjWB~XnM^Bn`!~`?x_?52p`IemNBElmG8YHW0+P7ecVhYq+e|Sr7np>)RBPFBk zh?aWI$1VZLwNf))IZSzf$NI|63gfD)>n+ehm=l*wjytTSd3p;DNntpIPn<JeYSxX- zLr#@)&(@mZ>y`vF{gee$%t|yAsT<?k5g1>as*%eM30N;=XVta&@?M40oz$wiu6k^3 z!sa9+z~ojK*HWJ$OEm7F4EWUwT#8&)T<W4as2<;vIhY@pIDWq-s}5?(Ol&c$gWaf% zYint!MVoYXn~=yA_zJ9Xfa&6-N8RMAbWPM1nfZI=zuM|D1xrNMCL$WfW~*ylGchV% zmA#S$4aXLYOSk0Gt~b4jA=QtwohNJ230lPI*y;J^HYkhi*RNVbYRypYDop54t6R%q z=<Q%3MShX-l@Hv-lBkVVNoo;fDttH3s86OPQIn)Mi3V-p6{c&Rcllbg`edhMs#-{G z%9NoC?Nw+wJ(x(1DCnWGSU;@{MszFhI0=iDLTe#EZ7=;|-pkiTg<w&BaBw6%<T9)* zDkSJ9;E^3gh(=tLa^>3^2S?EdJ`+{c-{@0zHWF{_JzUj42p8oOBJpkM!|;%gmP>49 z?apR0nQS(r95J?!O6dt^nzZ@rUl%#pLD?3D@u~;lwH2O!dL(^%h0&C`7IcBR@WPS( z)Cg(T7uXK3?~RfDTqY(P<P$g_eQ!cF9Hi6PfI6HDJuS)y?R$}nK)4Y?fJ)e&PqgO; z_l(5r7~L}I$9{8bp=M;aVRmKk%novIrnOmHS<3>6ZnVTp<&qbEeI!7mPbYY#s}fml zbL{ThOFt7$+%p7kA-QX0KhZ?CP%b9te06qYKSEh$b$z_{%E*2I5<I7n_-}qx%W_^e zmDQ>!n@PyX%nQn9;CgE-jIpIfHk%Dp?S!qwbE-fyDd^I9(cbVzB0)4kYEfP+2Lo@@ z&uvTcQxX)W!>{i}&cpo_KWZ=3yty}cLPs$%>Pvuj1@~^x>f_p#J&)UeoPO`I^;Jz~ zQPCW%?fVgSDn1HHnd&G$hEtbJR<-9dV!3}LeU8vXVno)o=hby|KWM{cV*Kg$d{TDb zm(FAZ{iol*`Ac(MgXE{0=A3pIM)PZU%lcJ}X_vp{2l|Kjb+#)&*)4w5QpmiP(MJdH z5{bYqeq{y-&}(6zLVj{#!l-x;1L!~IyM9rjTBbiL{#lPW4yiZx+>$T6Hd1~b1&uTZ zYkpK1*-amiTt3(<oTV1#6*}_TXUu3XK{oHz_uGUVh_F&<DdeXYa<7jB2n=|jA3Dh_ zYLH21-;8B~TqGh^Q|2CaRd+tIg^AJnfL~vKy9CpV@~QSha+JM*PX*EpcXm-hT}RuC zUY6%y$n?1J>MQ8Vt87NI!$><VOfKa2Ele0p%dj-l$j{|Bn7+%+)g}UnSMB+oFOHOp zQRgQyuGN_7Bliw|X#pc>Il84vi>AHCaTFF;>~Bh8=O*G0#ZVatF^Q0)5-w^;wAVI2 zKZ-t-Wv1ZqQqHTXrfvre+6#@>6gzB}0j3q46Ycf+nhLCj$>cYLR&uFNwAYQ+8+q(d zRR-9cdz(1q`bT!uWIJ+he0CHcqL&Q`s|ZKIG*B9$5S7)onLbKpwS$;V$5u*UMmTQI zyPq2c&uq%<-m=7GyZFf0S1H%X$Tjc}n;+oUXwwNBG`ZA;Z;giM?_q&bCwrEizD=Ao zQQB!z`=shZb-1S@u7%j^NIp`F8l>WIuk)n<8Ew$#ez`k6nm)&gOrSJuZ%Qnxuic)( z@Kvx8OhVP@r#Edm=B<2U6dyzM8FIe5Na3UXT)50HWiqzk;PG_dF|JBnO*xx{u4jtj zhQ_eHHqqWV<^}0jx(&2qbN#wrrP~-T^I%h9$J_90Yf0c0_ATTm76yYbo6b~LM>uqr zb0pduGNb(nfkcJg&5QCia*<JTVO<ebk*$u{Rbkw-#1#oTA!#RwGb4*W@M`~gwEWc1 z0h$;UpC=Xa`xORla+d56T}C?8o`WP31vjig8;7Z?<VD{cB^R7tCC2ab>Kmi{!zB{w zL!cWL<u!F>`WR}1F&d$cl?FWC5r-D#`x$6eC)7%};ibJPY_DtCBw0u%0X39Zd`6A< zFdC3w{hOOd@d3XT)%>z1eB5w(MsN6_%Q`wkn)hY*4Z$wsLq;W%iTa~{_2uig$<K_$ zJ3=nWhJ6||Pd~9~WIw0Pb6KQq`C9F`z2(J`jat02bx%t^z2WWP89xZOUGcttpIw<W z>m&2u@}xx{@n>o>xip2lN5YeEaEo#Y+Z*w>s*(L7vDwA=kY6s!r+1PMp*M7<DqNL4 zb&nqvcH~FG1EH+Jti$dV?-%Cxe@x_t%x*F%%qk0gSPgK&OB~;)Fk{R}crYPzaZAv> zt&bXJycNeaH33?1h8L4x!|S8<3r3AG0Sa&P{>{?wlY7yx^AST0vwU-YaR4RIrX{QR zNZYz1?!$G=qC$gG=uzwBSRd$3C1`HX*R~fXKO;cQYwTDlKI<gHuzbXWd}M!xX^qRi zHBv4nH=Q)j<d;}fmuRmU*d_W5zI$(4^QGH?VO3{eM;(4hC{3uQshVCDU%>9wRIPRB z!hE`SG+ql2MkxG>2~E}cZ6o^$uMuK+)h}F#9c;W$?kK#P#})6H*99o%!LB*2D>P3( zkA9dZC1#EAcxn*=xgeiKb>YJ1siX7@zf>>u6CX`Yk0}gU{E2Lu{N79p9w_0WrbK&n z-D^g*o-tC7yY@PQr@Vb;AwRBg;2xAuC*CRnhK+K326BE%U9O;Y%E*bj+z%R6`R&i7 zy1r5KzFtX{LzTQ~Vd0<&W-F2ia^&80RS{3Cq>uK(w7tX^^d>qZL-6>wMY$F0WS^tq z+4w=b5Go3*+MAT;>^<K#-NCnNs=Y>2dN3+4##yMbuoH_K6AQ<r_A;LXXDDW6+Z&SY z4U>&FqYqxKmQ}%kpfID5pHOIcS;EpnWT;m3vfHZm#<c$HH=T)5u?%b|i|`t_Ai1y* zF32C-Cvyo^^*zR}VuAQQRMSe<+UxS$G&L(iyWBAOk$8QbchIPOGFF-67w4J>7uL^c z8tF&ah}2L9TeYxWU0X-xC8k^SYaFTjf<ibye@qE|!zn&QMP>pSrxM9V<$vw@^dNH# zh4B>dTHtln1zH3o7FKV20DdcJ#GJ(UP+8O%E~uXQ1PxFFOyom9g9|5mmu;_2x7TMi zznS<9vBz<H?<{LT*j}T&eb2*{IJqywGx=!DBI#}Hv^SWy#HRT=*JzCr$2R5nEy1Fy zoqH^<Sk9)nAP<H%6^Tc7013jopenT+<`An`$ilmIau#4C3>S_`ENo8hHu*|=FrsR_ z8a(wy=E;R)6(`5-#OrBNfpXT<!Ut3@;|>|8Z?`*EqBj+5M20b8&`0;ew7m8$21S>4 z8&&8lY8YU^IWf3ezu3~g-i3;}#Cwk$7Poj0Zm;=CHOW*sIzKh>#uTfs;%PW9Tl0pj z%HmHs4uMPnBbZ@QdBnon3HpJY$8ih`*+5rW0=g}XFXRs>9I{6uBR{B!_s~Z?AUzHO z{pui_&pdNC3~TDJc?+IgirA|2p<lD<S3AXjA89WTr(yzyglv1A{CDS*qxwZcrw{5) zF4Q`uFii=$>w@@!Mf2Wp>%uFO%lNvN^~&Z2H7T}6V<NWcuQ-%yZ+P`7bVhNqI77cW zfKxR?{@j$^Ci$^mv>c2zWH}C*WRm=zPCsY6@Is&8yq~(UHm-<Q`ZX#0T=_ZcNAe3g z&>9^gS5BE)*qqy9&pJUPwr@JKMrVBD;S*%1pF0a&UYV;c$Ayz}owP9DyfB~LIU29v z2p-UkfcE-uepTxzeHdQ-;-(C9K~rL3!#?Xq!jpciKqB(1)_lIGZtM#lg<yjy<m)K- zwF+wXBMMLNMqg5ws(eZJLmZ$Nb=M~5(M|L2R3ObH1V>f-%E~526yGO2W->8_sy+7v zp92KN*2j{xUF+Km)$N7Xo<^my40Vg%EbKxWpu_fYiAA-AQTyIeKM_VxF(iALH=*WL zvrYjLO5Z~@O$er*ZOnoyrN)iVNG{~yqQ&+EB)ce&)QvqXP`oe9e~kP9KeHUs@<ekY zfkG}}I7yq-?S=l=eVu|8+I&!+6W{@Olciso)=S(|RWL14I#l2!xlndr-?zr_D!6!# zXnCT>iALe2)-7mG>A%;EPXnqE4mhICpeZro7u#R^HrkKzshbrrTQ3Qs(ejPP=f$qY zNY9NGU+ClEg<IvZ&4~rg2aJI(Rm)=;WBnX6lCeDEsQiwem{r(?W26Bb6&qsvfBB|A zsFgK9RM{^f_me$P)l*4bVnOwh_*lqVn#x=k!?CNLlI>%|_UeTX$;vd+a~E~fo1qHg zhG`A@{`Q{Vcz*3Zj4WLqn7rF!Zec#PAU|h<jW!-6N6FHNkC5vkew!tlmmdO#*}iVb zwZUt!kRfiTylFu$T;smz^Oh_|e3~IgO4CK~+Urjm>E`;rh03g&oIQ{2n*j|f*ptf{ zNWfHsRprI=#sq&F36L&^8uYqJ%^x2w7+1SH@=3*AVk+E6@PI3T^|I%Mbs6nPV0LI0 z3$u7&=&YL<Mt%$P&;3=Z)tto~>{akIvZ89U>98rOJ(6xY9)Q>3I8N|ZFKo)T*H3#A zn{yj<n=yC-7_l297v#ga4KuDm2WBhIho#~M(-{wCSK-mM``v8(s;}oy@awQ*{F#Nd znlGoVW8RPL9{e#vT_I0-XO;4UftO=Duy2lL2X4m>Pf<tt>Ab>+_7@xR`d9G?&-Sk_ zW^bZ`xI4f3IQhKg?6HrS9|<4wVN5csO^b!qHQNME^RIlEu{Hraq&WWRS6cd{toc&H zg+~2n1wRwdL(lW_;gJnzUP;bJ+@O=fgyaXC^z_1h*uv^(o3UX!MAaA(E0AWTZegK% zLBj#H8U-TJul0;<Mv(Mg)w>4C`8lN$2WtN%idUdPFhj-Q@vki=)-`V#Y0pj{bTX&w zM|ACVx%Rs3Te6q(np@Cp-hvUQPW$%@nv)Bf4yl4Bk!ZRw`9Yn!#pvaf;hgaue=+?= zHihk|13lf>d6?grIJ$A|uhE6U)JgUtzJcd4TzHbnd0E+2VnAXZiq9rz#|dI+3^gCk zt6g_3daJC!sI19(<7Lvd_oFLBN5}=X;~nC|^UjHnBV3VRkzZj1^aCq+We2q%(w`sz z7W-Fty5-~Q5%*FatKWmP<*UA<xn9B*MUg$Ii_N>S{E~Afg-1?q9JN0bzjt-}?+;q@ z8%si_HHYj^N`obnM-)qqK<VS~WcD>-v~S(Wni|g=G2EodZ}Bu(vT=T6@gVNQH90pI zE^M54i`)nc6lQz^dy3@3U}DGINy;N?u`Bz&9_0rn=NP_qJX-68!pENyU&vL(L#1S= zZmti#(!WY#pY<beXj)6KkZ0YkdyLpRaiz4(ub(`>zJH7H%X}&P#<O~fGuMgwY4adF zGBf{{k^W)a<HZI|`*qW*@?*6=lF0B0>|U7N-<-yXo4I4Pe|6mN<2^ImHv>1IWP?_9 z@B8;B==WIImF;&jEvR3Ve?{PG<`>fQ3&-7{cS0>WBVG-Htl0j<kmB>0#Qbz&v&<eF zH9N)MgbE^K+YizUs+04o=1kNGvwIgaKjQTQT+@f*=~2}mdPZ{d-$t1HjE@L4u=RU} zqYL5O!u3~U#wuzg3ewLW>0%|nAfH@Nf9zZI!R(!9JjILqh~~@rx%B*8gVv31OT;&9 z3_jE|R)^w!U3g^bs2zsRbmBPz(9G_zJ<8F_W9#;m5H5rndeI7(bd67``OV?c%}Wjv zs7TK0Bc>dP&Hz>+e?DUJf&pa9yo(R(Hi8$$D<r6Wnj<oAU5A|G#hO@(<DVf0X6oov zcvLd9?+~aYuAqvl37X$uO>Nw~85kx*SDf3G^%aRS+6nW<q>mm`_eP{QbZ6Bq9+=Ki zYVJh&<*~0LUgRQNrZIJhV>8!a{M<tI(S;Km#V7eqxdNw>#-;_eH4ADBqks1h!^1=M zAM^B~^`Fx$ihPk9o*q*LZBAgz+{TGVHO)Zxnpe%|2rq7B(KtytnOc|&=Z|lAMQkvi zSLhe94f)cfqsG_I8Go35Lp+p6L|`Dxcm;d?{Oaud>P>&C5Hp}{KL>cwOTUXcIaij8 zzbW#JFC;3m(?4CoS;I9`vcHrJf4ofG=qK}3a`Qy^o$s>uu9}Rh5bL$pgQ|*a)bIW{ z!ed?!%->xDR0{DZsoCbT@6%2}nj$3m>z|hMFXnXB^}YJynWpOZ7-~tUAG!>hQNNE( zr&s-uJ9J`EK&PKwW3-4?r#lmF|Al^=q~EGr)vt!r>5W$zG0_Q_FRrlFFZiT0T7I~K z*8)zMQ-DY&Z(PL-qPH6Li@0>Q_uoa0Mr2Iq>K?5AA!ErPZLB)|>_$mbYZ~bBy7EdJ zuNGjz{C$GMx>c}5fmELU^OZa)|5FWwAxJ-W7sS{eQK+0lQL^{fprSa(VffswNZwl1 zmkrG;mkV_k0`02LJH0mxXoLsWGU+F}>>`)ZH)d%$4BrxkNWx|nKqmkELwJ(pH2^w9 z;k8MDMJxU+U3_19;6eRdhId>mrr5kr3V#yF_bVfhX2A&3&RYc6Av^TU?n}T3j(C>q z>7nyb$tGV|2cB4tGS+bA_aO}WWFGi^^3rR7K`R=f-haJ~koH8WX?f*k>WpaE05Rt7 zP#^SU>rhEqTDlyj(279l4-2HzE5D`Q$su|&*;Jp+pk@sT@fjvwyGWXl_J-=CHzO5u zb6`me>EGa^=u2lTDt&t|6e>c~Xk{HTB=JXCbV;wiQkc~=R9AmL78UO$yztjIai=0I z8F7<MZhXw1nE)clSPel<v$>Wt>XUfvP9j1mSwM}h>1S>h=jP#%M6P)A@8taa%D7wy zo^{9~kj*lQ^S<>%FwlA;QM}Ol=tM+QOZMkK6g2j`HAo!<{nbra6BceERxSDeh1A&J z$vQS&9Kk_?W~<39^noX#7pIw^RsUKL9O?l)^}ORs`l!Hz)~e}L-&>+fHs-tEz`SEM z^b5K6g`hc;N!=C=Qtl=Rsn7Gz8xGzwm#VD#mV0DbsNrMR8x9H3{8@55_)?=em6E}x z%zmzymMK!GwjhD?+T*fzYm;DcyYSD~h#kurZLO(}*DN;!z)L_OUTWWhLdFY_N;W%D z@z6MT(sj-$hD!=&c1~rlv~0y}j^3|5fHfj5qgiMleL(70;8Ard603^@0Ayq`kebKe zh|3@=YY_!^-)v7tfro|FKaFsiiV^Pa$MG}F*|j9Eyo*`GO<qw@Zwh~m=Mw%A0=k|2 z9r$HN*XE?0HJvHwkBmSsaJ=04Yk~$cj?2`aNl@BbvE+(V*z#BG+3n3o9s80g086k4 zkj-w9r(|Sn@=XzgsPDR+zR&?Ou^zs97s;)u!Z=A}8tx!!MMadQ(|ucnM`6J>Rz+tf z9JfaTKz_nyH8J~I0kgsgH2A$uL|UIS<auhmbGbT*4is(iH9h_!J&7EnP9!DLSKJk1 zTT$gcr9B+;HrYRL65;kOK+{O)L=QLJiD^r+&|`hZJ&BBEEn-rVRoiy$fkK%@J~O}u z{R~;d6gen@mRNK-Q53-PZn~!@-0yG8=hS|!q91GoQaWYk9VUkGL8=Wq;80{te#+*A z$PQ-w&fo%CBN4~EKgcF6HW5mtgT$Qi3??q?KPyuo)c|Raw^(d8owCdkSi)r8YPNFW z34Vn&^E#__i#_xsFdn|2fwPlFDde|Ll~@QfW_(PThjuFzm|6wLoaOL0Z7vXa5h{gc z!xN4{4uAnC(2pI|yrSO90#%{%K<yz5sHj0l$f0(fP~y3!dqjTEl?FpJ0|VMm{kHzv zh>RmzL#TB^v$4bWStRQZ{TL>hl0A|HVYMPQIUO?tHJy3yQQ{af(vZpZz}u0N#RRdz z{Q=L21gy>GP5}t_ALDP(pasbE?1!O@B6Jc*BKyd1WY3HeL8kij_$lHJcKFj1x`yHI z2Zqh2B6sm2#6!*hQCQ3-KfFi!mjkHcQ4+yHIbjc^Fdc#|3q0<-1`uIO+z`;T16QUx zrZ9Zp`^amE1)TV6DF1OQkxdZHS*4Ej39H~h028u7jn1YQeS;P+P%k@Nh&`BKL<V~K zz@G$DU(ggJJZOa<{Rl6_K3Y@`874kfPo$Mtuo&~a_pQ?n5aXIS=Te0MR7@o*W!fJR zLURalVWnxScrwkQ8F89D_2(Ee)31JUC<6?_zkeQiNqP2FN5c~D)8C*G$z`(B>Dp!} z7YGSbLo{69f=~;pioD~2P0&oFSHbf#cfJmFgfjYJE#Lm7%Nv=)NFx0E7WIkz#7sIf zeUIQuyu?F{ArW3xM3$1i!JujJ4F2Mg{<FgEjJ5a!eqnQl1o7D`T?U*rUP;8~UPmmV z-{xg#I`bisPdL<c;Pb)19Aa!5SK>@Em@M0H*A;NfTmI#1dQI>QHOK<$1(zExjK?&V z4bT3hdb5wiCXK|KNq_Y^)1?VW!zG_j+$b_}cs_EPk$<?|;26OP&0Jx4{$r+oi4^%! z|G7mPH@HM2^w|FZGlDlMu&Vsaw*+4jhH;EMo4xivi3)*HWzAvgwD;3f79^`CO-yEf zzlC&xm>$ooXRUFgkS5TG5Px?+G;TW92+G+-TEw}f%FGKNnS<9OYpRANet4uh5+5*B zahu6}c8LaP6WXmsZJDL-aV%PbNEnh!=CLjMyIWu*#kb4#l7;|awtO6u96mEsKs5rr z%P<vl*7Y&{2_pW21`_9ehWX3XAzA2MaHRg85*|UQKtMs}S^c#u(I<2n;S{y$FIQ=P zHGPV8=Dy(kURY9__8u6XO<d9}AfTZj=gjZ_!)|o~8uvf>I0;ddz!|$YRLLleB1_oy z_L+YD@mV^T%L6w9A9B#Egqpbd3TcI`Kr~xJ@cLvq7WO9cY=IbFf0E`p(E*n@RTw^e zfCvLWYzt5}`;V+jBsnC)u5>!H?si_OiNy?KGk1Spqs&8b7D!mGS&umfonbH8!~@D; zqms}}FI|7+JOHbY^rJ(+Ai5$)$Tak(`E2@tQ$?zf7($Vn&0KJdpvVcFULbzy?@T%{ z0=q)|=xW_dx8hb6WTzc0A&~P+AI{xP`+^&P&>Nkyi3@%Y9{X!!C`aX1?RX2ELLVy{ zu&i5c<7I!aP8Rm3Gn5P(KM{A~_|K^;_Ag`}HSfMrNryq?%0EYW?K6?+0E+boZ@dT7 zCq0qrGjC*bM=-z2izIsam5xs@vh7<a;Xk2x_yZbirj6V&^jmY#K`;;zR(9W^o)8OI zQ5`0B-z_9C1fRArxm|ypSB5IC7>INqTCGu-2R<RglN<*}|4XNMEgfG62L}2vS|G%8 zZTv32>R&4GFMhm>S$I}|m3Vjw!+w3;8(xO@NTvD{eWU*6kTh(Cksw%i|GoE&97nrE zhuW<K>Hg%fKE#i>z=S|m1?f@0B4hFt7cuSWH-jCOePSRMjKr?~)t<8V%+BGsgvaSg zr4)uz=7%c>u8If8WN1QA@h7|JPvwm)C|mlpkS?mzdy;SV%Q!6GMyJ$~W0K*{J&Z#T zV4(0!3TzJ|Z}t0s{T_i)4yRv|Sse}Mf6u(?3}MIY%7ICuv89u6f>-zl--Jh*neJ`3 zN&YBL(Ftdfpo8Y1abP5o&=c!Ze5Dc}88}_zEsG=%F_~37Lw8$Zis#)*kR+5cP3#NW z5Xom-V(TdT0T=lJ*&OG82tU$KY%W*gf%}c-BND1~=B_*c`WNI3U=?F_=-HWH{odcq zv#eK(201ykoCQbi>9B54e=^TdM>J?>cSQN!-(7VQeTXI&w}g-(dNg_<U{C+f-CQZq z$a@N8^GthPqJOtSO?l?_89aX0RXVB7?b;>jlEP_S<~zwevt+W|SU3lN|JE-Yx`i9z zA}cQ!O*VS2>f1#;ELUVDDyT9At1H8+21q<rQ&BD3n^GpTyQz~mZb+pQl1Z8!b~8f3 zWF^iYfHS1Ypzmj*Q6Pru2oa{&oP6U+LWQr%7LlLjKE{B_L8qHizZxj(T+qyaxK`8? zlE;{h2^JqRP0rk_Xil^J=P<dxPx4{^L5aGUg<m~uW>!dzo~v@ZUX@1GPDOsy%6skC zex$D-z*3)0Brt2w5gwjTI&%JgvOD=;mTE90W%V0cmAz55O+Fd#zDGOo<!Abev~&CZ zPT(*XW)|C1tb8_^y*2onEZs6%T$_7hhW;b0TCK|UNh!l+W^=o|20Ik#L0I3<Yy&R_ z12`(2%C#xe_X_syMcIJl7C-s4mPzkSZ|xHh*-k2|=maESa)N%6T^`$5Y-c0@Lx^;L zNLaPO{L$^0xWRH<pplh@n)IIhTRFW(F8aMxT7MHxZ`9MOtbiOWIk;ynoWl;+z15=+ zI(+&F^zb~4r0S|yUykq!Bi{$ua<{@{O|B5m+4q3)8fOK$s6TLqJ*UFgcFN2xM(N@) zv*MXCg<O(<k;5&?i;CMY;$sXYH@N#1xZ!&Tm3z+c8P{3i{sSylD|T~jegUEzhqBu} z{hLJK&`!4QL8u;O6H2~s57P~P&VP`Ajp%;p`FF?v<{-<m6ik#d@y*6k9Tvt)<`m+x z>EmY|JPw`cKl5<}qbNS?`NIkvaAL(WQs<0kS*tRqFg!EhOQAHN6SJ%mQ*;&0xp=l{ zd#Ue9nlKwvgxct%XZyHApX4!p%{0DU1?XVa>-12Up{md;OB;%s$<zBz91+`?f33uJ z@ItW3{#7@!2X|a>i@5KxhfJ<ETOOL53{E@-90yIA)+Aq3Hg78AmBuTji~;Hz4D8q* z`vJ=n?nly>9@z6cb(O4?>&67=Dteh%OojuCcOK(<Hq}dv3E;$fSDugvKd|WdBO@D& z?TiqOf#?rK+kBBevE~5%a-H15){@|qaWQ|B2z!|vruPg<STwt@s~7U}n%r;Cpln-l zQ}c0jt<;O%PwJ0sT#_Xa>I`n|M*mq!PZ=oxi>-*6l=^53fNvq1V+rj?6UJ1;FNJ~J zBggo8Y=3gpzr1#P#|O+d(>1%^cn-V*Z@HDmnrv<UQ2^DeV8Msxyq|b0$mI&k%DVE3 zAO9z|t14RTYHCyH#tjT+Y6G!OI+DVPPw3X>4Vzbe9=a>l+fU#cs`5xVmY%KZK67X) z+yhvfCt+3v{#B$h%iGd#r8Y4SB93w)5Hgp<Iz4=!@kSU1Pu>bcytAB1R|SQ{6{oCt zFEoR}t8^7<92=pgm+$&+#5cTK6;hDL1f-`okCPODQ{f73LuJ=^;i=x6+$h{I+;^NW z!L=M|Yt_U0RkbJ*Zz9=rjh&h$DQFTmAI|)5zinVuoYc;C5ml}!JDT~F>=au`364BP zY&bZc4SxECO%JYhdC7l8lC36<98seNMkG(|J6KbT&1KRlV5FGg&*?RTr8w_m3<~jQ z#a0@G|Gs-}{7oEtHQb8GRsQI^3sPOSKG^;$Hlr#$<eTQN@v}6M$sUsm`XmmE@sbOR zSJ7$xeT*KS%l=mXj}%*5C|{GhEi$8fY>;QU;vu`H;up*X?(6K7tB+0u5LrPwUzal* zHx7mrE*SBuK!6U}S<g7uWm2KRANjnaZ|j>HLM){+9?e9)Mwn7EyG8k`*^geT2Q<l^ z5l`8ktE;x}bQ_KOfDHktU`vvr_SSa42v2c^0or*_Px`Mt>5uc^Nkx+p!myC3NA?yp zKt+F)_buz8K1jpjxi^%bccp%&f5GEE0tE7<k<a1QzCVITCSdE{7^ZmEdKp_uryJ|G zZ<7Jau53vmt&>@neG79+?M%P04RNqOw5k)Zj5jeRk`uFYV|T+PQ2>sqdXip->due7 z^nbv`DoKIXeMJu#ycVF6V<OnyutoW<Yz&Kw2*&nBmx{?NteW(u{VN@sFha!=OaO9h z{z7>#-}cz`>Tmk77kY2ZRGfCb{`%H<u8glyPU-o!XqenL@L+|j+pT;+l#<(cqLe;w z*8s5v{}-M1>rBL>DhS9;|Kp(Wp<U*jj^8=62or4rNr+A3WuF>RSp`O#%?47TUH6}o z>qkk^f3^@56+DAozL3%1{Oi-2(Mvqn411P<2Ku*ch%HwrRg4(BLtfb7oa6SN!!<4# zOe{V+vfQg`c*_=jJnNmkr+?*hf9iJT6a`6^4bm=ohCeIb+jF|QW6#0B28`hYxIrF* zm8jmnEk?ps?5eMK<e!DG1DHB}x4vBAsY3<U{K)}+GyNaCr7fl)^Kd*<Vw10$3z_0> z_|RpCMi6A*tij4T7qnyL`s30s_Tj$ra*JC8G3y&Wi@tO&{r%la(T49c2$=enYieNk z_wW_jyrQekC7KURSUlq@LHdik&qwcay~xv@C($mk;`y@GS#Q{{%FF>}4Ps03WxY!X z;yDZ-PpuzdU!gK5f<Ctapy<~=*Zt2=Wp|1yRQqcPigij>fF~fLC;af=A5)q4n%;f1 z8NS(1O~b2iAzG+5_T;S5Gcj8dP3X^6+{j-7D36zhgvkpx7{u6Ds-F?>X8(dNQni9r zdmQhij`ZJ6IL_t^qJ$(T`}3L3pGATASh)DlH$bCV8Dzpxgi8Hv(rrj@*I$&7M)4-y zsEhR>%)6A+>5HHH&Le6hT@o3b6%R%{|LK<Btb#@ZZ~G$t;Sl@~0MC89ZoAd}R{Oee zr&rN4+sO9(#x)yPL^RsPa{34cK(M(L-&_7|1cD(*s8;DBy2>1;Kfm*EHL(|1E&_<J z8Giu(e0ujz><Jy2+LRXBvsjIv`yPJjR!vDmgEUUh{L`Oux!~!G{t!JVD#cQBv=Wsm zCR6jmHmO9hKq8g_${nD5*z>rV*|G9E6r(VKAw!$G@$a+Edow{_+p7(<DvQF(Y(5~( zAQ~b}H3fePFMAXH<3Cn0Vn$#|ku)ZLJa?M<*xZlt!jIkxhHN2veqVab0Ls>X`f7zu zd7R|6Xpjce=?ypEu@ac#M%<b0jQS<&p6VUDV#^UMxdsdw2uXoCC6hjR$)U6HS;Qs1 z%K8i@j;sh_Q%$%vze$s(5ri*582--Ho<(bTOsaL0-e_%u?<(l3(QsBg??1n3U(uY> zuoQSKq7bB!q0K*;?2Y4lBnHpF<13-4vVJxEV!urzp7LsJIjnF`&4drW{$G&;A|?oB zUN%2ra+NH@eFy8ea#cZ3%p0gcGBWx#ES-LR&y)HWpR)O=vTjgFvHVTZR{k4?&xg0~ zl-Xc75}KFjnI?%gn>}=Xq7I2jCKTIG5G3d_St0ya#;j+LQkqb+{$7vS5UNp}L3uK^ zOkv-b`uQie{BJN4(Fw)tA*KIMgq;TKUy$ChaxW49kCq0~0@8CEKPg`0eMrBO^T!qM z`BZ9#_Hrrg@5qV8s|iJdCA(!W?9h9s-|B5T!w!_jC3>EkdUH3{Wg9lKIun2dBgNyH z61=3_{{p`)vSKK~hr(2NMrYM$@B9JJ#2|7Pfw$t%aHY29ZLi>qe9e;07;Is-oL@uC z4|l%w!Xt(g5E_OLj(py4T;FDF*zA~`$o_rW&@&<H2UEX425vAHVPmc~iY&RnCKU&E z?YZ|!qYFfqdJ=)m--zpwo~~)yvsJCKDgjU*$kH=x=-DhT^Tw2Cs$`-X%bBIVfLN4L zFXDorjmvI(3S8P27N5vY=D;&oo+ZySQ$2kGEq7LovTRstsd!eRm%j748`g;!`4Q`U z8*VUV9mH`9Q?C~`X`N#7wA>KF>=}7txOzTk=F$l`T~a6g&$sNPpBLCKW-|QI7@gkw z;D*D6Qk*Jv5!+E6_Pqa=?4KnUfs{x=q9TD~Ic3LhZhlkru&$JEib7q8tHYlAPw(kN z9+(F683o(oIfi@sTdDh`6u!^NLUCVS>DReBxkOXx*52GT5;&36gN=itp9u$;1I@2V zEgolhjVY^Q8fAN)a!PJKQm(9~OcW|#!|(q!+4Zs{DrHFkk^uHV#I(h+9<aZI4!L8E zNHyV^z3MdVS^eJsp1U7XS2I_sTd<WESwD4!Po-NYK0W&mkteT4m%bi!N|-m*A`TbK z$m%cX5if?m{f&I?d*Xp#tE=RUAxM<~AO4)E*|up7CNCSd^{v!}wGVrKqyOjEOUa5T zB&P1(*gUo+dojh_c>n*D7=!}=fO$%&OvdPea?s3cu9UCYnvH4Qs!mZ?x~F$9*m@wO z3KE9p(>5+fL>Hm><#pSC^rTdRxtjYKTI^j0j}uX5?@3)jR3R9kD5!^YjW0jfHEc^k zKjVxj`hy(o(iKzDz8?(-A(a;>mcGcxp4Am0oY;GC`S<%W8MAp~SSNcH@_hPH?blfm z0K;hVQH#wepq_s9gv-q~M4{N^>_1K*1_%b_=^g7|q%TZ}a(v4fu6Vw2_Nq21N+e2Z z@IqK*yjnz&F%jmr+rQuxBxX4klMaBj5}~BicQ3qYCKjncC>Y3zScui?Nh-nnx6XKc zEQpBkARqukr~1gBgj2(s8cMy!Ig!xp8mW{E9+rMOz5GoLbO}XkQ+tl3q&FWpmi;K9 zaUP^2VYI+t>7ob|)wORbpEn9jFc>6ch$1sHo(JbXGtT5rO!aCs>lGG74F;MX8$h&H z&EupJo5f@n#$q=6RNv~y&8m#8h-k4^$=$P0{<O#9m1Hc|RW-uoP=3y?`O{B+P?m;- z!QM_qk>!Ws#t%PqGOSCN@=%GHlQ<Glv7!@)oVo5Nk?t^3ragF3kpSfTI85@hJINE& zP5M%E<fqXy*;gj>zSF9kq&G`0h0lVO1VmOY=Wz`6W1fH0jRJF#9;9b1101MPurmV# zKU%LTK(?alTS%6c682oK>GVOzU3I^PGOuG{1_n@-&;5yquC!+|Luim5gj0Qnp6BMa z-%9?VB3?00*0NC{u1cr}z1;Go#$fNb7NHv<!2r*=OD1vp&yNudv?#6=zg!p68+)Yk zZHfPr^L~6Ms-RI9GqI7+soYi;!V;I#1mQ!jn4!cXCp7Xjve?lX6h|M4J%jIjB#Jw9 zY#u$bde2}opvK3@XW<OGim#6z8OA-|?wTmQHhL5-*>|RO&tP@MxSf^v!pT3)8yxJ{ z9A3=Rxxbr|#y>aW5pqKJ}?O&yzpXM$zHavc?t(n#q@Jx5;qqxNjDF1RnaC%80N z8LSE}4_52ELia0^jDg3uyC#aei@SrqN^E|g9MGtQsEVnKsoo>%lcGLZytik4+g%a0 zG0mbp7fWbJE8Y@6CyVz44;Js#$R6VqZf$%LY>M3`6R<!5@*-IpfRCPCrCl3$jlfw9 zmTP3c=tZi7qL0EzXm{Q-#XlDR6x^{FK9MOJc)M#DY}D~caE^|%f-`iSs;dr@E%3nu zKJbDcI-n<0e609b@L;e+W0nN7f({*vb+;t*w=5wW+!?G1)=Gz~bS#&gR+w&Aichl? z!QcBex%B>x5A@tOOhP7G+0dXkg;%T(YB{@h2PNA~@Ko`M;8Ez)F?WbsS$w}Zq%a1p zFp}Tc4d~6D!EEqEupxLz@?qqeHufAi)yM%G6XOIwGV(JcAJ?(oMlKGP4vkEL&2`At zi?@MSGA=#U@qF=Njp0}<YG;|0!Rfvd`^Ly?CU~N_q4<bNc4bh~u^LYaR!Tzsb}+v3 z@K)^q(bAK$1hmnk@r<(jXe5@3oZt}JkrHrZ#l@G3uLLic^(+y!i^b^@(Y-`Aglw=r zxBOT#vE?U<n@cYipSLlKZTuNFc1eo<NV5NJu9@OP#r47c#$QQe&JaH1)bt5Yl{|7^ z=Ck;6$19~BW!vkKHLcLGEF@;dBe5X2qIjfYLTOh=UvZE6ZZzxNF6_&L?ZHMx6PF01 z-IiiV?ll?N!DGS0(jy06a)xB9_@LQ=5m<m*AC$U>#}GDX<b!4hXPA#-5oZRcn)MM) zh9t{aS~x3?6(1_CE8d~r$Oaq2eswQuT{_qrcw^6wrIaW=6s#%TYQ6DoC?+zT5y_VE zaEX6aT7rJc9z3AqE=i~)37xAkZIaNcV2y0Z>5Qp$+i_~~&#WT+T1Bw4q|3SDvqQ(l zg0sea1&r<)j2CKy##O%3vAJVw$5ZM{q(!RC4!Wz*ihF1%xj640cN4`|i?4OOBK<Fu zgg7r&Ee1<Nw{`l%DH38F5yszS6-m}>RytR-&Q$Coni-#2*CsPa<w#~5$DPr*^~L** zKcbLFBY92e{Tb<T1)SXBD?rQ2ejb*^yM*9$rSMBm(hAaae;JB^v5t}LgF5c9ksXpP z_6L;3Wv#fM#<ql1fvA|!L3Xj-<`pDUlw>(CPsb8<ewpX}&Lsrydo9Xesu7n4*9AAI zuF%}QLi+SRKyYb_bQ_N?iQlC!^t@1dG}0wf#Y3f6jYJ|udMsw>ibW8qlf@@W8%vMK z>af{!q|+sKUTSuW#k$qTkqdiwT9Q4R+lp<)z_TzvZ-i4x$Zgc^m9x*hK09a@44w|2 zDQ<v1i<o36c5l=o6}$_I!Q~Of^;xZc*eMk$T`VrSzc@u-Vjq@A1qSx-l{e4m*dRR~ zA1n~3bAuy-ll9bL8HQ`l{S3WAKM-iI4z3oi<<i5&IygsJO3LRIw*dNr*>gB}=pW39 z&yBKr;>htjgWJxMEu)~#ukgt;+;Xi}T)shg*93o&Y#t2m)|GmlX~n7YdDLMbU*|zt zYH>%fQ=@DKvon!;MP%{xa(%e<GagF-cdw3H6erJ=HJm9+I8&o#e;VnUh_&HdLZ=^z z;`7Dlikrk6GZ~R&g|3Qy(JY9SdjWzU&L=p3D_)T=TE*_AP0cGl^TxIge{NHZMysJl zt<qR|M?A*vE|oqx=;239B~P9|Zj!}6VdGaD%|5#<HcN0h#t|3UAT5tWiC}Zbi^UhE z&Bd0xc^o<?Se}JW@9Fv<(ynumYzvF&jw<u94oSvyla8Q6e7ZK^&ZCigxIdAn%cF|V zS&Us<aW2VMT=$Get1e-u6rK|$)(%_6Czjx6=HBx(a(Icg6JJ?7tPB2I{&9w|A1`W& z@=Jnc8tGa9KAieY=CeJ|S;g9QieW1h+aD3Gk}UW<L0O`a(1_NN6B?ui8{*lhHLc(u zNC?@Q-AXGi5qub)f#Vk7@T$#A)>uwXUcNbaR%cc7G9-wMM_ySQBsbn)`fJBugo#X? zGZ|xtX(hG*aD&-tK+@2VDM~`cd)1e`jht_#LFf>l$ic18qgedxR+I@|30^5~lRiq3 zk9rjB(Jbf({T(M3%i%iB2Dd5#{81Lq%z3eRT&nxk!D`_|G9C}&kuE8haJsa4<CfB^ zK_O_<%*(k$FblzWjl{RHBd;DeJ&t0-_~$M1GG-wnAHE5%s}%cuHW_{;hvLxsK6qj2 zOC7I@N-RP7o}JeQtF+RAPjnu~+c=W>HBs6eY?0m0HI2;FY_!~DyF|IB+nbMsRwTuh zV?bKjSbVbhxMV`~(_C%Zl;uV^;gJ$+2mUyOxAaW$nbK1>a<#CLxp`*n+KWdJ4~BaH z{>j|8OmK&t&2F(9x7f-nTws5X_B>p?PyW%SgB4kipJlhPMBHoKSDa65OL@HIL#$NX zih7LVGty|&{meN7zti9{VqM1S>QZr6l4NJe9?rqz6v2QDUOyPc5zh{(jn8$w7`(1g zfv8=p8K$6fmGVBuak!@-Dfba5!2YtqFJ(VhNlLO+*}<~lYdWtARx9?o1{^PXh&7DG zi<XWDl#Sml$;7h*bG?oX)S?ONWmxb5$LRifm!i;ZCZCclZ><hEUTv~PgW%)}1Z3vB zFv#{19S>PV=#Zx^7qwVYNA1qYu6K!7?TQ7vHBx{7C+O37uD&a<L9)G6zOqDn0;ftV zO9QkL>(jBtl=9@U0zKX$nXJ;Rf3A*m%;Q$1T=Vpg<E7vEj4b>`<;6XB$#NL$Yf!X$ zp5>YzN3b?*euxJ6P81(2JyLqWbh26!;;@XtBot#L_IQML>i~PQnAw;s)e;4C5WO68 zk8&`qZ7A}9k*C-qh}3A}Ze=uUgKyYzIS@1w3yS+;74b;!u!QGJTRMoEc=l>(<s6-L zmv-B8-eS2{;!JMbS=u8Qn-zn$ODhE(J=jGiws$1sbC5@u*ank554Jtrc8~0Jm9$9C z*J0;^sCAon??8v{DMRz|hSFml4@a`~JWO^FEY(PpeH5)-E3ssuI=NB#Md^9rD~Q^q z^0e*Zw4l{8QPamFW9*g!1P&zjUG-1NpU3Opv#phfZPxwdV7#o)vl#lgM%;#+XJ+0P ziexn<aTv>YyrR-_o68(N5a1dK#fLVCiw_6*3bP6;P-gBp!-%EJIOwJLY-IA%T>oV0 zarIuMiY8Zi1e3)>rO!&(Ql%Z>?}^fjW(jSEZLKVUJtEE8;*+u9gIc#CsBmeq>cGa= znP)T8cj#Cw=`KrqFSv_kgq(<Ie$50o6>kh~l=Wi2SiPbbhv9Vj1H*GU?${4QpNWo5 znpd7SOmj8XGh^j8=AW@&x>aE5?yCl2>BFT5OT<1r%+_*>L?v5Yxt$|Nmuk!}?eO_f z@KEu7)5lz5fkw}T0#S=>-QMBNM}wC`*N)A>OT{hX5)YY)4Tw|eMls&`iS>_OI6T6L z&*D?TQ>6_im6C8R)nRsTIW-uOq>sRg-G0HD2{sfT)f%1rYp$?)B-1XOW(VS`+X8%H z|2_u-XU|}|=k=c5ZM!w=29gYvlC5qG&KowbgnH}#;hcK}dvoa<9dDTh^%%9wE!QBA zkG%_A?k6!;#wSV}iW@o}F=`i!R`h8RNznwZkO)_BI=4LYlnm}GKB!%uujy&KG@@C| z&zj4SMm$chRe0urYx1E^&7lQx$Ico1302%j83t6wRJ)8_SHjt|qhot<yQo#xFK)qk zp5V-~okHkjEOvke#`y(!lO2zBJfPhO&%@Cs*|>D0Oe&V6TdPBfZ3u6B$fCRNjbpnj zwT@NxXj*ZZf(tCMZ}Y^+zgR5jQGaX)AA{oM8X4QI_jJEugvY;R>EVs*wHM~LvsC<c z7_~i7jF00cl7&)uMp8)Vm8IL4zNRR!L}Sjek@(uGTD*C;4sc<EzH-#ZMjfd@|EFhB z$+664u?@k7z_Sc??U*s+d;&~B@Hhnh8SMx>s;G%i&J`}?N+gQc4nw>W%NT*wptjnw z@XLjZ!!fhs*`P>`2EpUSvv7FuBdhG<_sT6+NTzEn`&%8HFWEk#JRTeKxEXsjIAiNb zcf8cLCD<k`<nSAXW0mfLV5ZGTjHS3Xk*Rw(qmylK6?ZQk6n7;Z#QC+7u&iGrd5`Ym zu`VGj5sS<Qzf!(<b?~f>dR8>Al5~|fX5IEGWjj1`NCYpIUg&s9c$Uk8X6d|Iw!2Jg zB-hI5Juu`$$rPVggn!(6uaI7f8oxwm-$8SEV6S*9SC=&WXGPtwf-5B(X0juM`)i_B z_AA*ANfeHel1mEi(d(wtGo_8vJ*!>T9A{|U@?eFnSLlgeJi6mEvE{Ol@n*2A)Gun= zj7#SGb9CQkUWOFe0rio{Z0N`aHwQNb*GHCs4U~K}Q1RWtV}g$($8{O!q`y0ZKZ)Db z+LvS|yj#?+40>$-1j7(MWCRuH7|yR%zw0!T9Zg?Fk_Y+@H*#^gx>sTWjQ8trgG*#V z3q<E~?Y|N?ZI9b*DAs-D)nx{R+Z0c3krfe1dgM9RS!R8fWD9inNVMSb&&Sc4(YJ$M z`R5}VwML`)a#0fIb2NVr>C>ePm0)KyQS;7@n>uc>5o<*$JR)CmO^<axD_}hysW~&g z+G5`=M)56@E13rSjNj1g5PN?-*J2USOuKL@OTDwWM%u@Q{JcyYGk?0JB7eu|a)M*D z#oC@#2bytxJ}4<EVn=x&{WxN~1&&jj4W5@w9+urmD&m&>g8QXr@$?%S<G5VT_{z1x zH5&1(Ft1h&LpKKr#@Dp!@cb4ou_MmdJ6vK3iC}AKOX&h>ze8S0<Sd%M6g8KDjnPPz zo?L152$Lv1QQA<>#>JoMRT7S}H)IK)*eh~!K55H}#@_|MFl^+Q<YHi6Y;gz~dL(dr zg@)L&d{62@Ny+!4o>ewZ_PMc~G2&Hj_i)M=X+N~)4c2wsWAY&{E+68P!?7YEr@E3_ zz7XFk>9XraUb0#`(Mn1B^yuNT<sRHFG2mqs(Z5;zcl9mm@bfb6m8Hh3KgJ+kmucLZ z)z_!rXiw@ald9)@=Ws9UbIlD|s&gCjnNuwJZSZqZ>MObx!n;P4Kd5K|ZSgpdd5pzZ zkZ(5ltHq(SOcz+-c;VOjLtmh<gqS~<uX|WzOQmN^&+01x`$DrMot469^RHqb7^z;s zLv{PpS$iLwl^K^bW}`+il3Z$OIm5u>upp=>HUJ5`t=5?96oqcld4;ZbD_>YiT##qe z3k-2@qzzUm#}3!2-@U@aLF}aJyMXx$(7i8`aa(Y$LhWX)>9z)KiU@Nx_8jp$Q+2Uq z3r|qVDDXkGa}V{2jx8OplwPsks|9ttXq~C?J<&Ql)*kc$fvm{KhoX)+g1ug?IJQjr z1@}Gnh1h)**}8mOPH-?F32l{k+^sV+{bogl6*@l~+@MJ9vVc$I3-y)PtmJdQG=U{_ zXfEV@o~UJ?8cN-I8N&f?Bt@&%g2mtK>mHiaib2%kHOl)eY9h^eOg!4hqpg=qFH0^R zk|+2UOTrr^<E2`;B275;G2nMAa{XlGDXW725r5<}8&rvXd|QrnX&NwH#+r0_XGPg( z6^R}crDRd(3BuhvuZ&i7&XooR$P)=s&`YZ0<)FCqB~e(?+wD59QvP2Gw#&0U0?`+$ z;{)ok%8XWJj|2~hLo#DL^ATayj*GszzVm@4{L*Xzd$2ux(X6kjvRk)Vw{q|xRo4<Q zL-oH_bI>ZQ>^b)+*FInRWOjhkSf-2wmP;HPx>`Euk$)_=yP~Kij%~DEb#wxJmkr#- zno)~(KDKsjH%nkg6e#2it0J68l(Dh5LZw@L)-sIiwaYitxRk9+n{B}|?G)}-Ryh!z z=?&(T=|?}fRRp_Ex#m^E!*QKy<#MbrLwtp^m_oGToWeaE|58$6#lR{_k}=EGy=3dQ z=D3*2&@0e5hzT!f=j3J4&?bu=Z(1#hTddFfIc9Kh_&8|KYR3MR@R|07^*oKb0ZXWY zM{EviV~<8hLlXL{Wb_9~g}otS?h@r-Mbqc-6$;ck9e!np`ypAMa;NBEF4Na(@##E) z!#Q>txs=6c@#T)9qIF4lI%IduXY9{oxAdpC7nim3i7h6J>w=q?{$ASb(6L6eE|C>U z(u(mOq1}ey5GXMn?1QZ@-m3K{+FWbrRcJHlsbWNYxTnRwj)eOM(@S^v?AEW>dNgjS zC|wn0^vi4?3`|hz_U17Z+-NtHL>Fr=VbytrqRARNKNzgBsEGz0uXBqH(}s+zwLiE+ z$4u4jcHSY)s72YEkMbB9TR=>)o=YzlU()QrntrvNSDH2WY>#|7hO!O!Zk~zM%J(fs z&(#?GY^khb=*vtjC6_JI#j>=DDgChcoOVQurjKRPOqBUWD>|px{W;Va{KX?!Rx$FP z;CA6+Z<1BVIXblSXITw+eAYyd6!$Z?e!h8KqVL~lY20F+FBRUi^qtpN03IWu&+nXX zm+{14p1zxIke9V-7Cb@`{t?k}x8?ERVT5OI=mJWSFJAUp+3cqzS7ftF+~Q@kw9A8J zDkB)r6k5p}tCd^uUG8q<ajotzm#p>s2wMxf_Q2w@aT$SIqc=Xg@$t6%g>kzu`kA%E zD#MAzfXBIWUB*_G(68RMl^BJ^5{<|=mj^TDW%w9aoxeD8y63?MmT;#=`JNI{o?lU( zS=MKalf6HV*fK&{-H(Lla>byPcD0xpTx{R2T$a!ZW@HQ%K04X9zW8A2F4-NCeYNN$ zcf+&e-7M$PbzgZ-E`77Kv(zUF+ca-37v<aSyf*SOw;iZNui*2jz}jJrZ12}P<1I&s z+vU>c89_<Z#!-lIJYfYM=ZOhfMa-ME>R2isN|MY@jl5WJR@Lqr<lws#<Cwwqf3en~ zpViw@t$46Pp7ITObFqBri<GS$T$7H;WkXzX&a=XFyX?rnE%Q~mB%F%3ktMhdB2DOI zTx|PUts-v|y_ai5N!U4C4pz&I#BAr^$Kvm0>0p=UM&5+N_gmRGyJ%#J%%7}z&zEdn z2bCU)lxXD(GZ|y8>JE9=b~_W#jtF+h;@w){kN!iuAl{x0)@ujjUfc25thtEjd9LKU zvb>^0H{LhaXJlF0Rl2CO*>+y}_E}U!*sk*|%W7hI(ihEejmL*Ud+=UyH(C0BQ0IfB z%V$*|wBNnC#bT{sb*kNZwL7`-sg4b851CZgMmC5g2I6!05%2Ul^+*Uyzd=&jDtw%e z7qy#%xt1|PU#!2_V!;j<@o&{DEy(Ugt>qDBGw>JNj`IpcelfRJ`4BTFKE{sCS(>w5 zo^CT}u<{wslgd&1wWGDntY?`hU8VbtLBVEwVvg%mLnU1-0SQ4tsJ)sS6cxyW?pD26 z5V&7cwp+I(ure0wckKLD;OQc34feQ~>r6hcJx0kEE%+?v_+o9+J}{WxxO*et9h61e z*d@Bto_bK!Z0~aAN~Cv8F-EApUisUV;_hlueZG!w$Zsy!Z}N#l@aXyn3eQ~KGLnix zeQka6%O%VS^019M7lT4An3xOP-uTWy{EM%BgUOB^#qDjcDw>pJ5uQ0N73DpO32}r4 zuj7ehljFWuD|???&eX`|vb-K7CD}qB(sYTsM%>=vHmALz_4?Mqubk$J=G7X_H^RmG zbt&(mnX$1(e7+{0F+1EXO8qxz=gBvhnKiMq<Rju}2^0>G3Y@Rh+G>TeY2q!bPi8XR z%i^6Iu!1+%CeJ>aeUsZ{w`U3$`^@J`TDn&b<|Da6E&4=5e#Npn1d-nwZPvjT0QTi; zgMuW)NaW<a(U%tIoc3N(xmp>*#qtn-|F&I}Ypo=Uck6Zu`^@0lacSigzy4c2nO7dv zsAaMrtvP~AZEX*4ZoO`+jHhCYz6-lt*`G2Q+cQ}vY3uhqnpbv<FCsH@i(j>N)Gr)% ziw7e0FZFf#Qj3)Q3Wzy)r>@Iw&Fj3nEM2xPHRqpSwBBOBgy7!+oT_Z<JRKM3V&8C? zcr>c?Pv5`&V>CCcm0UMUTFM>DzJe@=<m#B6S9T$=)^j8m)`30Z_T1oN%`4D~PkCm| zXzsb9sZjG6zhz(*d5gxME1o&`*zb(N;QExX1jng$U&XVp7uF4$AJ}{2H;MKu-Y6e( zx_}Vta!4z;MDyTvvIFdvEJYkdHsrFTH<+*rctCp9iaG_&dYl(1#&eJjOfT=%c;BS) z2({d~R_>IS-KIH#*!K-#WQXX?;N<emi}m1*tUj1UUDmWfEjv;CI+>m0l^TD3a85Zl z@f;;SV?i8!q8<OdSUi&7mduv;t;>pNf5@eaWZj<P2t#`@C~EIbXUUfHMmw*JaPAWH zKEo2n6TZ>$l`au{w_|hgW%XVx$!e~S&nDZ-Sci0ZhHsx&*2-##ewUgBYHwT5%YsuS z+t`PPqM++CmhC#_7i+}Xxsok=VK)fMH}v(u_2zK^EAV*f-s+b87e$3XN)u;kB)`91 zEO}|wYwPSdp9YIZcw&)z5!Qz;N;<DKdRN%o!k2J*`Ap>eL4|Y99ltm)iNa;Ffewvc zshGmIl1Joa@$5i9w7?mj-FtFco!_UNkzW{`A*^czg&po5jr2%KPmeqC6<)F7>tzYw z)hO1;1zE$&V2?PxJo;B+aV`Vxp5^chPLB8s@gwrDf~13lH)`ZLmfyy{37zrWHsqtd z^6g*B>X{+V(#Rb)LtH9LU=4*<;0xXRc;}Wkx7l}+<7Kx?<Y$X@X5K#6eg))OOo&r> zcFS<fWhA?|YqT0XRi4It#9DHRa%wokzZl{3iqA_POBjg_{l#Xav*c@6i{>RrOVm1j zes=EArdtPBJo}G|3j7kAXhIGqoMs8=!DFERP7^3DS#UC2{y==Nk~?2^&wAyYV3n*7 zOQ5go6-xk$Tb1umm;m1Oi5bOZ_O6GF==lFWnzd5pC<)#)?ttANM<5yTm>Ti?w;zed ztj>Iu#(lhAqt)NOGnDi@zuwDRpkje!J?PD|AAT=`2KoN|w=|Xs6nd^y5YU7Wd|)pq zMm2#Gdj?lLM>$4cGhnr&1`TTv&SG#;@O2$?f>ZQ)@%dq|_woQv{flH(KXXUa*WZFE zx9??GMU!xTJ;GVh`cAhopDBwNoRP816q&y(KEJ6Y;5U^dp0A&f=pWL*6F%O7(<O_? zamO`OtMB+SC%<zMiht7&h%OMfrv@Jm26X(50!|`|=XBU?TB~@U$>I53@p++eqR(~( zqIXf8Prii09h~|s=kxJM@7)_f@!1(%XgKEuv-j3xWE(hLjzrQv@r4B=VYnnRRz{4G zqj@%*aQSsj4Kw%FV`Q7-ghS%0=T<ziOX66O`#Tlkyhz>x&Qs(q@6uO@UM^!~nUb|~ z_4Dw^xHsIw8S8VlHaOo!aa`D@V{smb<V#-i&R~Qy_7wy@AnW}b#bt{|@ej|+@E&G6 zcxHw9&ZR=OX9sQXR<^Otf`xmxBjN)Z?fct&#<B0c!P)N?CmxDq{p|dK&%f%CgS}G` zpG7-}3C9c6-z=_Ax6q-?&Mnw8r*|RSn9ug$Gw+s9mngQfN0KDgx}SQc_Acg?I40=x z_uphv9pIDf1kd+f6qhL3S{xbP8IH-;=dxO*VDHjD|8Hk^*DBdngaNoUA9$hBD-jV1 zAxH=z3?U4I1Q`Yyh9Dt`NRSXDNRSXjL`^iwq!UF%#0xLPYk!2lNc;ifl@hR?{q~yf zqd9BUb~V$dPj}C*uCKS=s=am}GS8Wk`1MIhg~RhzGVh--VgAMkuhJ6-32Vj-$q-E{ zXfo-+n?LcvMGW079BRi937K81X0#3y7RwDihd;knh}&3+TYAxzU3nG$`3!4>-!OjQ z?Qg4YH~k5BqA985hYJNCT6(5tKUS3fZzXlHhMpwpvIgF%+m>oJKg31c-l{E(Z9Qe? z#~aFx3{6jwO1hN!mtvc*7TbKO*k)rz&&=T<P7p{$dCq;qwgZR0R4lBmr~Ze$<VO89 zsZDlz+SLay+m0CeQ`NE^GO;buYFfa~en!t0_Wh!G-?3QVce=c9WFuda7cY_uaT_&z z==q1k(<`fZoi%w3&Y2UDiY53xj~j9O(Z>7UJAAeJmcLiFELLKOrhGVfeC+92`7>V^ z{(PrKAWeVjPGA8I$)RQNH@`PzVtvQ?`_8Y@Gnn^K&2rf`Qw{QQh18bw`~UY*>G}DJ zoX>7O!(aErP^^oKVL-VB7aIQj@YFlpI=p`PN8J`H85zVKz7@IgtxwS4ChwNaV`a;Z z9_iuwTo5PK#5qk>B{Qxd;_QQOc#FpyOx~(@u7a+PpLh+v(~f4DSIQ!1u4WRi)Ur3~ zq+~O0S&uyvGY}z<GkI#*c3{F=hsXBF3?Gq~@+0%7^rS6L9oxQe_-5C(xJaxSeZv;Q z7rZiGn?J+*zEGpSf7FO^u|}*WOTr9PZkoD>y7NO^#L(Ru^EG2g6b-It@~B_pQysUp zlqo;W6TVV-+vFw*?i^j*Km_Oq6Pz8GuhMg1!t0eQZA^edG|d!F{00RR$xE5X%1u#Z z$i4cAb+Gu8-_k9R9;QMPv<-*2Uhc`CWZta$*_3JS<%;C<jlLL)TZ1Qz-rgp?#>#OY z-rkwV+0UWc;MD&v3(QyPIWXaeeH@~tTuE(#fBH1fiRhKFO6CW3!-sZZe7J~COs2ph z`EsZTURAOUZwJ@BclgQNCV4gXbYzi3*YG}dCK1%~XXao#>ZhJhc4kTvZB;X?#i`9w z#cgxZQ?$s=pn=E<8ibv!ta}kd-|5f6&KxX!frUMaeH*oG`18rqw_QISeQ-ZfD}LmN z9BTOUxLNjCTX}A52CKW-N<Ji#a-R-6d6RsZ{r@XG;iq--ys2mXxunt)x@YzU6+Dx= z+Q5Vl5AW{nR}#1E7&h&v&R!L3%@c+{AKx>36EmrzY$|I8@|h$rZF?+#%9ZD9X1s!} zIv828r5eqq5J>GzC0#|(35O!n*IzYdKC)pDE+Qjo<)=@=mkocyTOG@en$5ERDp`Kg zlYK>R`k0lbTm1|Nd$CSlw&ONu8A!`{oOETPifo!+zb<g-xaWKsb_e;`6ay+}Zj#(L zV@U6CZ=0JeJ(?KGTr=}pJAQH#v#Q(mI(nt_e7F3$vqzE_tjeGGkNZ?IdNyqP{{EVs zisIOxD*Nhr^+xHHcyzulV(78jDA10fOh*O}8FP~}Z<tBlWI}}F;ZC2&r=rkSR)z_g zXbw$h5+7hf`p@U<y{#CEH_4=7W<uooEr>XiT6&(jrha9)QokUN_=M~tH5C*J>bK{s zWDc(R<C+ltvpY{nZ$i`bgpo#nC_G=Ap8rQJOXY;G=|tsAvZvL5eoz?-Z+Fi7<bTdU z#+v-;CRdkwj(Plx6}gQSe~Q;cP>|l^R1`=wKg@+ce_h+{+WrjcKm-UB-7sqL)WE)D z<)#dMx#kHg_m=|EQ*3@*b4|%b?zoZIu&wj<{JEoF2^NHN(T$y9VDxV3nfm!sY1>%z z#KGid?Ka-xM*NHl8je3Z(1kyLT70O9x9J?%Imph=bd;~^>U@>V5x37CzBYevULA2O zBh_o(V@-L9-LK)ZWWrkh+%X?wS-K^D!g5)6-DCTIC3E2I&Hj1&;LkV<=zJh7AT!=} z<m*?-9Gv=z!}t6CgzV{egLsf&^t{bn+1cAeo%AQ;9Dv>-voIMmUl)2lUE3KOYs8S~ z!E()_uw1t>p`Rb-LgrU%Ltt~pm>QBOg7xg{IkDWz&v3AvI3yDjN&1Imq)Zu+JkzxF z95ws*)%7+O+a_+pI3X-eGf{x?jhXQ{kMw5$TqN{+q@?(1<##=j=NmDkX77w!bAJ|v zcqB(-2;|n_w*&j`)$Xjuifv(BI;40J^2NsDcYc_QxP7fSbz_kked;RN&6=*M9%m)t zLaUaAQ-8B6=o+9)3a^PGH6%O_B6wc*v|?!B?YD}BHI`$Wx#{IeVo^S%t?Ken;lune zn{A`#i?t)Hsb}QEb=IXb4OLS%##m<S!k;(Gw#}NINX4e1pP#9tWYT*k@k+mP`*643 zyDIXVWuZ-?g^k_l*^_vZ89sEgb}8)A6Q3oS4@XZHe$>!2GM}u?*ln3GA$-<P9?eg^ zM5BI=n*EvD+}^G$s-&aiU2Gcp$;}3jA2@WUzh5)ais{KzSSOmy;9zbhDA(Kflq<63 z`90@!9FY`ORk6>#whWrDi(Gl?@bi8Cq^G%p*cDIke(>Fy)C-v}_3@S_jvqejajeR} z&~PU4O0N8%_SH02FvvZ`6FsAPg^#u7U;}UO)On=FA`PbUTPB&YtbRo-FF^&T9&vl) z@OVRHNy?3O9;q!JrO&pvdL?!9r!%g{jy&&)o@@$x{DVbs!M&(z`E%6I_PJ%XlU?11 zTeE30RUbP4{H5pMeZB~$vFHhBqht6;e$VqXp05j;zpu`$Jx>rXgMZOFXgj)?rObi1 zxBGR)Jl>6Ulapd8)jJlRNi99!->mz~s@Sje_wvNTdL<}?b;5{n&{kdfRmJVDy;-A{ zWGXF7_?M<6w`A(F@7FGjwm%=)vINQvY0zlQ!*=kYN9!W0X3Z8gG6L?fC$56?#m+lw z*^TOvRuEF5!ISA#@;#=c`Zqd#kLIglC^N?Q_RJXb-49TY_t=#u>8F-9FyUCZ2Z_F2 z7~j;>kwuMYO}_$#g1B;Mspr6<SNrFdu>yHW-?5i58SB2~&&2JHIkjlPM-oG%2MIEd zpKH0*?9ubSv1flg4Nd>mE}ETx^6y;g1>U~ZKVK$SNTOXTr)buX@^k|evVZ8kI?MaS zp8Z3~5EVLdL@#fycaC4^`NP8(yLBbAHnl6$HaSB_nD4X9*M-bCtG93BP&AVpB#0$( zj3dFPhHd3am_qw{L70Qd>NRt1S>|Bmwfs5i=MyElsVChs^P`(+^1I13)LpHz?dSfV zy|BS}F$>q}7Bt|`6_}OG!Ef(vGmO=TtYf;RPr<|7R2H*7TH=25gOp4=VbyG37T&yG zaO5S6iYK*Gt%14pUCKP3B1lna_x6cg(MoDML7wz!nle*Y?krtVM~yWz1B<LYLt5CN zk3L(QZF5fNm3{lck}25{>fRieUq#eR;tAtvdA}}zcY*hEMJu`l0n|_b@M^Xm)7<M1 zRC<22or^qP|DLO_kQw9&>ta)x3HQSv8aNa!@7Dxl$9X~DaRLdj>+}yY)IYWD>Zkng z-%8JcLpS^ThY~M%4;`TZw3V$gr7<(s2bvi-7u%94UPy40A0&BR^v+l5InG_}JnxX& z<vw#<3@{9-5x2v(kM`$aI$e04d<^GOXT+??UFtdT_J#gA0MlB>KF4qR1~4W=mom>> z^LDqEsh>2;`5ZnB?#k0v%^ow1@Af%Z&QXQG%Z;4Lp&u<<JU&shqqkQfgF8WjAU>|J zmUspGj>Y?$JOTGowZdCPw9CU=(p95M7#{~Un*+TpjVW_G$jVBL%CnXk%Ed$V?4 z;}3OYiz@_2ubp!_>uLOH-Uo5*L36HSMP^EiFdlKMp0RLtX2FD=z5NbOt+KG7nN;wH zG<g!-UD|f!=R5st_kyX3mLR)`jYoII(CvO-2E|QD!raw0GHIGlc&Vot!V`AvHyJY- zv77y1H0R%-?o#Fl#T3Zg@%;(TtU?<cjL!A9fJ&lAsWD5LKdb9o)z4l0HdaiZ4Fl9v zRYg>{urGQ(Q&XwNa#ULSKDM0WWlz#^hV(7-!xScjX}W&pEA#i})yPaQpU0^&=lPKM zovo7ji>-Uubsb&$1i6Xti5*v0gqyVb>|^;74n0+8b(%N?Q(+!GVIEC03G)gY&sOPq ztX#puUa6}in=<K!frSnEDL)Uz9^hbOJ~ZmeGn<~X54gP+A7(-<JI>!RlJk*?rP*ON zJ&&7p{juaF!ly^VO2SL9zQk;HhtcxknZSCjWM2JVo~2ZJrtegzMUG67FPYOc`B1KD z`&wZ`^ZGLOOLv`E4epYh4t%a?=?RB+_SwN(-z^Vs!&0CG{YBS&UHJ34!?Vk`*TL9U zuP}6i^R(qzj74Qx${e$|pVXI6Hm}c4F9Z+7kK7!28Sb}~Y47CDz3ODdr?hr6nF>x| zDD$=1R{ivcX?9=&kFp|`JE|#e1o;}aJ#N|Q%7gYE7kc8jLtFfWRoNL5%~$C;=6ySO zyuDB&Cl~}3^!egfzBFt*u<zcUeuakNemFw*f|yOEZ(8a(u3z~<?G<QZLShKJg+r{I zX^rUR=cUYZ&%5J0I7UuDKV80QMrvtuPei!MxA*K7peg>tkE5!Ep+xtYrWHe@|NMHL zUumr1P!K2I1C+CbJRIa}<Vw2F`!yYE?{OJ@Nq&Y$j~+tS%s={u36Z+v+8~jtPL7># zscxQ=K@E%_{mL8tb62Kc>?ju@uE>SDmfz=V(=#0GW`A!M`@sSBOsyt2vjlu$DRcNU zZ_J0C{3kIaH^L88O&CkM^Pc23Y<oQ6?F)z7+kdLN*-9Nr^@Q-rm_#iPdo*8Lu7sOB zarj*qhu9JFs9>Tt=ULb^Ikc2HaA^L<2d~mo=a4QJDu^b%8GD<It=2^hJ-uPV${8h* zOcteQyqBJkywtb3)C-x<^ku3ZYBT?dA=5t##<%b`*P-99D-U*Z&F~=jAeMB!^d0iA z*LBk~*|Ostfc`|p<|jN*U!cAH1FLj9#jW0cNBtBh!MmJYW>s+&3pZpA?EB@0L)V++ z^a_u`w{-Nf#<?;zCG$<s%vb3-xXF$FH5Owg<k+z>xv+?hSJ|@pGd25*b)9Q-za|^X zi*ycQojIeP%CgjRd<VyKwP&fxhu~XSEj$Q28hH~&IFou2L$B5z(YDNJW&TCB7&2SH zjofAuxBm0(+P}E7FQcbjAG~O$IyjIx^4n5oxaQ9N37Jr5hYQ9)`k4DQVrazeb6YK& zf5dt<xgtBptU`_?lKtg?^xm_>Y;hZ&aChVJtK`~b%21N@3)%6OP9oV7WVl{x$sCyQ zqZ%$W_xFibGDQm?LVC|6l2#wPWRBk98#NnmpF<DR!bzO<bOt>=3w?*puhVq1Z7|_W z^)>Fza~-S~zok-(U6>bU*0625?47ez89@pLn5x2;ut~Pg*C~cX(aVMLD_7LP22YTa zB=F`yS(-Ncvc&D7x`#Che;`xjX4;0U1c_8JF+E?U=a`$AQ#Y|s#LCaasYrtMcy(q) zOPR;ww=})g|85FgAYB-Qmm~5tsMP9_Mt;72_}={U<yHO^nKFb#Y%h^Sb2-!C3CEM3 zFV}U;?HC#pTgbqsW!ze+YYmyhpFgVW(3}2b%glz-BdI2y`&a3?nkHO1|M}73$u1@& zU&eK9f?fUkbk#RG+lX7|R>V+qk;jYqsaHu?#Kt&oYd$pQ3HJ`SJ7Oa%JdY*$Fn|3< zg=x+;&-L?8S0*``m#8e^B4M|x_l|wW&(?P+w|So)1<pdf{G($qu)$5lt#iv??)NL{ z2IUDaLV2|fI?!{Ka2NISMs*L(TnRVeS=BSLup+<v1oKrg2M+zYpDUu1mMV+P6j5TC z))-4u=5hYM^Q*KW1;RogOXXx+$j_(ecYo5O2X*CsO*PxLO<hUfNxtZbjZ<AdNz(bb zk_ivoc6=`^U9)E?^OGQhIEL{Je~uZ(E9Ke7A}{+eV69m-&xU1UWM|%c-N80J!@=&> zjIqhVf~jFc@J=jcDz0N$F`|pO{Y`&19!*(MW+X${+GASJSIN9Od&7yQYh<BXh8c)l zSVW@EX+0q-nFEJz_Bk~kLJr-sLqRMJPS(iJQM3P8AGnD_so69Qw@qb}H9kv&Cyd@< zSD%dmK?T~<G*-@U4Sx>od+YGp)RCtblPgew4|UqK9y?Cr*ZFZy{?uo`Q<Jc^ZOOn! zG8f`imW6=&ho#KphD68ucFp!)0W(JNgArZcaLus#nbgwLzVXNE-=Y5CX|orU7xsU^ zb$x?-SRkS@(^$wHdVYQTUY=C|)bW#{vNLDrGCdKqZmpTrh}#{r8hB&>13zM2swVsk z7B%|Mf$`s~Z<%W>T0+?DPZ;?~SJg#atyuL%+`d+fs2R8770SBL)W#<fSIN-%M=zNp zKi}-nHQ7`J6-E5Y%5sziR#oM+zc01ywLSH7bl2<%=S8kO@w0(_KRdj=am^hVFF$dh zARwJt*)tHhfeB|G-~JmRj!mKnW!*^kT~GYkh}+@MS1Ui8Ji#11ygfUHSUOz6eWQ06 zJ(52T*I0ZO|FJ0<G;<I4NnahL;&x!d^L6!J^Sh#1)lIg*^h|NX$spl;mCS(&cly`X z;sisI{ER0vr83uD${c#`*gJ_uJ9p!!93>Y<knYiZZMMx0zgzw9UVF6iLjNh2QoYW( z$=~y}*%p)cJ%zizYb4#KS`C$QW|A-A|9oA@e0KYuh-NJdwnGLiFN`GJAa=BrIWXZ) zKUd5V#y%67lAS|iA~%<K!rSynJN61>B9o3&|7*V}eZvHI;Lw}3AFMeWmn-42Y>btJ z>v}E|jhU_w@{^Xw**nK;;!=+Q4`he<_1JG}i=XpVG6&wiwZ-lH?e%J~uSAuGFffcd lvrWB=$epi}IWXb7buDI-_hCcX#jU2OU2qB7Lcx_k{{v_s2ZI0r literal 0 HcmV?d00001 diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs new file mode 100644 index 000000000..c8d35378d --- /dev/null +++ b/crates/victory-formats/src/bcpack.rs @@ -0,0 +1,1608 @@ +//! BCPack: lossless packing of BC1-BC7 block streams, as the console's +//! DirectStorage hardware unpacks them. Decode only; BC2 is left out (no +//! title data uses it). +//! +//! A packed stream has no header. It is 12 or 16 interleaved rANS *lanes*; +//! each lane is a run of fragments (header byte, length, payload) coded with +//! one of 128 static models, and a fixed schedule decides which lane takes +//! the next input byte. The lanes' symbols form one record per block: two +//! back references (to one of the last 256 blocks, or to a per-format +//! dictionary that stands in for blocks -1 to -255) and the residuals of the +//! endpoints and indices against them. The models, the index rank tables, +//! the BC7 control codes and the dictionaries are constants of the format, +//! kept in `bcpack-tables.bin` beside this file ([`Tables::builtin`]). + +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(pub &'static str); + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "BCPack: {}", self.0) + } +} + +impl std::error::Error for Error {} + +const MODELS: usize = 128; +const BUCKETS: usize = 9; +const HISTORY: usize = 256; +const DICTIONARY: usize = 255; +/// rANS: decode while the state is above this, read while below. +const LOW: u32 = 1 << 24; +/// Input bytes per schedule round. +const ROUND_BYTES: usize = 8; + +/// Bytes of the table file (see [`Tables::parse`]). +pub const TABLES_SIZE: usize = MODELS * BUCKETS * 2 + + 256 + + 64 + + 256 + + 64 + + 64 + + 512 * 2 + + DICTIONARY * (6 + 16 + 8 + 32 + 2 + 16 + 4 + 32 + 25 + 33 + 50 + 66); + +/// Endpoints and indices of BC1, BC3, BC4 and BC5: small unsigned values, +/// summed per element modulo the element's width. +#[derive(Clone, Copy, Default)] +struct Plain { + ep: [u8; 8], + ix: [u8; 32], +} + +#[derive(Clone, Copy, Default)] +struct Bc6Ep { + /// Endpoint 0 R G B, then endpoints 1-3, left-aligned and biased. + e: [[u16; 3]; 4], +} + +#[derive(Clone, Copy, Default)] +struct Bc6Ix { + mode: u8, + ix: [i16; 16], +} + +#[derive(Clone, Copy, Default)] +struct Bc7Ep { + ctrl: u16, + /// Per subset: R0 R1 G0 G1 B0 B1 A0 A1, left-aligned. + rows: [[u16; 8]; 3], +} + +#[derive(Clone, Copy, Default)] +struct Bc7Ix { + bits: [u8; 2], + ix: [[i16; 16]; 2], +} + +/// The format's constant tables. +pub struct Tables { + freq: [[u32; BUCKETS]; MODELS], + /// Each bucket's first slot; 65536 past the model's last, and one more + /// 65536 at the end so a bucket always has a next start. + start: [[u32; BUCKETS + 1]; MODELS], + /// Per model, the bucket of the first slot of each 256-slot window: the + /// search for a slot's bucket starts there and seldom moves on. + bucket: Box<[[u8; 256]; MODELS]>, + /// ceil(2^32 / freq): exact division for the offsets inside a bucket. + recip: [[u64; BUCKETS]; MODELS], + rank1: [u8; 256], + rank3a: [u8; 64], + rank3c: [u8; 256], + rank4: [u8; 64], + rank5: [u8; 64], + ctrl7: [u16; 512], + bc1: Vec<Plain>, + bc3: Vec<Plain>, + bc4: Vec<Plain>, + bc5: Vec<Plain>, + bc6: Vec<(Bc6Ep, Bc6Ix)>, + bc7: Vec<(Bc7Ep, Bc7Ix)>, +} + +struct Reader<'a>(&'a [u8]); + +impl Reader<'_> { + fn bytes<const N: usize>(&mut self) -> [u8; N] { + let (head, rest) = self.0.split_at(N); + self.0 = rest; + head.try_into().unwrap_or([0; N]) + } + fn u8(&mut self) -> u8 { + self.bytes::<1>()[0] + } + fn u16(&mut self) -> u16 { + u16::from_le_bytes(self.bytes()) + } +} + +impl Tables { + /// The tables VIctory ships with. + pub fn builtin() -> Result<Tables, Error> { + Tables::parse(include_bytes!("bcpack-tables.bin")) + } + + /// Reads the table file: 128 x 9 u16 model frequencies (per bucket, the + /// frequency of each of its symbols), the rank tables (BC1 256 B, BC3 + /// 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, 2 B, + /// 16 + 15 i16). Little-endian, no padding. Every model must tile 65536. + pub fn parse(bytes: &[u8]) -> Result<Tables, Error> { + if bytes.len() != TABLES_SIZE { + return Err(Error("table file has the wrong size")); + } + let mut r = Reader(bytes); + let mut freq = [[0u32; BUCKETS]; MODELS]; + let mut start = [[0u32; BUCKETS + 1]; MODELS]; + let mut bucket = Box::new([[0u8; 256]; MODELS]); + let mut recip = [[0u64; BUCKETS]; MODELS]; + for m in 0..MODELS { + for f in &mut freq[m] { + *f = u32::from(r.u16()); + } + // Model 16 g + shape has g + 2 buckets; bucket b > 0 holds 2^(b-1) symbols. + let used = m / 16 + 2; + let mut at = 0u32; + for b in 0..used { + if freq[m][b] == 0 { + return Err(Error("a model has an empty bucket")); + } + start[m][b] = at; + recip[m][b] = (1u64 << 32).div_ceil(u64::from(freq[m][b])); + at += freq[m][b] << b.saturating_sub(1); + } + if at != 1 << 16 { + return Err(Error("a model does not tile 65536")); + } + start[m][used..].fill(1 << 16); + for (window, b) in bucket[m].iter_mut().enumerate() { + let first = (window as u32) << 8; + *b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8; + } + } + let rank1 = r.bytes(); + let rank3a = r.bytes(); + let rank3c = r.bytes(); + let rank4 = r.bytes(); + let rank5 = r.bytes(); + let mut ctrl7 = [0u16; 512]; + for c in &mut ctrl7 { + *c = r.u16(); + } + let mut plain = |ep: usize, ix: usize| { + (0..DICTIONARY) + .map(|_| { + let mut p = Plain::default(); + for v in &mut p.ep[..ep] { + *v = r.u8(); + } + for v in &mut p.ix[..ix] { + *v = r.u8(); + } + p + }) + .collect::<Vec<_>>() + }; + let bc1 = plain(6, 16); + let bc3 = plain(8, 32); + let bc4 = plain(2, 16); + let bc5 = plain(4, 32); + let bc6 = (0..DICTIONARY) + .map(|_| { + // The endpoint entry's mode byte plays no part in decoding. + r.u8(); + let mut ep = Bc6Ep::default(); + for v in ep.e.as_flattened_mut() { + *v = r.u16(); + } + let mut ix = Bc6Ix { + mode: r.u8(), + ..Default::default() + }; + for v in &mut ix.ix { + *v = r.u16() as i16; + } + (ep, ix) + }) + .collect(); + let bc7 = (0..DICTIONARY) + .map(|_| { + let mut ep = Bc7Ep { + ctrl: r.u16(), + ..Default::default() + }; + for v in ep.rows.as_flattened_mut() { + *v = r.u16(); + } + let mut ix = Bc7Ix { + bits: [r.u8(), r.u8()], + ..Default::default() + }; + // 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) + }) + .collect(); + Ok(Tables { + freq, + start, + bucket, + recip, + rank1, + rank3a, + rank3c, + rank4, + rank5, + ctrl7, + bc1, + bc3, + bc4, + bc5, + bc6, + bc7, + }) + } +} + +/// 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. +pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), Error> { + let block = match bc { + 1 | 4 => 8, + 3 | 5 | 6 | 7 => 16, + _ => return Err(Error("unsupported BC format")), + }; + if dst.is_empty() || !dst.len().is_multiple_of(block) { + return Err(Error("destination is not a whole number of blocks")); + } + let blocks = dst.len() / block; + let (widths, per): (&[u8], usize) = match bc { + 1 => (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + 3 => (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + 4 => (&[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1), + 5 => (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + 6 => (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), + _ => (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), + }; + let stride = widths.len() * per; + let mut records = vec![0u8; blocks * stride]; + let mut next = src.iter().copied(); + lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; + let records = records.chunks_exact(stride); + let out = dst.chunks_exact_mut(block); + let t = tables; + match bc { + 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), + 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), + 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), + 5 => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), + 6 => bc6(records, out, &t.bc6), + _ => bc7(records, out, t), + } +} + +// Lanes. + +#[derive(Clone, Copy, Default)] +struct Lane { + /// Symbol bits - 1 at the full alphabet. + width: u8, + /// 0 header, 1 length (low byte), 2 length high byte, 3 payload. + phase: u8, + long: bool, + reset: bool, + model: u8, + need: bool, + latch: Option<u8>, + out: Option<u8>, + stalled: bool, + x: u32, + left: u32, +} + +impl Lane { + /// One step: take the latched byte (header, length or payload) and + /// decode at most one symbol. + fn step(&mut self, t: &Tables) -> Result<(), Error> { + if self.phase != 3 { + let Some(b) = self.latch.take() else { + return Ok(()); + }; + self.need = true; + match self.phase { + 0 => { + // The top two bits shrink the alphabet; width >= 3. + let group = self.width - (b >> 6); + self.model = group * 16 + (b & 15); + self.reset = b & 0x10 != 0; + self.long = b & 0x20 != 0; + self.left = 0; + self.phase = 1; + } + 1 if self.long => { + self.left = b.into(); + self.phase = 2; + } + 1 => { + self.left = u32::from(b) + 1; + self.phase = 3; + } + _ => { + self.left = (u32::from(b) << 8 | self.left) + 257; + self.phase = 3; + } + } + return Ok(()); + } + let mut x = self.x; + if x < LOW + && let Some(b) = self.latch.take() + { + self.left = self.left.wrapping_sub(1); + x = x << 8 | u32::from(b); + } + self.need = self.left != 0 && self.latch.is_none(); + if x > LOW { + 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 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 { + (0, freq[0] - 1, slot.wrapping_sub(1)) + } else { + let offset = slot - start[b]; + let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32; + ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b]) + }; + self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); + 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. + self.x = x; + } else { + // The fragment ends; a byte read in this step does not reach the carried state. + self.phase = 0; + self.need = self.latch.is_none(); + if self.reset { + self.x = 0; + } + } + Ok(()) + } +} + +/// The bucket holding `slot` (below 65536): the last whose start is at or +/// below it. The window table gives the bucket of the window's first slot; +/// later buckets that start inside the window are stepped over. +#[inline] +fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { + let start = &t.start[usize::from(model)]; + let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]); + while start[b + 1] <= slot { + b += 1; + } + b +} + +/// Decodes `per` symbols per block on every lane into `records` (one record +/// of `widths.len() * per` symbols per block), taking input from `fetch` +/// (given the lane that takes the byte) in the order of the schedule: each +/// round the lanes step in order and take at most 8 bytes between them. +// shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s +// on one core); if texture streaming needs more, run the schedule only to +// split the input per lane and decode the lanes apart. +fn lanes( + t: &Tables, + widths: &[u8], + per: usize, + blocks: usize, + mut fetch: impl FnMut(usize) -> Option<u8>, + records: &mut [u8], +) -> Result<(), Error> { + let mut lanes = [Lane::default(); 16]; + let lanes = &mut lanes[..widths.len()]; + for (lane, &width) in lanes.iter_mut().zip(widths) { + lane.width = width; + lane.need = true; + } + 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 = 1 << j; + let before = taken; + if !lane.stalled { + lane.step(t)?; + } + 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 = Some(b); + taken += 1; + } + } + lane.stalled = (lane.need && before >= ROUND_BYTES) || waiting; + if !lane.stalled + && let Some(sym) = lane.out.take() + { + records[at + j * per] = sym; + 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; + } + // Nothing read and nothing delivered for a few rounds: no lane can go on. + idle = if taken > 0 || moved { 0 } else { idle + 1 }; + if idle > 3 { + return Err(Error("the stream ends early or is corrupt")); + } + } + Ok(()) +} + +// Blocks. + +/// The record's endpoint and index references. +fn references(s: &[u8], paired: bool) -> (usize, usize) { + let (d, ix) = if paired { + (interleave(s[0], s[1]), interleave(s[2], s[3])) + } else { + (s[0], s[1]) + }; + let delta = (d >> 1) ^ (d & 1).wrapping_neg(); + (usize::from(ix.wrapping_add(delta)), usize::from(ix)) +} + +/// Two 4-bit symbols, the first on the even bits. +fn interleave(a: u8, b: u8) -> u8 { + let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); + spread(a) | spread(b) << 1 +} + +/// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first +/// block into the dictionary. +fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: &'a T) -> &'a T { + match r { + 0 => zero, + r if r <= i => &history[(i - r) % HISTORY], + r => &dictionary[r - i - 1], + } +} + +/// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +fn zz(v: u8, bits: u32) -> u8 { + let mask = ((1u32 << bits) - 1) as u8; + ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask +} + +/// Element widths of the plain formats' endpoints and indices. +struct Widths { + ep: [u8; 8], + ix: [u8; 32], + paired: bool, +} + +const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { + let mut ix = [0; 32]; + let mut k = 0; + while k < ix3 + ix2 { + ix[k] = if k < ix3 { 3 } else { 2 }; + k += 1; + } + Widths { ep, ix, paired } +} + +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<Item = &'a [u8]>, + out: impl Iterator<Item = &'a mut [u8]>, + dictionary: &[Plain], + w: &Widths, + residual: impl Fn(&[u8]) -> Plain, + pack: fn(&Plain, &mut [u8]), +) -> Result<(), Error> { + let mut history = vec![Plain::default(); HISTORY]; + let zero = Plain::default(); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, w.paired); + let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; + let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; + let mut v = residual(s); + for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { + *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + } + for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { + *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + } + history[i % HISTORY] = v; + pack(&v, block); + } + Ok(()) +} + +/// 2-bit index residuals: one symbol per 2x2 quad. +fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { + for (q, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym)]; + let base = (q >> 1) * 8 + (q & 1) * 2; + for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { + ix[base + p] = v >> (2 * k) & 3; + } + } +} + +/// 3-bit index residuals: one symbol per two pixels in raster order. +fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { + for (k, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym & 63)]; + ix[2 * k] = v & 7; + ix[2 * k + 1] = v >> 4 & 7; + } +} + +fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { + v.ep[k] = zz(s[2 + k], bits); + } + quads(&t.rank1, &s[8..12], &mut v.ix); + v +} + +fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { + // Colour lanes carry each channel's two endpoints together. + let mut v = Plain { + ep: [ + zz(s[14], 5), + zz(s[16], 6), + zz(s[18], 5), + zz(s[15], 5), + zz(s[17], 6), + zz(s[19], 5), + zz(s[4], 8), + zz(s[5], 8), + ], + ..Default::default() + }; + pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); + quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + v +} + +fn bc4_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + v.ep[..2].copy_from_slice(&[zz(s[2], 8), zz(s[3], 8)]); + pairs(&t.rank4, &s[4..12], &mut v.ix[..16]); + v +} + +fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for k in 0..4 { + v.ep[k] = zz(s[4 + k], 8); + } + pairs(&t.rank5, &s[8..24], &mut v.ix); + v +} + +/// Indices along the endpoint line -> BC1 and BC4 codes. +const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; +const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; + +fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { + let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); + let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); + let bits = (0..16).fold(0, |acc, p| { + acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) + }); + out[..2].copy_from_slice(&c0.to_le_bytes()); + out[2..4].copy_from_slice(&c1.to_le_bytes()); + out[4..8].copy_from_slice(&bits.to_le_bytes()); +} + +/// BC4 half: endpoints are kept 128 below their stored value. +fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { + let bits = (0..16).fold(0u64, |acc, p| { + acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) + }); + let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; + out[..8].copy_from_slice(&v.to_le_bytes()); +} + +fn bc1_pack(v: &Plain, out: &mut [u8]) { + bc1_color(&v.ep, &v.ix, out); +} + +fn 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..], &mut out[8..]); +} + +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]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); + bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); +} + +/// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); + let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + let (even, odd) = (z(half(b)), z(half(b >> 1))); + 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). +fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { + let up = |v: i16, b: u8| { + if b == 0 || b > 16 { + 0 + } else { + (v as u16) << (16 - b) + } + }; + let sum = up(cur, bits).wrapping_add(up(refv, ref_bits)) as i16; + if bits == 0 { 0 } else { sum >> (16 - bits) } +} + +/// Little-endian bit writer for one 128-bit block. +#[derive(Default)] +struct Bits { + v: u128, + at: u32, +} + +impl Bits { + fn put(&mut self, value: u64, n: u32) { + if n > 0 && self.at < 128 { + self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + } + self.at += n; + } +} + +// BC7. + +/// Public BC7 anchor indices: second subset of two; second and third of three. +const ANCHOR2: [u8; 64] = [ + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, + 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, + 2, 15, 15, 15, 15, 15, 2, 2, 15, +]; +const ANCHOR3A: [u8; 64] = [ + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, + 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, + 10, 8, 13, 15, 12, 3, 3, +]; +const ANCHOR3B: [u8; 64] = [ + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, + 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +]; + +/// Endpoint bits of R G B A per mode (public), before p-bits and rotation. +const BC7_BITS: [[u8; 4]; 8] = [ + [4, 4, 4, 0], + [6, 6, 6, 0], + [5, 5, 5, 0], + [7, 7, 7, 0], + [5, 5, 5, 6], + [7, 7, 7, 8], + [7, 7, 7, 7], + [5, 5, 5, 5], +]; +/// Index bits of the primary and secondary sets per mode. +const BC7_INDEX: [[u8; 2]; 8] = [ + [3, 0], + [3, 0], + [2, 0], + [2, 0], + [3, 2], + [2, 2], + [4, 0], + [2, 0], +]; + +fn pbits(mode: u16) -> bool { + matches!(mode, 0 | 1 | 3 | 6 | 7) +} + +/// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha +/// with the rotated channel. +fn bc7_precision(ctrl: u16) -> [u8; 4] { + let (mode, rot) = (ctrl & 7, usize::from(ctrl >> 3 & 3)); + let mut p = BC7_BITS[usize::from(mode)]; + if rot != 0 { + p.swap(3, rot - 1); + } else if pbits(mode) { + p[0] += 1; + } + p +} + +fn bc7<'a>( + records: impl Iterator<Item = &'a [u8]>, + out: impl Iterator<Item = &'a mut [u8]>, + t: &Tables, +) -> Result<(), Error> { + let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY]; + let zero = (Bc7Ep::default(), Bc7Ix::default()); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; + if ctrl == 0 { + return Err(Error("unused BC7 control code")); + } + let 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 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); + } + Ok(()) +} + +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); + let part = usize::from(ctrl >> 8 & 63); + let rot = usize::from(ctrl >> 3 & 3); + let mut w = Bits::default(); + w.put(1 << mode, u32::from(mode) + 1); + match mode { + 0 => w.put(part as u64, 4), + 1 | 2 | 3 | 7 => w.put(part as u64, 6), + 4 => { + w.put(rot as u64, 2); + w.put(u64::from(ctrl >> 5 & 1), 1); + } + 5 => w.put(rot as u64, 2), + _ => {} + } + let ends = 2 * subsets; + let field = |row: usize, col: usize, p: u8| u64::from(ep.rows[row][col] >> (16 - p)); + let mut order = [0, 1, 2, 3]; + if rot != 0 { + order.swap(3, rot - 1); + } + for ch in order { + let p = prec[ch]; + if p == 0 { + continue; + } + let drop = u32::from(ch == 0 && pbits(mode)); + for e in 0..ends { + w.put(field(e / 2, 2 * ch + e % 2, p) >> drop, u32::from(p) - drop); + } + } + match mode { + 1 => (0..subsets).for_each(|row| w.put(field(row, 0, prec[0]) & 1, 1)), + m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), + _ => {} + } + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mut indices = |set: usize| { + let bits = ix.bits[set]; + for (p, &v) in ix.ix[set].iter().enumerate() { + let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + w.put(u64::from(v as u16), n); + } + }; + match mode { + 4 => { + indices(1); + indices(0); + } + 5 => { + indices(0); + indices(1); + } + _ => indices(0), + } + out.copy_from_slice(&w.v.to_le_bytes()); +} + +// BC6H. + +/// Bits of endpoint 0, then of the other endpoints' R, G, B, per mode 1-14. +const BC6_BITS: [[u8; 4]; 15] = [ + [0; 4], + [10, 5, 5, 5], + [7, 6, 6, 6], + [11, 5, 4, 4], + [11, 4, 5, 4], + [11, 4, 4, 5], + [9, 5, 5, 5], + [8, 6, 5, 5], + [8, 5, 6, 5], + [8, 5, 5, 6], + [6, 6, 6, 6], + [10, 10, 10, 10], + [11, 9, 9, 9], + [12, 8, 8, 8], + [16, 4, 4, 4], +]; +/// Mode code and its width, modes 1-14. +const BC6_CODE: [(u64, u32); 15] = [ + (0, 0), + (0, 2), + (1, 2), + (2, 5), + (6, 5), + (10, 5), + (14, 5), + (18, 5), + (22, 5), + (26, 5), + (30, 5), + (3, 5), + (7, 5), + (11, 5), + (15, 5), +]; + +/// A run of the public BC6H layout: `len` bits of channel `ch` (0-2; 3 is +/// the partition) of endpoint `ep`, from bit `first` up. +#[derive(Clone, Copy)] +struct Run { + ch: u8, + ep: u8, + first: u8, + len: u8, +} + +const fn r(ch: u8, ep: u8, first: u8, len: u8) -> Run { + Run { ch, ep, first, len } +} + +const R: u8 = 0; +const G: u8 = 1; +const B: u8 = 2; +const D: Run = r(3, 0, 0, 5); + +/// The header after the mode bits, per mode 1-14. Modes 13 and 14 write the +/// high base bits in ascending order (what the console's packer does). +#[rustfmt::skip] +const BC6_LAYOUT: [&[Run]; 15] = [ + &[], + &[ + r(G, 2, 4, 1), r(B, 2, 4, 1), r(B, 3, 4, 1), r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), + r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), + r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), + r(B, 3, 3, 1), D, + ], + &[ + r(G, 2, 5, 1), r(G, 3, 4, 1), r(G, 3, 5, 1), r(R, 0, 0, 7), r(B, 3, 0, 1), r(B, 3, 1, 1), + r(B, 2, 4, 1), r(G, 0, 0, 7), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 7), + r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6), + r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 5), r(R, 0, 10, 1), r(G, 2, 0, 4), + r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1), + r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(G, 3, 4, 1), + r(G, 2, 0, 4), r(G, 1, 0, 5), r(G, 0, 10, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1), + r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 0, 1), r(B, 3, 2, 1), r(R, 3, 0, 4), + r(G, 2, 4, 1), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(B, 2, 4, 1), + r(G, 2, 0, 4), r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5), + r(B, 0, 10, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 1, 1), r(B, 3, 2, 1), r(R, 3, 0, 4), + r(B, 3, 4, 1), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 9), r(B, 2, 4, 1), r(G, 0, 0, 9), r(G, 2, 4, 1), r(B, 0, 0, 9), r(B, 3, 4, 1), + r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), + r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), + r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 8), r(G, 3, 4, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 3, 2, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(B, 3, 3, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 5), + r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 6), + r(R, 3, 0, 6), D, + ], + &[ + r(R, 0, 0, 8), r(B, 3, 0, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(G, 2, 5, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(G, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), + r(G, 1, 0, 6), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), + r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 8), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 2, 5, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), + r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 5), + r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 6), r(G, 3, 4, 1), r(B, 3, 0, 1), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 6), + r(G, 2, 5, 1), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 6), r(G, 3, 5, 1), + r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6), + r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D, + ], + &[r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 10), r(G, 1, 0, 10), r(B, 1, 0, 10)], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 9), r(R, 0, 10, 1), r(G, 1, 0, 9), + r(G, 0, 10, 1), r(B, 1, 0, 9), r(B, 0, 10, 1), + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 8), r(R, 0, 10, 2), r(G, 1, 0, 8), + r(G, 0, 10, 2), r(B, 1, 0, 8), r(B, 0, 10, 2), + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 6), r(G, 1, 0, 4), + r(G, 0, 10, 6), r(B, 1, 0, 4), r(B, 0, 10, 6), + ], +]; + +fn bc6_index_bits(mode: u8) -> u8 { + match mode { + 1..=10 => 3, + 11..=14 => 4, + _ => 0, + } +} + +fn bc6<'a>( + records: impl Iterator<Item = &'a [u8]>, + out: impl Iterator<Item = &'a mut [u8]>, + dictionary: &[(Bc6Ep, Bc6Ix)], +) -> Result<(), Error> { + let mut history = vec![(Bc6Ep::default(), Bc6Ix::default()); HISTORY]; + let zero = ( + Bc6Ep::default(), + Bc6Ix { + mode: 11, + ..Default::default() + }, + ); + let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); + let wide = |a: u8, b: u8| { + (0..8).fold(0u16, |acc, k| { + acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) + }) + }; + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let mode = s[30].wrapping_add(1); + if !(1..=14).contains(&mode) { + return Err(Error("BC6H mode out of range")); + } + let two = mode < 11; + let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); + let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); + let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); + let (e2, e3) = if two { + ( + [s[16], s[18], s[20]].map(|v| z(v.into())), + [s[17], s[19], s[21]].map(|v| z(v.into())), + ) + } else { + (e0, e1) + }; + let r = &pick(i, ep_ref, &history, dictionary, &zero).0; + let mut ep = Bc6Ep::default(); + // Endpoint 0 at the base precision, the others per channel; the + // reference is cut by the mask after the sum. + let mask = |sh: u32| 0xffffu16 << sh; + for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { + *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); + } + for (k, res) in [e1, e2, e3] + .iter() + .enumerate() + .take(if two { 3 } else { 1 }) + { + for c in 0..3 { + ep.e[k + 1][c] = + r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); + } + } + if !two { + for c in 0..3 { + ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; + } + ep.e[3] = ep.e[1]; + } + let rx = &pick(i, ix_ref, &history, dictionary, &zero).1; + let bits = bc6_index_bits(mode); + let mut ix = Bc6Ix { + mode, + ..Default::default() + }; + for k in 0..8 { + for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() { + let p = 2 * k + h; + ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode)); + } + } + 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()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_shipped_tables_parse() { + assert!(super::Tables::builtin().is_ok()); + } + + use super::*; + + /// Tables we made: uniform models, identity ranks, a BC7 code per mode, + /// empty dictionaries. + fn tables() -> Vec<u8> { + let mut t = Vec::new(); + for m in 0..MODELS { + let g = m / 16; + for b in 0..BUCKETS { + let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 }; + t.extend_from_slice(&f.to_le_bytes()); + } + } + t.extend((0..=255u8).map(|v| v & 0x77)); // rank1 (unused by the tests beyond 2-bit fields) + t.extend(0..64u8); // rank3a + t.extend(0..=255u8); // rank3c + t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4)); // rank4: low 3 bits, next 3 bits + t.extend(0..64u8); // rank5 + for code in 0..512u16 { + // Code c: mode 6 (one subset), the only one the tests use. + let ctrl: u16 = if code == 0 { 0x46 } else { 0 }; + t.extend_from_slice(&ctrl.to_le_bytes()); + } + t.resize(TABLES_SIZE, 0); + t + } + + /// A lane's symbols as one fragment: uniform model, rANS from 2^24, no + /// reset, so the lane keeps 2^24 when it ends. + fn fragment(width: u8, symbols: &[u8]) -> Vec<u8> { + let f = 1u32 << (15 - width); + let mut x = LOW; + let mut bytes = Vec::new(); + for &s in symbols.iter().rev() { + let (freq, start) = if s == 0 { + (f - 1, 1) + } else { + (f, u32::from(s) * f) + }; + while x >= (freq << 16) { + bytes.push(x as u8); + x >>= 8; + } + x = ((x / freq) << 16) + x % freq + start; + } + bytes.extend_from_slice(&x.to_le_bytes()); + bytes.reverse(); + let mut out = vec![0]; + if bytes.len() > 256 { + out[0] |= 0x20; + let n = bytes.len() - 257; + out.extend_from_slice(&[n as u8, (n >> 8) as u8]); + } else { + out.push((bytes.len() - 1) as u8); + } + out.extend(bytes); + out + } + + /// Interleaves per-lane fragments the way the decoder takes bytes. A lane + /// that has finished still asks: a filler fragment (two payload bytes) + /// brings its state to 2^24 with a byte latched, which parks it for good. + fn stream(t: &Tables, widths: &[u8], per: usize, records: &[Vec<u8>]) -> Vec<u8> { + let stride = widths.len() * per; + let mut queues: Vec<std::collections::VecDeque<u8>> = (0..widths.len()) + .map(|j| { + let syms: Vec<u8> = records + .iter() + .flat_map(|r| r[j * per..j * per + per].to_vec()) + .collect(); + let mut bytes = fragment(widths[j], &syms); + bytes.extend([0, 1, 0, 0]); + bytes.into() + }) + .collect(); + let mut out = Vec::new(); + let mut check = vec![0; records.len() * stride]; + let fetch = |j: usize| { + let b = queues[j] + .pop_front() + .expect("a parked lane asked for input"); + out.push(b); + Some(b) + }; + lanes(t, widths, per, records.len(), fetch, &mut check).unwrap(); + assert_eq!(check, records.concat()); + out + } + + const BC4_LANES: [u8; 12] = [7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5]; + + fn zigzag(v: i32) -> u8 { + if v >= 0 { + (2 * v) as u8 + } else { + (-2 * v - 1) as u8 + } + } + + #[test] + fn bc4_blocks_with_and_without_references() { + let t = Tables::parse(&tables()).unwrap(); + // Block 0: endpoints 10, -3 (+128 stored), indices p -> p & 7. + let mut b0 = vec![0, 0, zigzag(10), zigzag(-3)]; + b0.extend((0..8).map(|k| ((2 * k) & 7) | ((2 * k + 1) & 7) << 3)); + // Block 1 refers to block 0 for both: residual endpoints +1, +1; indices +1. + let mut b1 = vec![0, 1, zigzag(1), zigzag(1)]; + b1.extend((0..8).map(|_| 1 | 1 << 3)); + let src = stream(&t, &BC4_LANES, 1, &[b0, b1]); + let mut dst = [0u8; 16]; + decode(4, &src, &mut dst, &t).unwrap(); + let block = |e0: u8, e1: u8, ix: &dyn Fn(usize) -> usize| { + let bits = (0..16).fold(0u64, |a, p| a | BC4_CODE[ix(p)] << (16 + 3 * p)); + (u64::from(e0) | u64::from(e1) << 8 | bits).to_le_bytes() + }; + assert_eq!(dst[..8], block(138, 125, &|p| p & 7)); + assert_eq!(dst[8..], block(139, 126, &|p| (p + 1) & 7)); + } + + #[test] + fn lanes_take_bytes_in_schedule_order_and_long_fragments() { + let t = Tables::parse(&tables()).unwrap(); + // Many blocks: long fragments (over 256 payload bytes) on the wide lanes. + let records: Vec<Vec<u8>> = (0..400u32) + .map(|i| { + let mut r = vec![0, 0, (i * 7) as u8, (i * 13) as u8]; + r.extend((0..8).map(|k| ((i + k) * 5 % 64) as u8)); + r + }) + .collect(); + let src = stream(&t, &BC4_LANES, 1, &records); + let mut got = vec![0u8; records.len() * 12]; + let mut next = src.iter().copied(); + lanes(&t, &BC4_LANES, 1, records.len(), |_| next.next(), &mut got).unwrap(); + assert_eq!(got, records.concat()); + } + + #[test] + fn bc7_mode6_block() { + let t = Tables::parse(&tables()).unwrap(); + // Control code 0 -> mode 6; endpoints R 8 bits (p-bit low), G B A 7 bits. + let mut s = vec![0u8; 32]; + s[4] = zigzag(0x55); // R0 = 0x55: field 0x2a, p-bit 1 + s[5] = zigzag(-1); // R1 = 0xff (8 bits) + s[6] = zigzag(3); + s[10] = zigzag(0x7f >> 1); + let src = stream( + &t, + &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], + 2, + &[s], + ); + let mut dst = [0u8; 16]; + decode(7, &src, &mut dst, &t).unwrap(); + let mut w = Bits::default(); + w.put(1 << 6, 7); + for (v, n) in [ + (0x2a, 7), + (0x7f, 7), + (3, 7), + (0, 7), + (0, 7), + (0, 7), + (0x3f, 7), + (0, 7), + ] { + w.put(v, n); + } + w.put(1, 1); + w.put(1, 1); + assert_eq!(dst, w.v.to_le_bytes()); + } + + #[test] + fn malformed_input_is_an_error() { + let t = Tables::parse(&tables()).unwrap(); + let records: Vec<Vec<u8>> = (0..64u8) + .map(|i| vec![0, 0, i, i, 1, 2, 3, 4, 5, 6, 7, 8]) + .collect(); + let src = stream(&t, &BC4_LANES, 1, &records); + let mut dst = vec![0u8; 64 * 8]; + decode(4, &src, &mut dst, &t).unwrap(); + // Truncated. + assert!(decode(4, &src[..src.len() / 2], &mut dst, &t).is_err()); + // Headers promising more payload than the stream holds. (Other corrupt + // headers decode to garbage: the format has no redundancy.) + let headers = [[0x30; 8], [0xff; 8]].concat(); + assert!(decode(4, &headers, &mut dst[..8], &t).is_err()); + assert!(decode(4, &[], &mut dst, &t).is_err()); + // Destination not a whole number of blocks, empty, more blocks than coded. + assert!(decode(4, &src, &mut dst[..12], &t).is_err()); + assert!(decode(4, &src, &mut [], &t).is_err()); + assert!(decode(4, &src, &mut vec![0u8; 65 * 8], &t).is_err()); + // Unsupported formats, bad tables. + assert!(decode(2, &src, &mut dst, &t).is_err()); + assert!(Tables::parse(&[0; 16]).is_err()); + let mut no_tiling = tables(); + no_tiling[0] = 1; + assert!(Tables::parse(&no_tiling).is_err()); + } + + #[test] + fn noise_never_panics() { + let t = Tables::parse(&tables()).unwrap(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + for round in 0..300 { + let len = round * 7 % 900; + let src: Vec<u8> = (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as u8 + }) + .collect(); + for bc in [1, 3, 4, 5, 6, 7] { + let mut dst = vec![0u8; 16 * (1 + round % 40)]; + let _ = decode(bc, &src, &mut dst, &t); + } + } + } + + /// The window table finds the bucket a scan of the starts finds, for + /// every slot of every model, in the shipped tables and in ours (whose + /// buckets are wide) and in tables whose buckets are one slot wide. + #[test] + fn bucket_lookup_matches_a_scan_of_the_starts() { + let mut narrow = tables(); + for m in 0..MODELS { + // Buckets 1.. of one slot each where they fit; bucket 0 takes the rest. + let used = m / 16 + 2; + let rest = (1u32 << 16) - (1..used).map(|b| 1u32 << (b - 1)).sum::<u32>(); + for b in 0..used { + let f = if b == 0 { rest } else { 1 }; + narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes()); + } + } + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + Tables::parse(&narrow).unwrap(), + ] { + for model in 0..MODELS as u8 { + let start = &t.start[usize::from(model)]; + for slot in 0..1u32 << 16 { + let scan = start[1..].iter().filter(|&&s| s <= slot).count(); + assert_eq!( + bucket_of(&t, model, slot), + scan, + "model {model} slot {slot}" + ); + } + } + } + } + + /// One rANS decode as first written: scan for the bucket, divide for the + /// symbol, rebuild its frequency and start from the symbol. + fn reference_decode(t: &Tables, model: u8, x: u32) -> (u8, u32) { + let (freq, start) = (&t.freq[usize::from(model)], &t.start[usize::from(model)]); + let slot = x & 0xffff; + let b = start[1..BUCKETS].iter().filter(|&&s| s <= slot).count(); + let sym = match b { + 0 => 0, + 1 => 1, + _ => (1u32 << (b - 1)) + (slot - start[b]) / freq[b], + } as u8; + let (f, c) = if sym == 0 { + (freq[0] - 1, 1) + } else { + let k = (8 - sym.leading_zeros()) as usize; + let f = freq[k]; + ( + f, + ((u32::from(sym) - (1 << (k - 1))) * f + start[k]) & 0xffff, + ) + }; + ( + sym, + (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot), + ) + } + + /// A payload step decodes the symbol and state the first version did, for + /// every model and slot of the shipped tables and ours, at assorted states. + #[test] + fn payload_step_matches_the_reference_decode() { + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + ] { + for model in 0..MODELS as u8 { + for high in [0x100u32, 0x1234, 0xffff] { + for slot in 0..1u32 << 16 { + let x = high << 16 | slot; + if x <= LOW { + continue; + } + let mut lane = Lane { + phase: 3, + model, + x, + left: 1, + ..Default::default() + }; + lane.step(&t).unwrap(); + let (sym, next) = reference_decode(&t, model, x); + assert_eq!( + (lane.out, lane.x), + (Some(sym), next), + "model {model} x {x:#x}" + ); + } + } + } + } + } + + /// Pseudo-random records that fit each lane's alphabet; BC7 keeps control + /// code 0 (mode 6), the only one the synthetic tables define. + fn random_records(widths: &[u8], per: usize, blocks: usize, bc7: bool) -> Vec<Vec<u8>> { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + (0..blocks) + .map(|_| { + let mut r: Vec<u8> = (0..widths.len() * per) + .map(|k| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let alphabet = 1u32 << (widths[k / per] + 1); + (seed as u32 % alphabet) as u8 + }) + .collect(); + if bc7 { + r[30] = 0; + r[31] = 0; + } + r + }) + .collect() + } + + /// The fast paths decode exactly what one lane step at a time does, on + /// every format's lane layout, with short and long fragments. + #[test] + fn every_layout_round_trips_through_the_lanes() { + let t = Tables::parse(&tables()).unwrap(); + let layouts: [(&[u8], usize); 6] = [ + (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + (&BC4_LANES, 1), + (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + (&[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), + ]; + for (widths, per) in layouts { + for blocks in [1, 2, 17, 300, 1000] { + let records = random_records(widths, per, blocks, false); + let src = stream(&t, widths, per, &records); + let mut got = vec![0u8; records.concat().len()]; + let mut next = src.iter().copied(); + lanes(&t, widths, per, blocks, |_| next.next(), &mut got).unwrap(); + assert_eq!(got, records.concat(), "{widths:?} x{per}, {blocks} blocks"); + } + } + } + + /// Decode throughput on synthetic streams (no game data): + /// `cargo test --release -p victory-formats bcpack_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn bcpack_throughput() { + let t = Tables::parse(&tables()).unwrap(); + let cases: [(u8, &[u8], usize, usize); 3] = [ + (1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8), + (4, &BC4_LANES, 1, 8), + (7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16), + ]; + for (bc, widths, per, block) in cases { + // One fragment per lane holds at most 65792 bytes. + let blocks = 1 << 14; + let records = random_records(widths, per, blocks, bc == 7); + let src = stream(&t, widths, per, &records); + let mut dst = vec![0u8; blocks * block]; + decode(bc, &src, &mut dst, &t).unwrap(); + let runs = 40; + let started = std::time::Instant::now(); + for _ in 0..runs { + decode(bc, std::hint::black_box(&src), &mut dst, &t).unwrap(); + } + let secs = started.elapsed().as_secs_f64() / f64::from(runs); + println!( + "BC{bc}: {blocks} blocks, {:.1} MB out/s, {:.1} ns/block", + (blocks * block) as f64 / secs / 1e6, + secs * 1e9 / blocks as f64 + ); + } + } + + /// Compares with reference outputs made outside the repository: + /// `VICTORY_BCPACK_TABLES` (the table file) and `VICTORY_BCPACK_CASES`, a + /// directory of `<name>.bc<n>` packed chunks with `<name>.out` beside them. + #[test] + #[ignore = "needs the format tables and reference chunks"] + fn reference_chunks() { + let tables = std::env::var_os("VICTORY_BCPACK_TABLES").expect("VICTORY_BCPACK_TABLES"); + let cases = std::env::var_os("VICTORY_BCPACK_CASES").expect("VICTORY_BCPACK_CASES"); + let t = Tables::parse(&std::fs::read(tables).unwrap()).unwrap(); + let mut n = 0; + for entry in std::fs::read_dir(cases).unwrap() { + let path = entry.unwrap().path(); + let Some(bc) = path + .extension() + .and_then(|e| e.to_str()?.strip_prefix("bc")?.parse().ok()) + else { + continue; + }; + let want = std::fs::read(path.with_extension("out")).unwrap(); + let mut got = vec![0u8; want.len()]; + decode(bc, &std::fs::read(&path).unwrap(), &mut got, &t).unwrap(); + assert!(got == want, "{}", path.display()); + n += 1; + } + 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 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/lib.rs b/crates/victory-formats/src/lib.rs new file mode 100644 index 000000000..f3641779f --- /dev/null +++ b/crates/victory-formats/src/lib.rs @@ -0,0 +1,10 @@ +//! Platform-level data formats, shared by every Xbox Series title. +//! +//! Each module is pure (bytes in, bytes out, no I/O): [`texture`] (the +//! GPU's tiled texture layouts and copies to and from linear rows). Planned: +//! BCPack textures, audio codecs (XMA2, Opus), and the zlib streams used by +//! hardware decompression. + +pub mod bcpack; +pub mod texture; +pub mod xma; diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs new file mode 100644 index 000000000..a1f72e438 --- /dev/null +++ b/crates/victory-formats/src/texture.rs @@ -0,0 +1,1090 @@ +//! Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and +//! alignment, where each mip and array slice starts, the address of each +//! element, and copies between tiled memory and linear rows. +//! +//! Units: an element is a texel, or a 4x4 block of a block-compressed +//! format. Mips of one array slice (or one depth slab of a thick 3D texture) +//! are stored together, smallest first: the mip tail (the small mips sharing +//! one block) at offset 0, mip 0 last. +//! +//! The algorithm follows AMD's address library (addrlib), as shipped in Mesa +//! under `src/amd/addrlib`: block dimensions, mip placement and mip tails +//! from `gfx10addrlib.cpp` and `addrlib2.cpp` +//! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`, +//! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`, +//! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile +//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on +//! RDNA2). addrlib carries this notice: +//! +//! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +//! SPDX-License-Identifier: MIT +//! +//! Permission is hereby granted, free of charge, to any person obtaining a +//! copy of this software and associated documentation files (the +//! "Software"), to deal in the Software without restriction, including +//! without limitation the rights to use, copy, modify, merge, publish, +//! distribute, sublicense, and/or sell copies of the Software, and to permit +//! persons to whom the Software is furnished to do so, subject to the +//! following conditions: the above copyright notice and this permission +//! notice shall be included in all copies or substantial portions of the +//! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +//! EXPRESS OR IMPLIED. + +/// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Swizzle(pub u32); + +impl Swizzle { + pub const LINEAR: Swizzle = Swizzle(0); + pub const SW_256B_S: Swizzle = Swizzle(1); + pub const SW_256B_D: Swizzle = Swizzle(2); + pub const SW_4KB_S: Swizzle = Swizzle(5); + pub const SW_4KB_D: Swizzle = Swizzle(6); + pub const SW_64KB_S: Swizzle = Swizzle(9); + pub const SW_64KB_D: Swizzle = Swizzle(10); + pub const SW_64KB_S_T: Swizzle = Swizzle(17); + pub const SW_64KB_D_T: Swizzle = Swizzle(18); + pub const SW_4KB_S_X: Swizzle = Swizzle(21); + pub const SW_4KB_D_X: Swizzle = Swizzle(22); + pub const SW_4KB_R_X: Swizzle = Swizzle(23); + pub const SW_64KB_Z_X: Swizzle = Swizzle(24); + pub const SW_64KB_S_X: Swizzle = Swizzle(25); + pub const SW_64KB_D_X: Swizzle = Swizzle(26); + pub const SW_64KB_R_X: Swizzle = Swizzle(27); + + /// log2 of the block size in bytes (0 for linear); `None` for modes + /// GFX10 does not have. + pub fn block_log2(self) -> Option<u32> { + Some(match self.0 { + 0 => 0, + 1 | 2 => 8, + 5 | 6 | 21..=23 => 12, + 9 | 10 | 17 | 18 | 24..=27 => 16, + _ => return None, + }) + } + + fn standard(self) -> bool { + matches!(self.0, 1 | 5 | 9 | 17 | 21 | 25) + } + + fn display(self) -> bool { + matches!(self.0, 2 | 6 | 10 | 18 | 22 | 26) + } + + fn z_order(self) -> bool { + self.0 == 24 + } + + /// Pipe and bank XOR modes (`_T`, `_X`): their addresses depend on the + /// GPU's pipe configuration. + pub fn xor(self) -> bool { + self.0 >= 16 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dimension { + Tex1d, + Tex2d, + Tex3d, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// The description makes no texture (zero size, bad element size, a + /// mode this dimension cannot use, too many mips). + Invalid, + /// A valid layout whose addressing is not implemented here. + Unsupported, + /// A buffer is smaller than the layout or the rows need. + TooSmall, +} + +/// One plane of a texture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Desc { + pub dimension: Dimension, + /// In texels. + pub width: u32, + pub height: u32, + /// Depth of a 3D texture, else the array size. + pub depth: u32, + pub mips: u32, + /// 1, 2, 4, 8 or 16. + pub element_bytes: u32, + /// Texels per element side: 1, or 4 for block compression. + pub block: u32, + pub samples: u32, + pub swizzle: Swizzle, +} + +/// Elements along one side of mip `mip`, as data and copies see it: texels +/// halve rounding down (to at least 1), then round up to whole elements. +fn dim(texels: u32, mip: u32, block: u32) -> u32 { + (texels >> mip).max(1).div_ceil(block) +} + +/// Elements along one side of mip `mip` for placement (padding, tail, +/// offsets): addrlib halves mip 0's elements rounding up, which can be one +/// more than [`dim`] for odd sizes. +fn padded_dim(texels: u32, mip: u32, block: u32) -> u32 { + texels.max(1).div_ceil(block).div_ceil(1 << mip) +} + +/// Where one mip lives inside a slice. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Mip { + /// Size in elements (depth 1 unless the texture is 3D). + pub width: u32, + pub height: u32, + pub depth: u32, + /// Padded size in elements: whole blocks, or the tail's share of one. + pub pitch: u32, + pub rows: u32, + pub depth_pitch: u32, + /// Byte offset of its first block in the slice (0 in the tail). + pub offset: u64, + /// In the mip tail: byte offset inside the tail block and the element + /// position the mip starts at. + pub tail: Option<Tail>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Tail { + pub offset: u32, + pub x: u32, + pub y: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Layout { + pub desc: Desc, + /// Block dimensions in elements (linear: the pitch alignment, 1, 1). + pub block: [u32; 3], + /// 3D blocks span `block[2]` depth slices (GFX10 3D `S` and `D` modes). + pub thick: bool, + /// Array slices, depth slabs of `block[2]` slices (thick), or depth + /// slices (thin and linear 3D). + pub slices: u32, + /// Bytes of one slice: its whole mip chain. + pub slice_size: u64, + pub size: u64, + pub alignment: u64, + /// The first mip in the tail; `mips.len()` without one. + pub first_tail_mip: u32, + pub mips: Vec<Mip>, + /// Byte offsets inside a block of each element coordinate bit, per + /// axis; empty for linear and unsupported modes. + pattern: [Vec<u32>; 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` +/// (also the `D` 3D modes). From addrlib's `GFX10_SW_256_S_RBPLUS`, +/// `GFX10_SW_256_D_RBPLUS` and `GFX10_SW_4K_S3_RBPLUS` patterns; the larger +/// blocks add bits Y, X (thin) or Y, X, Z (thick) in turn. +const MICRO: [[&[u8; 16]; 5]; 3] = [ + [ + b"x0x1x2x3y0y1y2y3", + b"--x0x1x2y0y1y2x3", + b"----x0x1y0y1y2x2", + b"------x0y0y1x1x2", + b"--------y0y1x0x1", + ], + [ + b"x0x1x2y1y0y2x3y3", + b"--x0x1x2y0y1y2x3", + b"----x0x1y0y1x2y2", + b"------x0y0x1x2y1", + b"--------x0y0x1y1", + ], + [ + b"x0x1z0y0z1y1x2z2", + b"--x0z0y0z1y1x1z2", + b"----x0y0z0y1x1z1", + b"------x0z0y0x1z1", + b"--------z0y0x0z1", + ], +]; + +/// For each axis, the address bit each coordinate bit lands on. +fn pattern(kind: usize, element_log2: u32, block_log2: u32) -> [Vec<u32>; 3] { + let mut axes: [Vec<u32>; 3] = Default::default(); + let micro = MICRO[kind][element_log2 as usize]; + for bit in 0..8u32 { + let (axis, index) = (micro[2 * bit as usize], micro[2 * bit as usize + 1]); + let axis = match axis { + b'x' => 0, + b'y' => 1, + b'z' => 2, + _ => continue, + }; + let index = usize::from(index - b'0'); + let to = &mut axes[axis]; + if to.len() <= index { + to.resize(index + 1, 0); + } + to[index] = bit; + } + let order: &[usize] = if kind == 2 { &[1, 0, 2] } else { &[1, 0] }; + for (bit, axis) in (8..block_log2).zip(order.iter().cycle()) { + axes[*axis].push(bit); + } + axes +} + +/// Byte offsets inside a block for coordinates 0..2^bits of one axis. +fn spread(bits: &[u32]) -> Vec<u32> { + (0..1u32 << bits.len()) + .map(|c| { + bits.iter() + .enumerate() + .map(|(i, &to)| ((c >> i) & 1) << to) + .sum() + }) + .collect() +} + +const MAX_MIPS: u32 = 16; + +/// The largest width, height and depth (or array size) accepted, in texels. +/// GFX10's image descriptors hold at most 16384 texels per side, so no +/// texture the GPU can use is refused. The bound also keeps every size +/// computed below within `u64` (and its `u32` steps), which unchecked +/// values from a title would otherwise overflow. +const MAX_EXTENT: u32 = 1 << 14; + +/// 256-byte micro tile dimensions by log2 element size, 2D and 3D. +const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]]; +const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]]; +const BLOCK_1K_3D: [[u32; 3]; 5] = [[16, 8, 8], [8, 8, 8], [8, 8, 4], [8, 4, 4], [4, 4, 4]]; + +impl Layout { + pub fn new(desc: &Desc) -> Result<Layout, Error> { + let d = *desc; + let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?; + let valid = (1..=MAX_EXTENT).contains(&d.width) + && (1..=MAX_EXTENT).contains(&d.height) + && (1..=MAX_EXTENT).contains(&d.depth) + && (1..=MAX_MIPS).contains(&d.mips) + && d.element_bytes.is_power_of_two() + && d.element_bytes <= 16 + && matches!(d.block, 1 | 4) + && d.samples.is_power_of_two() + && d.samples <= 8 + && (d.samples == 1 || (d.dimension == Dimension::Tex2d && d.mips == 1)) + && (d.dimension != Dimension::Tex1d || d.height == 1) + && (d.dimension != Dimension::Tex3d + || matches!(d.swizzle.0, 0 | 5 | 9 | 17 | 21 | 24..=27)); + if !valid { + return Err(Error::Invalid); + } + if block_log2 == 0 { + Ok(Layout::linear(d)) + } else { + Ok(Layout::tiled(d, block_log2)) + } + } + + /// `HwlComputeSurfaceInfoLinear`: rows aligned to 256 bytes, mips packed + /// smallest first, a 3D texture's depth slices each hold the chain. + fn linear(d: Desc) -> Layout { + let bpe = u64::from(d.element_bytes); + let align = 256 / d.element_bytes; + let three_d = d.dimension == Dimension::Tex3d; + let mut mips = vec![]; + let mut offset = 0; + for i in (0..d.mips).rev() { + let h = padded_dim(d.height, i, d.block); + let pitch = padded_dim(d.width, i, d.block).next_multiple_of(align); + mips.push(Mip { + width: dim(d.width, i, d.block), + height: dim(d.height, i, d.block), + depth: if three_d { dim(d.depth, i, 1) } else { 1 }, + pitch, + rows: h, + depth_pitch: if three_d { d.depth } else { 1 }, + offset, + tail: None, + }); + offset += u64::from(pitch) * u64::from(h) * bpe; + } + mips.reverse(); + Layout { + desc: d, + block: [align, 1, 1], + thick: false, + slices: d.depth, + slice_size: offset, + size: offset * u64::from(d.depth), + alignment: 256, + first_tail_mip: d.mips, + mips, + pattern: Default::default(), + } + } + + fn tiled(d: Desc, block_log2: u32) -> 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 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))] + } else { + // ComputeThinBlockDimension + let samples_log2 = d.samples.trailing_zeros(); + let elements_log2 = block_log2 - element_log2 - samples_log2; + let wide = samples_log2 & 1 == 0 || block_log2 & 1 != 0; + let w = (elements_log2 + u32::from(wide)) / 2; + [1 << w, 1 << (elements_log2 - w), 1] + }; + let slices = d.depth.next_multiple_of(block[2]); + let three_d = d.dimension == Dimension::Tex3d; + // Mip depths placed by a thick layout (thin ones store depth as + // slices). + 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 mut mips = Vec::with_capacity(d.mips as usize); + let mut first_tail_mip = d.mips; + let mut slice_size = 0u64; + if d.mips == 1 { + mips.push(Mip { + width: width(0), + height: height(0), + depth: depth_of(0), + pitch: width(0).next_multiple_of(block[0]), + rows: height(0).next_multiple_of(block[1]), + depth_pitch: if three_d { slices } else { 1 }, + offset: 0, + tail: None, + }); + 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; + if thick { + match block_log2 % 3 { + 0 => tail_max[1] >>= 1, + 1 => tail_max[0] >>= 1, + _ => tail_max[2] >>= 1, + } + } else { + tail_max[0] >>= 1; + } + // GetMaxNumMipsInTail; 256-byte blocks have no tail + // (`ComputeSurfaceInfoMicroTiled`). + let effective = if thick { + block_log2 - (block_log2 - 8) / 3 + } else { + block_log2 + }; + let max_in_tail = match effective { + 8 => 0, + 9..=11 => 1 + (1 << (effective - 9)), + _ => effective - 4, + }; + // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. + let mut fixed = tail_max; + if d.swizzle.z_order() && element_log2 <= 1 { + let b = BLOCK_256_2D[element_log2 as usize]; + fixed[0] /= b[0] / BLOCK_256_2D[2][0]; + fixed[1] /= b[1] / BLOCK_256_2D[2][1]; + } + let mut sizes = vec![]; + for i in 0..d.mips { + let (w, h) = padded(i); + if w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail { + first_tail_mip = i; + slice_size += block_bytes / u64::from(block[2]); + break; + } + let pitch = w.next_multiple_of(block[0]); + let rows = h.next_multiple_of(block[1]); + let depth = mip_depth(i).next_multiple_of(block[2]); + let one = u64::from(pitch) * u64::from(rows) * bpe; + slice_size += one; + sizes.push(one * u64::from(block[2])); + mips.push(Mip { + width: width(i), + height: height(i), + depth: depth_of(i), + pitch, + rows, + depth_pitch: if three_d { depth } else { 1 }, + offset: 0, + tail: None, + }); + } + // Standard mips from the smallest up, after the tail block. + let mut offset = if first_tail_mip < d.mips { + block_bytes + } else { + 0 + }; + for i in (0..first_tail_mip as usize).rev() { + mips[i].offset = offset; + offset += sizes[i]; + } + let micro = if thick { + let b = BLOCK_256_3D[element_log2 as usize]; + [b[0], b[1]] + } else { + BLOCK_256_2D[element_log2 as usize] + }; + let (mut pitch, mut rows) = (tail_max[0], tail_max[1]); + for i in first_tail_mip..d.mips { + let m = max_in_tail - 1 - (i - first_tail_mip); + let offset = if m > 6 { 16 << m } else { m << 8 }; + // Address bits 8.. of the offset, odd ones x, even ones y. + let bits = |from: u32| (0..6).map(|b| ((offset >> (from + 2 * b)) & 1) << b).sum(); + let (mut x, mut y): (u32, u32) = (bits(9), bits(8)); + if block_log2 & 1 != 0 { + std::mem::swap(&mut x, &mut y); + if element_log2 & 1 != 0 { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + mips.push(Mip { + width: width(i), + height: height(i), + depth: depth_of(i), + pitch, + rows, + depth_pitch: if thick { + mip_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2]) + } else { + 1 + }, + offset: 0, + tail: Some(Tail { + offset, + x: x * micro[0], + y: y * micro[1], + }), + }); + pitch = (pitch >> 1).max(micro[0]); + rows = (rows >> 1).max(micro[1]); + } + } + // Thick layouts store each depth slab's chain together. + let slab = if thick { u64::from(block[2]) } else { 1 }; + let slice_size = slice_size * slab; + let slices = slices / block[2]; + let addressable = !d.swizzle.xor() && d.samples == 1; + let pattern = if addressable { + let kind = if thick { + 2 + } else { + usize::from(d.swizzle.display()) + }; + pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) + } else { + Default::default() + }; + Layout { + desc: d, + block, + thick, + slices, + slice_size, + size: slice_size * u64::from(slices), + alignment: block_bytes, + first_tail_mip, + mips, + pattern, + } + } + + /// Whether [`Layout::offset`] and the copies work for this layout: + /// linear and the modes without pipe or bank XOR, single-sampled. + /// + /// shortcut: no addressing for the XOR modes (`_X`, `_T`) and MSAA; + /// they need the GPU's pipe and bank configuration (Series X and S + /// differ). Titles use them for render targets and depth, which the + /// host renders; add them when a title copies into or out of one. + pub fn addressable(&self) -> bool { + self.desc.swizzle == Swizzle::LINEAR || !self.pattern[0].is_empty() + } + + /// The slice and the depth inside it for `z` (an array slice or a 3D + /// depth slice). + fn split(&self, z: u32) -> (u32, u32) { + if self.thick { + (z / self.block[2], z % self.block[2]) + } else { + (z, 0) + } + } + + /// Byte offset of element (`x`, `y`) of mip `mip` in array slice or + /// depth slice `z`. Coordinates must lie inside the mip. + pub fn offset(&self, mip: u32, x: u32, y: u32, z: u32) -> Result<u64, Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let depth = if self.desc.dimension == Dimension::Tex3d { + m.depth + } else { + self.slices + }; + let inside = x < m.width && y < m.height && z < depth; + if !inside || !self.addressable() { + return Err(if inside { + Error::Unsupported + } else { + Error::Invalid + }); + } + let (slice, z) = self.split(z); + let base = u64::from(slice) * self.slice_size + m.offset; + if self.desc.swizzle == Swizzle::LINEAR { + let row = u64::from(y) * u64::from(m.pitch) + u64::from(x); + return Ok(base + row * u64::from(self.desc.element_bytes)); + } + Ok(base + self.row(m, y, z) + self.column(m, x)) + } + + /// The part of an address that depends on the row (and depth in a + /// thick block). + fn row(&self, m: &Mip, y: u32, z: u32) -> u64 { + let [bw, bh, _] = self.block; + let log2 = self.alignment.trailing_zeros(); + // In the tail the pattern of the shifted position gives the mip's + // 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]) + } + + /// The part of an address that depends on the column. + fn column(&self, m: &Mip, x: u32) -> u64 { + let bw = self.block[0]; + let x = x + m.tail.map_or(0, |t| t.x); + (u64::from(x / bw) << self.alignment.trailing_zeros()) + + u64::from(self.pattern[0][(x % bw) as usize]) + } + + /// Depth slices a subresource of mip `mip` covers: the mip's depth for + /// 3D textures, else 1 (one array slice). + pub fn subresource_depth(&self, mip: u32) -> u32 { + self.mips.get(mip as usize).map_or(0, |m| m.depth) + } + + /// Copies one subresource out of tiled memory (the whole texture, + /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice + /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are + /// `row_pitch` bytes apart, depth slices `depth_pitch`. + pub fn detile( + &self, + tiled: &[u8], + mip: u32, + slice: u32, + linear: &mut [u8], + 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 reverse of [`Layout::detile`]: linear rows into tiled memory. + pub fn tile( + &self, + tiled: &mut [u8], + mip: u32, + slice: u32, + linear: &[u8], + 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]); + }) + } + + /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). + #[allow(clippy::too_many_arguments)] + fn walk( + &self, + tiled_len: usize, + mip: u32, + slice: u32, + linear_len: usize, + row_pitch: usize, + depth_pitch: usize, + mut copy: impl FnMut(usize, usize, usize), + ) -> Result<(), Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let depth = m.depth; + let first = if self.desc.dimension == Dimension::Tex3d { + if slice != 0 { + return Err(Error::Invalid); + } + 0 + } else { + slice + }; + if first >= self.slices { + return Err(Error::Invalid); + } + if !self.addressable() { + return Err(Error::Unsupported); + } + let n = self.desc.element_bytes as usize; + let bytes = m.width as usize * n; + let need = (depth as usize - 1) + .checked_mul(depth_pitch) + .zip((m.height as usize - 1).checked_mul(row_pitch)) + .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset)) + .and_then(|offset| offset.checked_add(bytes)) + .ok_or(Error::TooSmall)?; + if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { + return Err(Error::TooSmall); + } + let linear = self.desc.swizzle == Swizzle::LINEAR; + // The row and depth contribute one common base to every column, so + // the same contiguous runs repeat on every row, including mip tails. + let mut runs = Vec::new(); + if !linear { + let mut first_linear = 0; + let mut first_tiled = self.column(m, 0) as usize; + for x in 1..m.width { + let offset = self.column(m, x) as usize; + let at = x as usize * n; + if offset != first_tiled + (at - first_linear) { + runs.push((first_tiled, first_linear, at - first_linear)); + first_tiled = offset; + first_linear = at; + } + } + runs.push((first_tiled, first_linear, bytes - first_linear)); + } + // A mip can end partway through the last run. Check the other runs + // once so each row can copy them with a compile-time length. + let (body, last) = runs.split_at(runs.len().saturating_sub(1)); + let run_len = body + .first() + .map(|run| run.2) + .filter(|&len| body.iter().all(|run| run.2 == len)); + for z in 0..depth { + let (s, inner) = self.split(first + z); + let base = u64::from(s) * self.slice_size + m.offset; + for y in 0..m.height { + let linear_row = z as usize * depth_pitch + y as usize * row_pitch; + if linear { + let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; + copy(tiled_row as usize, linear_row, bytes); + } else { + let tiled_row = (base + self.row(m, y, inner)) as usize; + match run_len { + Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy), + Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy), + Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy), + _ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy), + } + copy_runs::<0>(last, tiled_row, linear_row, &mut copy); + } + } + } + Ok(()) + } +} + +/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0. +fn copy_runs<const N: usize>( + runs: &[(usize, usize, usize)], + tiled_row: usize, + linear_row: usize, + copy: &mut impl FnMut(usize, usize, usize), +) { + for &(tiled, linear, len) in runs { + let len = if N == 0 { len } else { N }; + copy(tiled_row + tiled, linear_row + linear, len); + } +} + +/// What a DXGI format stores per element: bytes, texels per element side +/// (4 for block compression), and whether its stencil is a second plane +/// (the GPU keeps depth and stencil apart). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Format { + pub bytes: u32, + pub block: u32, + pub stencil: bool, +} + +/// By DXGI format number. `None` for 96-bit, 1-bit, packed 4:2:2 and video +/// formats. +/// +/// shortcut: those formats have no layout here; add them when a title uses +/// one. +pub fn format(dxgi: u32) -> Option<Format> { + let (bytes, block, stencil) = match dxgi { + 1..=4 => (16, 1, false), + 9..=18 => (8, 1, false), + 19..=22 | 44..=47 => (4, 1, true), + 23..=43 | 67 | 87..=93 | 116 | 117 => (4, 1, false), + 48..=59 | 85 | 86 | 115 => (2, 1, false), + 118..=120 => (2, 1, true), + 60..=65 => (1, 1, false), + 70..=72 | 79..=81 => (8, 4, false), + 73..=78 | 82..=84 | 94..=99 => (16, 4, false), + _ => return None, + }; + Some(Format { + bytes, + block, + stencil, + }) +} + +/// A texture as the console allocates it: a D3D12-style description with +/// a swizzle mode. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TextureDesc { + pub dimension: Dimension, + /// In texels. + pub width: u32, + pub height: u32, + /// Depth of a 3D texture, else the array size. + pub depth_or_array: u32, + /// 0: the full chain. + pub mips: u32, + /// DXGI format number. + pub format: u32, + pub samples: u32, + pub swizzle: Swizzle, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Plane { + /// From the start of the texture. + pub offset: u64, + pub stencil: bool, + pub layout: Layout, +} + +/// Every data plane of a texture (depth, then stencil), placed one after +/// the other. +/// +/// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC); +/// the console adds them to render targets and depth buffers unless the +/// description denies them, so those are smaller here than on the console. +/// The host GPU renders them, so nothing reads that memory; add the planes +/// if a title sizes a pool from console sizes and runs out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Texture { + pub planes: Vec<Plane>, + pub size: u64, + pub alignment: u64, +} + +impl Texture { + pub fn new(desc: &TextureDesc) -> Result<Texture, Error> { + let f = format(desc.format).ok_or(Error::Invalid)?; + let depth3d = if desc.dimension == Dimension::Tex3d { + desc.depth_or_array + } else { + 1 + }; + let mips = match desc.mips { + 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), + n => n, + }; + let plane = |bytes| Desc { + dimension: desc.dimension, + width: desc.width, + height: desc.height, + depth: desc.depth_or_array, + mips, + element_bytes: bytes, + block: f.block, + samples: desc.samples.max(1), + swizzle: desc.swizzle, + }; + let mut planes = vec![Plane { + offset: 0, + stencil: false, + layout: Layout::new(&plane(f.bytes))?, + }]; + if f.stencil { + let layout = Layout::new(&plane(1))?; + let offset = planes[0].layout.size.next_multiple_of(layout.alignment); + planes.push(Plane { + offset, + stencil: true, + layout, + }); + } + let last = &planes[planes.len() - 1]; + let size = last.offset + last.layout.size; + let alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1); + Ok(Texture { + planes, + size, + alignment, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(w: u32, h: u32, mips: u32, bpe: u32, swizzle: Swizzle) -> Desc { + Desc { + dimension: Dimension::Tex2d, + width: w, + height: h, + depth: 1, + mips, + element_bytes: bpe, + block: 1, + samples: 1, + swizzle, + } + } + + /// Sizes past the hardware's 16384 texels per side are refused instead + /// of overflowing the size arithmetic (found by random-input testing). + #[test] + fn extents_past_the_hardware_limit_are_invalid() { + for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] { + let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap(); + assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16); + for (w, h) in [ + (MAX_EXTENT + 1, 1), + (1, MAX_EXTENT + 1), + (u32::MAX, u32::MAX), + ] { + let result = Layout::new(&desc(w, h, 1, 16, swizzle)); + assert_eq!(result, Err(Error::Invalid), "{w}x{h}"); + } + let mut deep = desc(1, 1, 1, 16, swizzle); + deep.depth = u32::MAX; + assert_eq!(Layout::new(&deep), Err(Error::Invalid)); + } + } + + #[test] + fn blocks_hold_their_size_in_elements() { + for log2 in [8u32, 12, 16] { + let swizzle = match log2 { + 8 => Swizzle::SW_256B_S, + 12 => Swizzle::SW_4KB_S, + _ => Swizzle::SW_64KB_D, + }; + for e in 0..5 { + let l = Layout::new(&desc(1, 1, 1, 1 << e, swizzle)).unwrap(); + let [w, h, d] = l.block; + assert_eq!(u64::from(w * h * d) << e, 1 << log2, "{log2} {e}"); + // The pattern covers exactly the block's coordinates. + assert_eq!(l.pattern[0].len() as u32, w); + assert_eq!(l.pattern[1].len() as u32, h); + } + } + // 64 KiB, 16-byte elements: 64x64 (a 256x256 BC7 texture). + let l = Layout::new(&desc(64, 64, 1, 16, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.block, [64, 64, 1]); + assert_eq!((l.size, l.alignment), (65536, 65536)); + } + + /// Every element of every mip and slice lands on its own address, inside + /// the texture, and tiling then detiling gives the rows back. + #[test] + fn addresses_are_a_bijection_and_copies_round_trip() { + 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(40, 9, 3, 2, Swizzle::SW_64KB_S), + desc(30, 20, 5, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + Desc { + block: 4, + ..desc(109, 71, 6, 16, Swizzle::SW_256B_D) + }, + Desc { + depth: 3, + ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) + }, + 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 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 }; + for slice in 0..slices { + for mip in 0..d.mips { + let m = l.mips[mip as usize]; + let active = m.width as usize * n; + let row = active + 13; + let plane = row * m.height as usize + 11; + let linear: Vec<u8> = (0..plane * m.depth as usize) + .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8) + .collect(); + l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap(); + let mut back = vec![0xcc; linear.len()]; + l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap(); + for z in 0..m.depth { + let base = z as usize * plane; + for y in 0..m.height { + let start = base + y as usize * row; + assert_eq!(back[start..start + active], linear[start..start + active]); + assert!(back[start + active..start + row].iter().all(|&b| b == 0xcc)); + for x in 0..m.width { + let at = l.offset(mip, x, y, slice + z).unwrap() as usize; + let source = start + x as usize * n; + assert_eq!(tiled[at..at + n], linear[source..source + n]); + assert!(at + n <= seen.len(), "{d:?} mip {mip} outside"); + assert!(at.is_multiple_of(n)); + assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice"); + seen[at] = true; + } + } + assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); + } + } + } + } + } + + /// 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. + #[test] + fn hand_checked_addresses() { + let l = Layout::new(&desc(128, 128, 1, 4, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 2)); + assert_eq!(l.offset(0, 4, 0, 0), Ok(1 << 6)); + assert_eq!(l.offset(0, 0, 4, 0), Ok(1 << 7)); + assert_eq!(l.offset(0, 0, 8, 0), Ok(1 << 8)); + assert_eq!(l.offset(0, 64, 64, 0), Ok((1 << 15) | (1 << 14))); + let l = Layout::new(&desc(32, 32, 1, 16, Swizzle::SW_4KB_S)).unwrap(); + assert_eq!(l.block, [16, 16, 1]); + assert_eq!(l.offset(0, 0, 1, 0), Ok(1 << 4)); + assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 6)); + // Blocks row by row: (16, 0) is the second block, (0, 16) the third. + assert_eq!(l.offset(0, 16, 0, 0), Ok(4096)); + assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); + } + + /// 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] + fn mip_tail_comes_first() { + let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.first_tail_mip, 1); + assert_eq!(l.size, 2 * 65536); + assert_eq!(l.mips[0].offset, 65536); + assert_eq!( + l.mips[1].tail, + Some(Tail { + offset: 32768, + x: 32, + y: 0 + }) + ); + assert_eq!(l.offset(1, 0, 0, 0), Ok(32768)); + // 4 KiB blocks hold fewer tail mips: 16x16 BC7 mips stay outside. + let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_4KB_S)).unwrap(); + assert_eq!(l.first_tail_mip, 3); + assert_eq!(l.mips[2].offset, 4096); + assert_eq!(l.mips[1].offset, 8192); + assert_eq!(l.mips[0].offset, 8192 + 16384); + } + + #[test] + fn depth_stencil_is_two_planes() { + let t = Texture::new(&TextureDesc { + dimension: Dimension::Tex2d, + width: 1920, + height: 1080, + depth_or_array: 1, + mips: 1, + format: 20, + samples: 1, + swizzle: Swizzle::SW_64KB_Z_X, + }) + .unwrap(); + assert_eq!(t.planes.len(), 2); + // 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks. + assert_eq!(t.planes[0].layout.size, 1920 * 1152 * 4); + assert_eq!(t.planes[1].offset, t.planes[0].layout.size); + assert_eq!(t.planes[1].layout.size, 2048 * 1280); + assert!(!t.planes[0].layout.addressable()); + } + + #[test] + fn texture_copies_reject_overflowing_pitches() { + let layout = Layout::new(&desc(4, 2, 1, 4, Swizzle::LINEAR)).unwrap(); + let mut tiled = vec![0; layout.size as usize]; + let mut linear = [0; 32]; + assert_eq!( + layout.detile(&tiled, 0, 0, &mut linear, usize::MAX, 0), + Err(Error::TooSmall) + ); + assert_eq!( + layout.tile(&mut tiled, 0, 0, &linear, usize::MAX, 0), + Err(Error::TooSmall) + ); + } + + #[test] + fn volume_copy_rejects_overflowing_depth_pitch() { + let layout = Layout::new(&Desc { + dimension: Dimension::Tex3d, + depth: 3, + ..desc(4, 2, 1, 4, Swizzle::LINEAR) + }) + .unwrap(); + let tiled = vec![0; layout.size as usize]; + let mut linear = [0; 96]; + assert_eq!( + layout.detile(&tiled, 0, 0, &mut linear, 16, usize::MAX), + Err(Error::TooSmall) + ); + } + + #[test] + fn bad_descriptions_and_buffers_are_refused() { + assert_eq!( + Layout::new(&desc(0, 4, 1, 4, Swizzle::SW_4KB_S)), + Err(Error::Invalid) + ); + assert_eq!( + Layout::new(&desc(4, 4, 1, 12, Swizzle::SW_4KB_S)), + Err(Error::Invalid) + ); + assert_eq!( + Layout::new(&desc(4, 4, 1, 4, Swizzle(3))), + Err(Error::Invalid) + ); + let l = Layout::new(&desc(64, 64, 1, 4, Swizzle::SW_4KB_S)).unwrap(); + let mut out = vec![0; 64 * 64 * 4]; + assert_eq!( + l.detile(&[0; 100], 0, 0, &mut out, 256, 0), + Err(Error::TooSmall) + ); + assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid)); + } +} diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs new file mode 100644 index 000000000..e6ca93150 --- /dev/null +++ b/crates/victory-formats/src/xma.rs @@ -0,0 +1,1247 @@ +//! XMA2, the console's hardware audio codec: mono or stereo WMA Pro frames of +//! 512 samples per channel, packed into 2048-byte packets. +//! +//! A packet starts with a 32-bit header (MSB first): the number of frames +//! that begin in it (6 bits), the number of bits that finish the previous +//! frame before the first new one (15), metadata (3) and how many packets of +//! other streams follow before this stream's next packet (8). Every frame +//! starts with its length in bits (15) and ends with a "more frames" bit. +//! +//! The frame decoder follows FFmpeg's `wmaprodec.c` (LGPL-2.1-or-later, used +//! under GPL-3.0-or-later) restricted to what XMA needs: at most two +//! channels, four subframe sizes (512 down to 128), no LFE channel. + +mod tables; + +use std::sync::OnceLock; + +use tables::*; + +pub const PACKET_BYTES: usize = 2048; +const PACKET_BITS: usize = PACKET_BYTES * 8; +const HEADER_BITS: usize = 32; +/// Samples per channel in one frame. +pub const FRAME_SAMPLES: usize = 512; +/// Samples per channel in one subframe, the unit of skips and loop ends. +pub const SUBFRAME_SAMPLES: usize = 128; +const LENGTH_BITS: u32 = 15; +/// 512 >> 2: the smallest subframe. +const MIN_SUBFRAME: usize = SUBFRAME_SAMPLES; +const BLOCK_SIZES: usize = 3; +const MAX_BANDS: usize = 29; +const MAX_SUBFRAMES: usize = 32; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(pub &'static str); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "XMA: {}", self.0) + } +} + +impl std::error::Error for Error {} + +// Packets. + +/// A packet's header fields. +#[derive(Debug, Clone, Copy)] +pub struct Packet { + pub frames: u32, + pub first_frame_bit: u32, + pub skip: u32, +} + +pub fn packet(data: &[u8], index: usize) -> Option<Packet> { + let start = index.checked_mul(PACKET_BYTES)?; + let b = data.get(start..)?.get(..4)?; + let h = u32::from_be_bytes([b[0], b[1], b[2], b[3]]); + Some(Packet { + frames: h >> 26, + first_frame_bit: (h >> 11) & 0x7fff, + skip: h & 0xff, + }) +} + +/// One frame's bits gathered out of its packets. +#[derive(Debug, Clone)] +pub struct Frame { + /// The frame from its length field on, MSB first. + pub data: Vec<u8>, + pub bits: usize, + /// Bit offset in the buffer where it starts, and where the next frame + /// starts (`None` when the buffer has no further frame). + pub start: usize, + pub next: Option<usize>, +} + +/// Bit positions in a buffer of packets, skipping each packet's header and +/// the packets of other streams. +struct Cursor<'a> { + data: &'a [u8], + pos: usize, +} + +impl Cursor<'_> { + fn bit(&mut self) -> Option<u32> { + if self.pos.is_multiple_of(PACKET_BITS) { + // Leaving a packet: jump over the other streams' packets. + let previous = self.pos / PACKET_BITS; + if previous > 0 { + let skip = packet(self.data, previous - 1)?.skip as usize; + self.pos = (previous + skip) * PACKET_BITS; + } + self.pos += HEADER_BITS; + } + let byte = *self.data.get(self.pos / 8)?; + let bit = (byte >> (7 - self.pos % 8)) & 1; + self.pos += 1; + Some(bit as u32) + } + + fn bits(&mut self, n: u32) -> Option<u32> { + (0..n).try_fold(0, |v, _| Some(v << 1 | self.bit()?)) + } +} + +/// Reads the frame starting at bit `start` (a frame start inside a packet's +/// payload) of `data`, a buffer of whole packets of one stream. +pub fn read_frame(data: &[u8], start: usize) -> Option<Frame> { + let mut cursor = Cursor { data, pos: start }; + let bits = cursor.bits(LENGTH_BITS)? as usize; + if bits <= LENGTH_BITS as usize || bits == 0x7fff { + return None; + } + let mut out = vec![0u8; bits.div_ceil(8)]; + let mut cursor = Cursor { data, pos: start }; + for i in 0..bits { + out[i / 8] |= (cursor.bit()? as u8) << (7 - i % 8); + } + let end = cursor.pos; + let next = next_frame(data, start, end); + Some(Frame { + data: out, + bits, + start, + next, + }) +} + +/// Where the frame after the one at `start`..`end` begins: right after it, +/// unless it was the last frame to begin in its packet and the rest of that +/// packet is padding. +fn next_frame(data: &[u8], start: usize, end: usize) -> Option<usize> { + let index = start / PACKET_BITS; + let header = packet(data, index)?; + let mut at = index * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; + let mut number = 0; + while at < start { + let mut cursor = Cursor { data, pos: at }; + let bits = cursor.bits(LENGTH_BITS)? as usize; + // The same rule as `read_frame`: a length that does not cover its own + // field is not a frame. A zero length would never move `at`, so a + // damaged packet would loop here for good. + if bits <= LENGTH_BITS as usize { + return None; + } + at += bits; + number += 1; + } + let last = number + 1 >= header.frames; + 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 header = packet(data, next)?; + end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; + } + (end / 8 < data.len()).then_some(end) +} + +// Bitstream reading inside a frame. + +struct Bits<'a> { + data: &'a [u8], + pos: usize, + end: usize, +} + +impl Bits<'_> { + fn peek32(&self) -> u32 { + let mut v = 0u64; + let byte = self.pos / 8; + for i in 0..5 { + v = v << 8 | *self.data.get(byte + i).unwrap_or(&0) as u64; + } + (v << (24 + self.pos % 8) >> 32) as u32 + } + + fn read(&mut self, n: u32) -> u32 { + if n == 0 { + return 0; + } + let v = self.peek32() >> (32 - n); + self.pos += n as usize; + v + } + + fn bit(&mut self) -> bool { + self.read(1) != 0 + } + + fn signed(&mut self, n: u32) -> i32 { + ((self.read(n) << (32 - n)) as i32) >> (32 - n) + } + + fn consumed(&self) -> usize { + self.pos + } + + fn overread(&self) -> bool { + self.pos > self.end + } +} + +/// A prefix code built like FFmpeg's `ff_vlc_init_from_lengths`: codes are +/// handed out in table order, each the next free one of its length. +struct Vlc { + /// Left-aligned code, length, symbol; sorted by code. + codes: Vec<(u32, u8, i32)>, +} + +impl Vlc { + fn new(entries: impl Iterator<Item = (i32, u8)>) -> Vlc { + let mut code = 0u64; + let mut codes = Vec::new(); + for (symbol, len) in entries { + codes.push((code as u32, len, symbol)); + code += 1 << (32 - len); + } + Vlc { codes } + } + + fn read(&self, bits: &mut Bits) -> i32 { + let v = bits.peek32(); + let i = self.codes.partition_point(|c| c.0 <= v) - 1; + let (_, len, symbol) = self.codes[i]; + bits.pos += len as usize; + symbol + } +} + +struct Codes { + scale: Vlc, + scale_rl: Vlc, + coef: [Vlc; 2], + vec4: Vlc, + vec2: Vlc, + vec1: Vlc, +} + +fn codes() -> &'static Codes { + static CODES: OnceLock<Codes> = OnceLock::new(); + CODES.get_or_init(|| { + let pairs = |t: &'static [(u16, u8)], offset: i32| { + Vlc::new(t.iter().map(move |&(s, l)| (s as i32 + offset, l))) + }; + 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))), + pairs(&COEF1, 0), + ], + 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), + } + }) +} + +/// `ff_wma_get_large_val`. +fn large_value(bits: &mut Bits) -> u32 { + let mut n = 8; + if bits.bit() { + n += 8; + if bits.bit() { + n += 8; + if bits.bit() { + n += 7; + } + } + } + bits.read(n) +} + +fn log2(v: usize) -> u32 { + usize::BITS - 1 - v.max(1).leading_zeros() +} + +// The inverse transform. + +/// Half-length inverse MDCT as FFmpeg defines it (`av_tx` MDCT, inverse): +/// `n` coefficients to the middle `n` samples of the 2n-sample window, +/// negated and scaled by `scale`. Computed as a DCT-IV through an +/// n/2-point complex FFT. +fn imdct_half(input: &[f32], out: &mut [f32], scale: f32) { + let n = input.len(); + let m = n / 2; + let mut re = vec![0f64; m]; + let mut im = vec![0f64; m]; + for k in 0..m { + let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64); + let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); + (re[k], im[k]) = (a * c - b * s, a * s + b * c); + } + fft(&mut re, &mut im); + for k in 0..m { + let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); + let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c); + // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j]. + out[n - 1 - 2 * k] = (wr as f32) * scale; + out[2 * k] = -(wi as f32) * scale; + } +} + +/// In-place radix-2 forward DFT (`exp(-2Ï€i nk/N)`). +fn fft(re: &mut [f64], im: &mut [f64]) { + let n = re.len(); + let mut j = 0; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut len = 2; + while len <= n { + let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); + for start in (0..n).step_by(len) { + let (mut cr, mut ci) = (1.0, 0.0); + for k in 0..len / 2 { + let (a, b) = (start + k, start + k + len / 2); + let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr); + (re[b], im[b]) = (re[a] - tr, im[a] - ti); + (re[a], im[a]) = (re[a] + tr, im[a] + ti); + (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); + } + } + len <<= 1; + } +} + +/// `ff_sine_windows`: the rising half of a sine window of length `n`. +fn sine_window(n: usize) -> Vec<f32> { + (0..n) + .map(|i| ((i as f64 + 0.5) * std::f64::consts::PI / (2.0 * n as f64)).sin() as f32) + .collect() +} + +// The frame decoder. + +#[derive(Clone)] +struct Channel { + prev_block_len: usize, + transmit_coefs: bool, + num_subframes: usize, + subframe_len: [usize; MAX_SUBFRAMES], + cur_subframe: usize, + decoded_samples: usize, + quant_step: i32, + reuse_sf: bool, + scale_factor_step: i32, + max_scale_factor: i32, + saved_scale_factors: [[i32; MAX_BANDS]; 2], + scale_factor_idx: usize, + /// Which of the two saved sets is in use for this subframe. + scale_factors: usize, + table_idx: usize, + num_vec_coeffs: usize, + coeffs: [f32; FRAME_SAMPLES], + /// The frame's output, then half a frame of overlap for the next one. + out: [f32; FRAME_SAMPLES + FRAME_SAMPLES / 2], +} + +impl Channel { + fn new() -> Self { + Channel { + prev_block_len: FRAME_SAMPLES, + transmit_coefs: false, + num_subframes: 0, + subframe_len: [0; MAX_SUBFRAMES], + cur_subframe: 0, + decoded_samples: 0, + quant_step: 0, + reuse_sf: false, + scale_factor_step: 1, + max_scale_factor: 0, + saved_scale_factors: [[0; MAX_BANDS]; 2], + scale_factor_idx: 0, + scale_factors: 0, + table_idx: 0, + num_vec_coeffs: 0, + coeffs: [0.0; FRAME_SAMPLES], + out: [0.0; FRAME_SAMPLES + FRAME_SAMPLES / 2], + } + } +} + +/// Decodes the frames of one mono or stereo stream. +#[derive(Clone)] +pub struct Decoder { + channels: usize, + num_sfb: [usize; BLOCK_SIZES], + sfb_offsets: [[usize; MAX_BANDS + 1]; BLOCK_SIZES], + sf_offsets: [[[usize; MAX_BANDS]; BLOCK_SIZES]; BLOCK_SIZES], + ch: [Channel; 2], + // Per subframe. + subframe_len: usize, + channels_for_cur_subframe: usize, + channel_indexes: [usize; 2], + num_bands: usize, + table_idx: usize, + esc_len: u32, + transmit_num_vec_coeffs: bool, + transform: bool, + transform_band: [bool; MAX_BANDS], + parsed_all_subframes: bool, +} + +/// What the decoder needs from the stream format: the channel count and +/// the sample rate, which sets the scale factor band layout. +impl Decoder { + pub fn new(channels: usize, sample_rate: u32) -> Decoder { + let channels = channels.clamp(1, 2); + let rate = match sample_rate { + r if r > 44_100 => 48_000, + r if r > 32_000 => 44_100, + r if r > 24_000 => 32_000, + _ => 24_000, + }; + let mut sfb_offsets = [[0usize; MAX_BANDS + 1]; BLOCK_SIZES]; + let mut num_sfb = [0usize; BLOCK_SIZES]; + for i in 0..BLOCK_SIZES { + let subframe_len = FRAME_SAMPLES >> i; + let offsets = &mut sfb_offsets[i]; + let mut band = 1; + for &freq in CRITICAL_FREQ.iter().take(MAX_BANDS - 1) { + if offsets[band - 1] >= subframe_len { + break; + } + let offset = ((subframe_len * 2 * freq as usize) / rate + 2) & !3; + if offset > offsets[band - 1] { + offsets[band] = offset; + band += 1; + } + if offset >= subframe_len { + break; + } + } + offsets[band - 1] = subframe_len; + num_sfb[i] = band - 1; + } + let mut sf_offsets = [[[0usize; MAX_BANDS]; BLOCK_SIZES]; BLOCK_SIZES]; + for i in 0..BLOCK_SIZES { + for b in 0..num_sfb[i] { + let offset = ((sfb_offsets[i][b] + sfb_offsets[i][b + 1] - 1) << i) >> 1; + for x in 0..BLOCK_SIZES { + let mut v = 0; + while v + 1 < MAX_BANDS && (sfb_offsets[x][v + 1] << x) < offset { + v += 1; + } + sf_offsets[i][x][b] = v; + } + } + } + Decoder { + channels, + num_sfb, + sfb_offsets, + sf_offsets, + ch: [Channel::new(), Channel::new()], + subframe_len: FRAME_SAMPLES, + channels_for_cur_subframe: 0, + channel_indexes: [0, 1], + num_bands: 0, + table_idx: 0, + esc_len: 0, + transmit_num_vec_coeffs: false, + transform: false, + transform_band: [false; MAX_BANDS], + parsed_all_subframes: false, + } + } + + pub fn channels(&self) -> usize { + self.channels + } + + /// Forgets the overlap with earlier frames (a new stream or a seek). + pub fn reset(&mut self) { + self.ch = [Channel::new(), Channel::new()]; + } + + /// Decodes one frame (`frame.data`, `frame.bits`) and appends + /// `FRAME_SAMPLES` interleaved samples per channel to `out`. + pub fn decode(&mut self, data: &[u8], bits: usize, out: &mut Vec<i16>) -> Result<(), Error> { + let mut b = Bits { + data, + pos: 0, + end: bits, + }; + let len = b.read(LENGTH_BITS) as usize; + let result = self.frame(&mut b, len); + if result.is_err() { + // Whatever the frame held is lost; keep the stream's timing. + for c in 0..self.channels { + self.ch[c].out = [0.0; FRAME_SAMPLES + FRAME_SAMPLES / 2]; + } + } + for i in 0..FRAME_SAMPLES { + for c in 0..self.channels { + out.push(to_i16(self.ch[c].out[i])); + } + } + for c in 0..self.channels { + self.ch[c].out.copy_within(FRAME_SAMPLES.., 0); + } + result + } + + /// The overlap left after the last frame, then silence: half a frame of + /// samples per channel. + pub fn flush(&mut self, out: &mut Vec<i16>) { + for i in 0..FRAME_SAMPLES / 2 { + for c in 0..self.channels { + out.push(to_i16(self.ch[c].out[i])); + } + } + self.reset(); + } + + fn frame(&mut self, b: &mut Bits, len: usize) -> Result<(), Error> { + self.tile_header(b)?; + // Post-processing transform. + if self.channels > 1 && b.bit() && b.bit() { + b.read((self.channels * self.channels * 4) as u32); + } + // Dynamic range compression gain, unused. + b.read(8); + if b.bit() { + // Trim at start and end, which only WMA Pro files apply. + if b.bit() { + b.read(log2(FRAME_SAMPLES * 2)); + } + if b.bit() { + b.read(log2(FRAME_SAMPLES * 2)); + } + } + self.parsed_all_subframes = false; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + ch.decoded_samples = 0; + ch.cur_subframe = 0; + ch.reuse_sf = false; + } + while !self.parsed_all_subframes { + self.subframe(b)?; + } + // FFmpeg flags `len != consumed + 2` but keeps the samples; so do we. + if b.overread() || b.consumed() > len { + return Err(Error("frame overread")); + } + Ok(()) + } + + fn subframe_length(&self, b: &mut Bits, offset: usize) -> Result<usize, Error> { + if offset == FRAME_SAMPLES - MIN_SUBFRAME { + return Ok(MIN_SUBFRAME); + } + // Four subframe sizes: a 1-bit "not maximal", then 1 bit of shift. + let shift = if b.bit() { 1 + b.read(1) } else { 0 }; + let len = FRAME_SAMPLES >> shift; + if len < MIN_SUBFRAME { + return Err(Error("subframe length")); + } + Ok(len) + } + + fn tile_header(&mut self, b: &mut Bits) -> Result<(), Error> { + let mut num_samples = [0usize; 2]; + let mut contains = [false; 2]; + let mut channels_for_cur_subframe = self.channels; + let mut min_channel_len = 0; + for c in 0..self.channels { + self.ch[c].num_subframes = 0; + } + let fixed = b.bit(); + loop { + for c in 0..self.channels { + contains[c] = num_samples[c] == min_channel_len + && (fixed + || channels_for_cur_subframe == 1 + || min_channel_len == FRAME_SAMPLES - MIN_SUBFRAME + || b.bit()); + } + let subframe_len = self.subframe_length(b, min_channel_len)?; + min_channel_len += subframe_len; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + if contains[c] { + if ch.num_subframes >= MAX_SUBFRAMES { + return Err(Error("too many subframes")); + } + ch.subframe_len[ch.num_subframes] = subframe_len; + num_samples[c] += subframe_len; + ch.num_subframes += 1; + if num_samples[c] > FRAME_SAMPLES { + return Err(Error("channel longer than a frame")); + } + } else if num_samples[c] <= min_channel_len { + if num_samples[c] < min_channel_len { + channels_for_cur_subframe = 0; + min_channel_len = num_samples[c]; + } + channels_for_cur_subframe += 1; + } + } + if min_channel_len >= FRAME_SAMPLES || b.overread() { + break; + } + } + if b.overread() { + return Err(Error("tile header")); + } + Ok(()) + } + + fn channel_transform(&mut self, b: &mut Bits) -> Result<(), Error> { + self.transform = false; + if self.channels == 1 { + return Ok(()); + } + if b.bit() { + return Err(Error("channel transform bit")); + } + // One group holding every channel of the subframe. + if self.channels_for_cur_subframe == 2 { + if b.bit() { + if b.bit() { + return Err(Error("channel transform type")); + } + } else { + self.transform = true; + } + } + if self.transform { + if !b.bit() { + for i in 0..self.num_bands { + self.transform_band[i] = b.bit(); + } + } else { + self.transform_band = [true; MAX_BANDS]; + } + } + Ok(()) + } + + fn coefficients(&mut self, b: &mut Bits, c: usize) -> Result<(), Error> { + let codes = codes(); + let table = b.bit() as usize; + let (run, level): (&[u16], &[f32]) = if table == 1 { + (&COEF1_RUN, &COEF1_LEVEL) + } else { + (&COEF0_RUN, &COEF0_LEVEL) + }; + let subframe_len = self.subframe_len; + let ch = &mut self.ch[c]; + let mut rl_mode = false; + let mut cur = 0; + let mut num_zeros = 0; + while (self.transmit_num_vec_coeffs || !rl_mode) && cur + 3 < ch.num_vec_coeffs { + let mut vals = [0u32; 4]; + let idx = codes.vec4.read(b); + if idx < 0 { + for i in (0..4).step_by(2) { + let idx = codes.vec2.read(b); + if idx < 0 { + for v in &mut vals[i..i + 2] { + let mut x = codes.vec1.read(b) as u32; + if x as usize == VEC1.len() - 1 { + x += large_value(b); + } + *v = x; + } + } else { + vals[i] = (idx >> 4) as u32; + vals[i + 1] = (idx & 0xf) as u32; + } + } + } else { + vals = [ + (idx >> 12) as u32, + ((idx >> 8) & 0xf) as u32, + ((idx >> 4) & 0xf) as u32, + (idx & 0xf) as u32, + ]; + } + for v in vals { + if v != 0 { + let negative = !b.bit(); + ch.coeffs[cur] = if negative { -(v as f32) } else { v as f32 }; + num_zeros = 0; + } else { + ch.coeffs[cur] = 0.0; + num_zeros += 1; + rl_mode |= num_zeros > subframe_len >> 8; + } + cur += 1; + } + if b.overread() { + return Err(Error("vector coefficients")); + } + } + if cur < subframe_len { + ch.coeffs[cur..subframe_len].fill(0.0); + // `ff_wma_run_level_decode`, version 1. + let mask = subframe_len - 1; + let mut offset = cur; + while offset < subframe_len { + let code = codes.coef[table].read(b); + if code > 1 { + offset += run[code as usize] as usize; + let negative = !b.bit(); + let v = level[code as usize]; + ch.coeffs[offset & mask] = if negative { -v } else { v }; + } else if code == 1 { + break; + } else { + let value = large_value(b) as i32; + if b.bit() { + if b.bit() { + if b.bit() { + // A broken escape ends the channel's + // coefficients, as in FFmpeg. + break; + } + offset += b.read(self.esc_len) as usize + 4; + } else { + offset += b.read(2) as usize + 1; + } + } + let negative = !b.bit(); + ch.coeffs[offset & mask] = if negative { -value } else { value } as f32; + } + if b.overread() { + return Err(Error("run level coefficients")); + } + offset += 1; + } + } + Ok(()) + } + + fn scale_factors(&mut self, b: &mut Bits) -> Result<(), Error> { + let codes = codes(); + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + let sf_offsets = self.sf_offsets[self.table_idx][self.ch[c].table_idx]; + let ch = &mut self.ch[c]; + let target = 1 - ch.scale_factor_idx; + 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) { + *sf = from[offset]; + } + } + if ch.cur_subframe == 0 || b.bit() { + if !ch.reuse_sf { + ch.scale_factor_step = b.read(2) as i32 + 1; + let mut val = 45 / ch.scale_factor_step; + for band in 0..self.num_bands { + val += codes.scale.read(b); + ch.saved_scale_factors[target][band] = val; + } + } else { + let mut band = 0; + while band < self.num_bands { + let idx = codes.scale_rl.read(b); + let (skip, val, negative) = match idx { + 0 => { + let code = b.read(14); + ((code & 0x3f) >> 1, (code >> 6) as i32, code & 1 == 0) + } + 1 => break, + _ => ( + SCALE_RL_RUN[idx as usize] as u32, + SCALE_RL_LEVEL[idx as usize] as i32, + !b.bit(), + ), + }; + band += skip as usize; + if band >= self.num_bands { + return Err(Error("scale factor run")); + } + ch.saved_scale_factors[target][band] += if negative { -val } else { val }; + band += 1; + } + } + ch.scale_factor_idx = target; + ch.table_idx = self.table_idx; + ch.reuse_sf = true; + } + let sf = &ch.saved_scale_factors[ch.scale_factors][..self.num_bands]; + ch.max_scale_factor = sf.iter().copied().max().unwrap_or(0); + } + Ok(()) + } + + fn subframe(&mut self, b: &mut Bits) -> Result<(), Error> { + let mut offset = FRAME_SAMPLES; + let mut subframe_len = FRAME_SAMPLES; + let mut total_samples = FRAME_SAMPLES * self.channels; + for c in 0..self.channels { + let ch = &self.ch[c]; + if offset > ch.decoded_samples { + offset = ch.decoded_samples; + subframe_len = ch.subframe_len[ch.cur_subframe.min(MAX_SUBFRAMES - 1)]; + } + } + self.channels_for_cur_subframe = 0; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + total_samples -= ch.decoded_samples; + if offset == ch.decoded_samples + && ch.cur_subframe < ch.num_subframes + && subframe_len == ch.subframe_len[ch.cur_subframe] + { + total_samples -= subframe_len; + ch.decoded_samples += subframe_len; + self.channel_indexes[self.channels_for_cur_subframe] = c; + self.channels_for_cur_subframe += 1; + } + } + if self.channels_for_cur_subframe == 0 { + return Err(Error("no channel in subframe")); + } + if total_samples == 0 { + self.parsed_all_subframes = true; + } + self.table_idx = log2(FRAME_SAMPLES / subframe_len) as usize; + self.num_bands = self.num_sfb[self.table_idx]; + self.subframe_len = subframe_len; + self.esc_len = log2(subframe_len - 1) + 1; + + // Extended header: fill bits. + if b.bit() { + let mut fill = b.read(2) as usize; + if fill == 0 { + let len = b.read(4); + fill = b.read(len) as usize + 1; + } + b.pos += fill; + } + if b.bit() { + return Err(Error("reserved bit")); + } + self.channel_transform(b)?; + + let mut transmit_coeffs = false; + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + self.ch[c].transmit_coefs = b.bit(); + transmit_coeffs |= self.ch[c].transmit_coefs; + } + if transmit_coeffs { + self.transmit_num_vec_coeffs = b.bit(); + if self.transmit_num_vec_coeffs { + let num_bits = log2(subframe_len.div_ceil(4)) + 1; + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + let n = (b.read(num_bits) << 2) as usize; + if n > subframe_len { + return Err(Error("vector coefficient count")); + } + self.ch[c].num_vec_coeffs = n; + } + } else { + for i in 0..self.channels_for_cur_subframe { + self.ch[self.channel_indexes[i]].num_vec_coeffs = subframe_len; + } + } + // Quantisation step (16-bit samples: 90 * 16 >> 4). + let mut quant_step = 90; + let mut step = b.signed(6); + quant_step += step; + if step == -32 || step == 31 { + let negative = step == -32; + let mut quant = 0; + while b.pos + 5 < b.end { + step = b.read(5) as i32; + if step != 31 { + break; + } + quant += 31; + } + 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; + } else { + let modifier_len = b.read(3); + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + self.ch[c].quant_step = quant_step; + if b.bit() { + self.ch[c].quant_step += if modifier_len > 0 { + b.read(modifier_len) as i32 + 1 + } else { + 1 + }; + } + } + } + self.scale_factors(b)?; + } + + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + if self.ch[c].transmit_coefs && b.pos < b.end { + self.coefficients(b, c)?; + } else { + self.ch[c].coeffs[..subframe_len].fill(0.0); + } + } + + // Where this subframe's samples go in the channel output. + let at = offset + FRAME_SAMPLES / 2; + if transmit_coeffs { + self.inverse_channel_transform(); + // Output in [-1, 1] for 16-bit streams. + let scale = 2.0 / subframe_len as f32 / 32768.0; + let sfb = self.sfb_offsets[self.table_idx]; + let mut tmp = [0f32; FRAME_SAMPLES]; + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + 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 quant = 10f32.powf(exp as f32 / 20.0); + 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); + } + } else { + for i in 0..self.channels_for_cur_subframe { + self.ch[self.channel_indexes[i]].out[at..at + subframe_len].fill(0.0); + } + } + + // Window and overlap-add with the previous block. + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + let mut winlen = ch.prev_block_len; + let mut start = at - winlen / 2; + if subframe_len < winlen { + start += (winlen - subframe_len) / 2; + winlen = subframe_len; + } + window_overlap(&mut ch.out[start..start + winlen], &windows()[log2(winlen) as usize - 7]); + ch.prev_block_len = subframe_len; + } + + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + if ch.cur_subframe >= ch.num_subframes { + return Err(Error("subframe overrun")); + } + ch.cur_subframe += 1; + } + if b.overread() { + return Err(Error("subframe overread")); + } + Ok(()) + } + + fn inverse_channel_transform(&mut self) { + if !self.transform || self.channels_for_cur_subframe != 2 { + return; + } + let sfb = self.sfb_offsets[self.table_idx]; + let [a, b] = &mut self.ch; + for band in 0..self.num_bands { + let range = sfb[band]..sfb[band + 1].min(self.subframe_len); + if self.transform_band[band] { + for y in range { + let (l, r) = (a.coeffs[y], b.coeffs[y]); + (a.coeffs[y], b.coeffs[y]) = (l - r, l + r); + } + } else { + for y in range { + a.coeffs[y] *= 181.0 / 128.0; + b.coeffs[y] *= 181.0 / 128.0; + } + } + } + } +} + +/// Sine windows for blocks of 128, 256 and 512 samples. +fn windows() -> &'static [Vec<f32>; 3] { + static WINDOWS: OnceLock<[Vec<f32>; 3]> = OnceLock::new(); + WINDOWS.get_or_init(|| [sine_window(128), sine_window(256), sine_window(512)]) +} + +/// FFmpeg's `vector_fmul_window` in place: the first half of `block` holds +/// the previous block's tail, the second half the current block's head. +fn window_overlap(block: &mut [f32], window: &[f32]) { + let len = block.len() / 2; + for k in 0..len { + let (i, j) = (k, 2 * len - 1 - k); + let (s0, s1) = (block[i], block[2 * len - 1 - k]); + let (wi, wj) = (window[i], window[j]); + block[i] = s0 * wj - s1 * wi; + block[j] = s0 * wi + s1 * wj; + } +} + +fn to_i16(v: f32) -> i16 { + (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Writes `value` as `n` bits, MSB first, at bit `pos`. + fn put_bits(data: &mut [u8], pos: usize, n: u32, value: u32) { + for i in 0..n as usize { + if value >> (n as usize - 1 - i) & 1 == 1 { + data[(pos + i) / 8] |= 1 << (7 - (pos + i) % 8); + } + } + } + + /// A damaged packet whose first frame says it is 0 bits long: finding + /// the frame after a later one must give up, not walk in place forever + /// (found by random-input testing). + #[test] + fn a_zero_length_frame_before_the_start_ends_the_search() { + let mut data = vec![0u8; PACKET_BYTES]; + // Two frames, the first at payload bit 0; its 15-bit length stays 0. + put_bits(&mut data, 0, 32, 2 << 26); + let start = HEADER_BITS + 100; + put_bits(&mut data, start, LENGTH_BITS, 200); + let frame = read_frame(&data, start).expect("the frame at `start` is well formed"); + assert_eq!(frame.bits, 200); + assert_eq!(frame.next, None); + } + + /// The direct sum `imdct_half` stands for (FFmpeg's naive inverse MDCT: + /// the standard formula, negated). + fn imdct_reference(input: &[f32]) -> Vec<f32> { + let n = input.len(); + (0..n) + .map(|j| { + let t = (j + n / 2) as f64 + 0.5 + n as f64 / 2.0; + -(input + .iter() + .enumerate() + .map(|(k, &x)| x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos()) + .sum::<f64>() as f32) + }) + .collect() + } + + #[test] + fn fast_imdct_matches_the_direct_sum() { + for n in [128usize, 256, 512] { + let input: Vec<f32> = (0..n).map(|i| ((i * 7919) % 97) as f32 - 48.0).collect(); + let mut fast = vec![0f32; n]; + imdct_half(&input, &mut fast, 1.0); + let reference = imdct_reference(&input); + for (a, b) in fast.iter().zip(&reference) { + assert!((a - b).abs() < 1e-2 * (1.0 + b.abs()), "n {n}: {a} vs {b}"); + } + } + } + + /// Windowed MDCT blocks of a signal, put back together the way the + /// decoder does (half IMDCT, then window and overlap), give the signal. + #[test] + fn imdct_and_window_reconstruct_a_signal() { + let n = 256; + let signal: Vec<f32> = (0..n * 6).map(|i| (i as f32 * 0.05).sin() * 0.3).collect(); + // The 2n-sample sine window; its rising half is `sine_window(n)`. + let window = |i: usize| ((i as f64 + 0.5) * std::f64::consts::PI / (2.0 * n as f64)).sin(); + let mut out = vec![0f32; n * 7]; + for block in 0..5 { + let base = block * n; + let coeffs: Vec<f32> = (0..n) + .map(|k| { + (0..2 * n) + .map(|i| { + let t = i as f64 + 0.5 + n as f64 / 2.0; + // FFmpeg's forward MDCT pairs with its inverse + // by sign. + -signal[base + i] as f64 + * window(i) + * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos() + }) + .sum::<f64>() as f32 + }) + .collect(); + // The half output is the middle of the 2n window. + let at = base + n / 2; + imdct_half(&coeffs, &mut out[at..at + n], 2.0 / n as f32); + if block > 0 { + window_overlap(&mut out[at - n / 2..at + n / 2], &sine_window(n)); + } + } + for i in n..5 * n { + assert!((out[i] - signal[i]).abs() < 1e-3, "{i}: {} vs {}", out[i], signal[i]); + } + } + + #[test] + fn packet_rejects_out_of_range_indices_and_partial_headers() { + assert!(packet(&[0; 4], usize::MAX / PACKET_BYTES + 1).is_none()); + assert!(packet(&[0; 3], 0).is_none()); + } + + #[test] + fn packet_headers_and_frame_walk() { + // Two packets: frame A (100 bits) and B (16300 bits, crossing into + // packet 1 by 48 bits), then C (60 bits) in packet 1; the rest is + // padding. + let mut data = vec![0xffu8; 2 * PACKET_BYTES]; + let header = |frames: u32, first: u32| (frames << 26) | (first << 11); + let bits = [(0, header(2, 0), 32), (PACKET_BITS, header(1, 48), 32)]; + let put = |data: &mut Vec<u8>, at: usize, value: u32, width: u32| { + for i in 0..width as usize { + let bit = (value >> (width as usize - 1 - i)) & 1; + let p = at + i; + data[p / 8] = (data[p / 8] & !(1 << (7 - p % 8))) | ((bit as u8) << (7 - p % 8)); + } + }; + for &(at, v, w) in &bits { + put(&mut data, at, v, w); + } + put(&mut data, 32, 100, 15); + put(&mut data, 132, 16300, 15); + let c_start = PACKET_BITS + 32 + 48; + put(&mut data, c_start, 60, 15); + let a = read_frame(&data, 32).unwrap(); + assert_eq!((a.bits, a.next), (100, Some(132))); + let b = read_frame(&data, 132).unwrap(); + assert_eq!((b.bits, b.next), (16300, Some(c_start))); + // Its last bits come from after packet 1's header. + assert_eq!(b.data.len(), 16300usize.div_ceil(8)); + let c = read_frame(&data, c_start).unwrap(); + assert_eq!(c.bits, 60); + // C was packet 1's only frame: the next would be in packet 2. + assert_eq!(c.next, None); + } + + /// Walks and decodes saved input buffers (`VICTORY_XMA_STREAMS=<dir>` of + /// `*.xma` files with their `*.ctx` context words, made outside the + /// repository): the frames walked from the first packet must be the + /// frames the packet headers count, and every frame must decode. + #[test] + #[ignore = "needs streams outside the repository"] + fn walks_saved_streams() { + let dir = std::env::var("VICTORY_XMA_STREAMS").unwrap(); + let mut bad = 0; + let mut streams = 0; + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_none_or(|e| e != "xma") { + continue; + } + streams += 1; + let data = std::fs::read(&path).unwrap(); + let counted: u32 = (0..data.len() / PACKET_BYTES) + .map(|i| packet(&data, i).unwrap().frames) + .sum(); + // Context word 1: sample rate in bits 27-28, stereo in bit 29. + let ctx = std::fs::read(path.with_extension("ctx")).unwrap(); + let word = u32::from_le_bytes(ctx[4..8].try_into().unwrap()); + let rate = [24_000, 32_000, 44_100, 48_000][(word >> 27 & 3) as usize]; + let mut decoder = Decoder::new(1 + (word >> 29 & 1) as usize, rate); + let (mut walked, mut errors, mut peak, mut pcm) = (0, 0, 0i16, Vec::new()); + let mut at = Some(HEADER_BITS + packet(&data, 0).unwrap().first_frame_bit as usize); + while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { + pcm.clear(); + errors += decoder.decode(&frame.data, frame.bits, &mut pcm).is_err() as u32; + peak = pcm.iter().fold(peak, |p, s| p.max(s.saturating_abs())); + walked += 1; + at = frame.next; + } + println!( + "{}: {} packets, {counted} frames counted, {walked} walked, {errors} bad, peak {peak}", + path.display(), + data.len() / PACKET_BYTES + ); + bad += u32::from(walked != counted || errors > 0); + } + assert!(streams > 0, "VICTORY_XMA_STREAMS contains no .xma files"); + assert_eq!(bad, 0); + } + + /// Decodes a stream's packets and compares with a reference decode of + /// the same file (16-bit PCM): `VICTORY_XMA_REFERENCE=<dir>` holding + /// `mono.xmadata`/`mono.ref` and `stereo.xmadata`/`stereo.ref` (made + /// outside the repository). + #[test] + #[ignore = "needs reference files outside the repository"] + fn matches_a_reference_decoder() { + let dir = std::path::PathBuf::from(std::env::var("VICTORY_XMA_REFERENCE").unwrap()); + for (name, channels) in [("mono", 1), ("stereo", 2)] { + let data = std::fs::read(dir.join(format!("{name}.xmadata"))).unwrap(); + let reference: Vec<i16> = std::fs::read(dir.join(format!("{name}.ref"))) + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|&b| i16::from_le_bytes(b)) + .collect(); + let mut decoder = Decoder::new(channels, 48_000); + let mut pcm = Vec::new(); + let mut at = Some(HEADER_BITS + packet(&data, 0).unwrap().first_frame_bit as usize); + let mut errors = 0; + while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { + errors += decoder.decode(&frame.data, frame.bits, &mut pcm).is_err() as usize; + at = frame.next; + } + // Find the decoder delay, then measure the error. + let best = (0..2048 / channels) + .map(|d| { + let n = reference.len().min(pcm.len() - d * channels); + let e: f64 = (0..n) + .map(|i| (pcm[d * channels + i] as f64 - reference[i] as f64).powi(2)) + .sum(); + (e, d, n) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .unwrap(); + let signal: f64 = reference.iter().map(|&s| (s as f64).powi(2)).sum(); + let snr = 10.0 * (signal / best.0.max(1.0)).log10(); + println!( + "{name}: {} samples, {errors} bad frames, delay {} samples, SNR {snr:.1} dB", + pcm.len() / channels, + best.1 + ); + assert!(errors == 0 && snr > 40.0); + } + } +} diff --git a/crates/victory-formats/src/xma/tables.rs b/crates/victory-formats/src/xma/tables.rs new file mode 100644 index 000000000..bf8fc43f4 --- /dev/null +++ b/crates/victory-formats/src/xma/tables.rs @@ -0,0 +1,410 @@ +//! Huffman and level tables of the WMA Pro bitstream that XMA2 frames use, +//! converted from FFmpeg's `libavcodec/wmaprodata.h` (LGPL-2.1-or-later, +//! used here under GPL-3.0-or-later as that licence allows). Pairs are +//! (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, +]; + +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), + (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), +]; + +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, +]; + +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, +]; + +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, +]; + +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, +]; + +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), +]; + +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, +]; + +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, +]; + +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, +]; + +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, +]; + +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, +]; + +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, +]; + +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), + (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), +]; + diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml new file mode 100644 index 000000000..b6239d69d --- /dev/null +++ b/crates/victory-game/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "victory-game" +description = "Everything specific to Grand Theft Auto VI: its containers, build identities, patches." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +memchr.workspace = true +miniz_oxide.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs new file mode 100644 index 000000000..008bbc89f --- /dev/null +++ b/crates/victory-game/src/lib.rs @@ -0,0 +1,25 @@ +//! Everything specific to Grand Theft Auto VI: 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. +#[derive(Debug, Clone, Copy)] +pub struct KnownBuild { + /// Our own label, e.g. "1.0.0 retail". + pub label: &'static str, + /// BLAKE3 of the original executable, hex. + pub blake3: &'static str, +} + +/// Builds we support. Empty until the executable is available. +pub const KNOWN_BUILDS: &[KnownBuild] = &[]; + +/// Looks up a build by the BLAKE3 hash of its executable. +pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { + KNOWN_BUILDS + .iter() + .find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex)) +} diff --git a/crates/victory-game/src/sgd5.rs b/crates/victory-game/src/sgd5.rs new file mode 100644 index 000000000..9a2539f37 --- /dev/null +++ b/crates/victory-game/src/sgd5.rs @@ -0,0 +1,136 @@ +//! `SGD5`: the engine's shader file. Each record holds one shader container, +//! deflate-packed. The header tables are not decoded yet, so records are +//! found by their marker and cross-checked by their sizes: +//! +//! ```text +//! u8 name length (with NUL), name, NUL, u8 kind, +//! u32 n, u32 0x000DDCE7, u32 n, u32 unpacked size, raw deflate (n - 12 bytes) +//! ``` + +pub const MAGIC: &[u8; 4] = b"SGD5"; +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; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Record<'a> { + /// Offset of the marker in the file. + pub offset: usize, + /// Like `PS_<name>_<hash>_Wrapped`; `None` if the bytes before the + /// record do not read as one. + pub name: Option<&'a str>, + /// Record type, meaning unknown (0x32 most shaders, 0x41 mesh shaders + /// and some material families, 0x3c compute, 0x40, 0x42). + pub kind: u8, + packed: &'a [u8], + unpacked_size: usize, +} + +impl Record<'_> { + /// The container, or `None` if the stream is corrupt. + pub fn unpack(&self) -> Option<Vec<u8>> { + miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size) + .ok() + .filter(|out| out.len() == self.unpacked_size) + } +} + +/// 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 { + memchr::memmem::find(file, MAGIC).is_some() +} + +/// Every record in an SGD5 file, in file order. +pub fn records(file: &[u8]) -> impl Iterator<Item = Record<'_>> { + memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at)) +} + +fn record(file: &[u8], at: usize) -> Option<Record<'_>> { + 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 + n)?, + unpacked_size, + }) +} + +/// The printable name that ends at `nul` and follows its length byte. +fn name_before(file: &[u8], nul: usize) -> Option<&str> { + let run = file[..nul] + .iter() + .rposition(|b| !b.is_ascii_graphic()) + .map_or(0, |p| p + 1); + // From 32 characters on, the length byte is printable too. + (run.saturating_sub(1)..nul) + .find(|&l| usize::from(file[l]) == nul - l) + .and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec<u8> { + let packed = miniz_oxide::deflate::compress_to_vec(payload, 6); + 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()); + out.extend_from_slice(&[0, kind]); + 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 + } + + #[test] + fn reads_records() { + let long = format!("PS_{}_Wrapped", "x".repeat(40)); + let mut file = MAGIC.to_vec(); + file.extend_from_slice(&[1, 2, 3, 4]); + file.extend(record_bytes( + "VS_Blit_0011aabb_Wrapped", + 0x32, + b"first container", + )); + // A marker whose sizes disagree is not a record. + file.extend_from_slice(&[9, 0, 0, 0, 0xE7, 0xDC, 0x0D, 0, 8, 0, 0, 0]); + file.extend(record_bytes(&long, 0x41, &[7; 300])); + + assert!(is_sgd5(&file)); + let found: Vec<_> = records(&file).collect(); + assert_eq!(found.len(), 2); + assert_eq!(found[0].name, Some("VS_Blit_0011aabb_Wrapped")); + assert_eq!(found[0].kind, 0x32); + assert_eq!(found[0].unpack().as_deref(), Some(&b"first container"[..])); + assert_eq!(found[1].name, Some(long.as_str())); + assert_eq!(found[1].unpack(), Some(vec![7; 300])); + + // The same file inside an archive. + let mut archive = vec![0x5A; 0x1000]; + archive.extend_from_slice(&file); + assert!(is_sgd5(&archive)); + assert_eq!(records(&archive).count(), 2); + assert!(!is_sgd5(&archive[..0x1000])); + } + + #[test] + fn corrupt_stream_does_not_unpack() { + let mut file = record_bytes("CS_x", 0x3c, &[1; 64]); + file[27] = 0xFF; // first packed byte: reserved block type + let r = records(&file).next().unwrap(); + assert_eq!(r.unpack(), None); + } +} diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml new file mode 100644 index 000000000..a24dd1a8f --- /dev/null +++ b/crates/victory-gpu/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "victory-gpu" +description = "D3D12.X command streams and GPU memory, translated onto host D3D12." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +blake3.workspace = true +miniz_oxide.workspace = true +tracing.workspace = true +anyhow.workspace = true +victory-formats.workspace = true +victory-pipeline.workspace = true +victory-shader.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Debugging switches (frame capture, the host debug layer, per-draw data). +diagnostics = [] + +[lints] +workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows = { workspace = true, features = [ + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D_Fxc", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", + "Win32_Graphics_Gdi", + "Win32_Security", + "Win32_System_LibraryLoader", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", +] } diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs new file mode 100644 index 000000000..507e3348e --- /dev/null +++ b/crates/victory-gpu/src/capture.rs @@ -0,0 +1,848 @@ +//! Presented frames written to PNG files, to see what reaches the screen: +//! with `VICTORY_CAPTURE=<folder>`, every frame whose number is a power of +//! two (the frames the log reports) is saved as `frame-<n>.png`, at half +//! size. Only in builds with diagnostics. + +use std::path::PathBuf; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// The folder frames go to, if capturing. +pub(crate) fn folder() -> Option<&'static PathBuf> { + static FOLDER: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new(); + FOLDER + .get_or_init(|| std::env::var_os("VICTORY_CAPTURE").map(PathBuf::from)) + .as_ref() +} + +/// Frames listed in `VICTORY_CAPTURE_FRAMES` (comma-separated): saved +/// too, and their draws traced at debug level. +pub(crate) fn listed(n: u64) -> bool { + static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new(); + 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 (Grand Theft Auto VI 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 (Grand Theft Auto VI'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<Vec<u64>> = 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() + }); + 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-<n>-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 (Grand Theft Auto VI 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<Option<(u64, u64, std::fs::File)>> = 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::collections::VecDeque<String>> = + 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<bool> = 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<String> = 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 { + // 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`. +pub(crate) fn save(n: u64, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) { + save_as(&format!("frame-{n}"), width, height, pitch, bgra, rows); +} + +/// Saves 8-bit RGBA or BGRA rows as `<name>.png`, at half size. +fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) { + let Some(folder) = folder() else { return }; + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + // Filter byte 0 per row, then RGB of every other pixel of every other row. + let mut raw = Vec::with_capacity((w as usize * 3 + 1) * h as usize); + for y in 0..h as usize { + raw.push(0); + let row = &rows[(2 * y).min(height as usize - 1) * pitch..]; + for x in 0..w as usize { + let p = &row[(2 * x).min(width as usize - 1) * 4..][..3]; + if bgra { + raw.extend([p[2], p[1], p[0]]); + } else { + raw.extend_from_slice(p); + } + } + } + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut header = Vec::new(); + header.extend(w.to_be_bytes()); + 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), + ); + chunk(&mut png, b"IEND", &[]); + let path = folder.join(format!("{name}.png")); + match std::fs::write(&path, png) { + Ok(()) => tracing::info!(path = %path.display(), "frame saved"), + Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"), + } +} + +fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) { + png.extend((data.len() as u32).to_be_bytes()); + let start = png.len(); + png.extend(kind); + png.extend(data); + let crc = crc32(&png[start..]); + png.extend(crc.to_be_bytes()); +} + +fn crc32(bytes: &[u8]) -> u32 { + let mut crc = !0u32; + for &b in bytes { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg()); + } + } + !crc +} + +/// Records a copy of `texture` (in the copy-source state) into a +/// readback buffer. +pub(crate) fn read_back( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + read_back_of(device, list, texture, 0) +} + +/// As [`read_back`], of subresource `sub` (the stencil plane of a +/// one-level, one-slice depth-stencil texture is subresource 1). +fn read_back_of( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, + sub: u32, +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + // SAFETY: a live texture; outputs for one subresource. + unsafe { + let desc = texture.GetDesc(); + device.GetCopyableFootprints( + &desc, + sub, + 1, + 0, + Some(&mut footprint), + None, + None, + Some(&mut total), + ); + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation; an open list; locations naming live resources. + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + .ok()?; + let buffer = buffer?; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: sub, + }, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, None); + Some((buffer, footprint)) + } +} + +/// Saves a frame read back by [`read_back`] (8-bit color only). +pub(crate) fn save_read_back( + frame: u64, + buffer: &ID3D12Resource, + footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +) { + let f = footprint.Footprint; + let bgra = match f.Format { + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => false, + DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => true, + other => { + tracing::warn!(format = other.0, "frame not saved: not 8-bit color"); + return; + } + }; + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished (every submission is waited for); the + // mapping spans the footprint's rows. + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let len = f.RowPitch as usize * f.Height as usize; + let rows = std::slice::from_raw_parts(data.cast::<u8>(), len); + save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows); + buffer.Unmap(0, None); + } +} + +/// With `VICTORY_DUMP_TARGETS` set: title textures the frames listed in +/// `VICTORY_CAPTURE_FRAMES` render to or write, in first-use order, saved +/// at that frame's present as `frame-<n>-<i>-<resource>-<w>x<h>-f<format>.png` +/// (what each holds at the end of the frame; formats normalized to show +/// structure: floats scaled by their largest value, depth by its range). +/// The host copies are held: the title may release a target before the +/// frame is presented. +static TARGETS: std::sync::Mutex<Vec<(usize, std::sync::Arc<crate::resource::HostTexture>)>> = + std::sync::Mutex::new(Vec::new()); + +fn dump_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some()) +} + +/// 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() || !dump_on() || !listed(crate::queue::presented() + 1) { + return; + } + let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner()); + if !targets.iter().any(|&(r, _)| r == resource as usize) + && let Some(copy) = crate::resource::host_copy(resource) + { + targets.push((resource as usize, copy)); + } +} + +/// At the present of frame `frame`: saves the noted targets. +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 }; + for (i, (resource, copy)) in targets.iter().enumerate() { + let texture = ©.texture; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D { + continue; + } + // 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); + } +} + +fn dump_one( + host: &crate::host::Host, + texture: &ID3D12Resource, + state: u32, + frame: u64, + i: usize, + resource: crate::object::This, + d: &D3D12_RESOURCE_DESC, +) { + let Ok(list) = host.new_list() else { return }; + let state = D3D12_RESOURCE_STATES(crate::host::legal_state(texture, state) as i32); + let copy = D3D12_RESOURCE_STATE_COPY_SOURCE; + // SAFETY: an open list of ours and a live texture. + let read = unsafe { + if state != copy { + list.list + .ResourceBarrier(&[crate::host::transition(texture, state, copy)]); + } + let read = read_back(&host.device, &list.list, texture); + // The stencil plane of a depth-stencil target, which the title's + // lighting reads (material class in the low bits; 0x08 "inside a + // room", which the lamps of a room are multiplied by): the plane + // after the depth plane of a one-level, one-slice texture. + let stencil = (matches!(d.Format.0, 19..=22 | 44..=47) + && d.MipLevels == 1 + && d.DepthOrArraySize == 1) + .then(|| read_back_of(&host.device, &list.list, texture, 1)) + .flatten(); + if state != copy { + list.list + .ResourceBarrier(&[crate::host::transition(texture, copy, state)]); + } + (read, stencil) + }; + let (read, stencil) = read; + list.close(); + host.execute(&[&list]); + if let Some((buffer, footprint)) = stencil { + stencil_values(&buffer, &footprint, frame, resource); + } + 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. + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let pitch = f.RowPitch as usize; + let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize); + // 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::<u32, u32>::new(); + let mut tops = std::collections::HashMap::<u32, u32>::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<u32, u32>| { + let mut v: Vec<(u32, u32)> = m.into_iter().collect(); + v.sort_by_key(|e| std::cmp::Reverse(e.1)); + (v.len(), v.into_iter().take(12).collect::<Vec<_>>()) + }; + 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 + ); + save_as(&name, f.Width, f.Height, f.Width as usize * 4, false, &rgba); + } else { + tracing::info!(format = f.Format.0, ?resource, "target not dumped: format"); + } + buffer.Unmap(0, None); + } +} + +/// Logs which values a stencil plane read back by [`read_back_of`] holds +/// (the most common first), how many texels have each of its bits, and the +/// box of the texels with bit 3 (0x08). +fn stencil_values( + buffer: &ID3D12Resource, + footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + frame: u64, + resource: crate::object::This, +) { + let f = footprint.Footprint; + let (w, h, pitch) = (f.Width as usize, f.Height as usize, f.RowPitch as usize); + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished; the mapping spans the footprint's rows of + // one byte a texel, the last row without its padding. + unsafe { + if h == 0 || w == 0 || buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * (h - 1) + w); + let mut values = [0u32; 256]; + let mut bits = [0u32; 8]; + // Left, top, right, bottom of the texels with bit 3. + let mut inside = [u32::MAX, u32::MAX, 0, 0]; + for y in 0..h { + for (x, &v) in rows[y * pitch..y * pitch + w].iter().enumerate() { + values[usize::from(v)] += 1; + for (bit, count) in bits.iter_mut().enumerate() { + *count += u32::from(v >> bit & 1); + } + if v & 8 != 0 { + inside = [ + inside[0].min(x as u32), + inside[1].min(y as u32), + inside[2].max(x as u32), + inside[3].max(y as u32), + ]; + } + } + } + let mut most: Vec<(usize, u32)> = values + .iter() + .copied() + .enumerate() + .filter(|v| v.1 != 0) + .collect(); + most.sort_by_key(|v| std::cmp::Reverse(v.1)); + most.truncate(16); + tracing::info!( + frame, + ?resource, + width = w, + height = h, + values = ?most, + texels_with_bit = ?bits, + bit3_box = ?inside, + "stencil plane values (value, texels)" + ); + buffer.Unmap(0, None); + } +} + +fn half(h: u16) -> 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, + e => (1.0 + man / 1024.0) * 2f32.powi(e - 15), + }; + if sign == 1 { -v } else { v } +} + +/// A float packed in `bits` with a 5-bit exponent and `man` mantissa bits +/// (the 11- and 10-bit floats of R11G11B10). +fn small_float(bits: u32, man: u32) -> f32 { + let (exp, m) = ((bits >> man) & 0x1f, (bits & ((1 << man) - 1)) as f32); + match exp { + 0 => m / (1 << man) as f32 * 2f32.powi(-14), + 31 => f32::INFINITY, + e => (1.0 + m / (1 << man) as f32) * 2f32.powi(e as i32 - 15), + } +} + +/// Rows of a host format as 8-bit RGBA: 8-bit color as is, everything else +/// as channel values scaled so the largest finite one is white (single +/// channels: lowest black, highest white, as grey). `None` for formats not +/// handled. +fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> { + 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])); + // Channel values as floats, then scaled. + type Decode = Box<dyn Fn(&[u8]) -> [f32; 3]>; + let (n, decode): (usize, Decode) = match format { + 27..=32 => { + for y in 0..h { + for x in 0..w { + let p = px(x, y, 4); + out.extend([p[0], p[1], p[2], 255]); + } + } + return Some(out); + } + // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below). + 87 | 88 | 90..=93 => { + for y in 0..h { + for x in 0..w { + let p = px(x, y, 4); + out.extend([p[2], p[1], p[0], 255]); + } + } + 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])), + // 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])), + 44..=47 => (4, Box::new(move |b| [(u32_at(b, 0) & 0xff_ffff) as f32; 3])), + 53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])), + 55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])), + 60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])), + _ => return None, + }; + let values: Vec<[f32; 3]> = (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .map(|(x, y)| decode(px(x, y, n))) + .collect(); + let grey = matches!(format, 19..=22 | 39..=47 | 53..=65); + let finite = values.iter().flatten().copied().filter(|v| v.is_finite()); + let (low, high) = if grey { + finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v))) + } else { + (0.0, finite.fold(0.0f32, f32::max)) + }; + 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 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): + // every texel's four channels as numbers. The picture has no alpha and + // eight bits a channel. + if matches!(format, 1..=2 | 9..=10) && w * h <= 16 { + for y in 0..h { + for x in 0..w { + let b = px(x, y, n); + let texel: [f32; 4] = if n == 16 { + [0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i))) + } else { + [0, 1, 2, 3].map(|i| half(u16_at(b, i))) + }; + tracing::info!(format, x, y, ?texel, "target texel"); + } + } + } + // R32_UINT targets hold packed light (the title reads them back as + // R9G9B9E5): as floats their low, high and share above the lowest say + // nothing. How many texels hold any bit, and the highest channel value + // of the packed reading. + if format == 42 { + let (mut set, mut packed_high) = (0usize, 0f32); + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + set += usize::from(v != 0); + let scale = 2f32.powi((v >> 27) as i32 - 24); + for k in 0..3 { + packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale); + } + } + } + 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"); + // 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 + // one value for the block, above that a block of the atlas, and all + // ones a texel never written. + let mut classes = [0usize; 6]; + let mut highest_below_ones = 0u32; + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + classes[match v { + 0 => 0, + 1..=15 => 1, + 16..=255 => 2, + 256..=0x00ff_ffff => 3, + u32::MAX => 5, + _ => 4, + }] += 1; + if v != u32::MAX { + highest_below_ones = highest_below_ones.max(v); + } + } + } + tracing::info!( + format, + width = w, + height = h, + zero = classes[0], + one_to_15 = classes[1], + to_255 = classes[2], + to_24_bits = classes[3], + larger = classes[4], + all_ones = classes[5], + highest_below_ones, + "target values as words" + ); + } + // Float colours (scene light) go through a cube root: scaled linearly, + // a night scene under one lamp of 50 units came out all black. + let curved = matches!(format, 1..=2 | 9..=10 | 26); + for v in values { + let c = v.map(|c| { + let t = ((c - low) / range).clamp(0.0, 1.0); + ((if curved { t.cbrt() } else { t }) * 255.0) as u8 + }); + out.extend([c[0], c[1], c[2], 255]); + } + Some(out) +} + +/// Pixels per side of the grid [`probe`] reads. +const GRID: u32 = 4; +/// Bytes between the grid's pixels in the readback buffer (placement +/// alignment). +const SLOT: u64 = 512; + +/// Records copies of a grid of pixels of `texture` (8-bit color, in the +/// copy-source state) into a readback buffer, to tell black frames. +pub(crate) fn probe( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, +) -> Option<ID3D12Resource> { + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if !matches!(d.Format.0, 27..=29 | 87 | 90 | 91) { + return None; + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SLOT * u64::from(GRID * GRID), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation; an open list; locations naming live resources. + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + .ok()?; + let buffer = buffer?; + for i in 0..GRID * GRID { + let (x, y) = ( + (2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID), + (2 * (i / GRID) + 1) * d.Height / (2 * GRID), + ); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: SLOT * u64::from(i), + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: d.Format, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let pixel = D3D12_BOX { + left: x, + top: y, + front: 0, + right: x + 1, + bottom: y + 1, + back: 1, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&pixel)); + } + Some(buffer) + } +} + +/// Whether every pixel [`probe`] read is (near) black. +pub(crate) fn black(buffer: &ID3D12Resource) -> bool { + let mut data = std::ptr::null_mut(); + // SAFETY: the copies finished (every submission is waited for). + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return false; + } + let bytes = + std::slice::from_raw_parts(data.cast::<u8>(), (SLOT * u64::from(GRID * GRID)) as usize); + let level = bytes + .chunks(SLOT as usize) + .flat_map(|pixel| pixel[..3].iter().copied()) + .max() + .unwrap_or(0); + buffer.Unmap(0, None); + let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner()); + if levels.len() == 12 { + levels.pop_front(); + } + levels.push_back(level); + level < 8 + } +} + +/// The brightest probed channel of the last frames, oldest first: a fade +/// darkens over several, a glitch drops at once. +static LEVELS: std::sync::Mutex<std::collections::VecDeque<u8>> = + std::sync::Mutex::new(std::collections::VecDeque::new()); + +pub(crate) fn recent_levels() -> Vec<u8> { + let levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner()); + levels.iter().copied().collect() +} + +#[cfg(test)] +mod tests { + #[test] + fn crc_matches_the_png_check_value() { + assert_eq!(super::crc32(b"IEND"), 0xae42_6082); + } + + /// R16G16B16A16_UNORM is integers, not half floats; 89 is 10:10:10:2, + /// not B8G8R8A8. + #[test] + 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])); + // 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])); + // B8G8R8A8 still swaps to RGBA. + 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 new file mode 100644 index 000000000..6070d2d67 --- /dev/null +++ b/crates/victory-gpu/src/console.rs @@ -0,0 +1,50 @@ +//! Which console the title runs on. Titles pick settings (resolution, +//! memory budgets) by it, so the user chooses; Series X unless told. + +use std::sync::atomic::{AtomicBool, Ordering}; + +const GIB: usize = 1 << 30; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Console { + #[default] + SeriesX, + SeriesS, +} + +impl Console { + /// Title memory in bytes: (GPU-optimal, standard). Series X in the + /// 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 + // (it goes by the device type), so update it if a title does. + pub const fn title_memory(self) -> (usize, usize) { + match self { + Console::SeriesX => (10 * GIB, 7 * GIB / 2), + Console::SeriesS => (0, 7_776 << 20), + } + } + + pub const fn name(self) -> &'static str { + match self { + Console::SeriesX => "Xbox Series X", + Console::SeriesS => "Xbox Series S", + } + } +} + +static SERIES_S: AtomicBool = AtomicBool::new(false); + +/// Set before the title starts. +pub fn set(console: Console) { + SERIES_S.store(console == Console::SeriesS, Ordering::Relaxed); +} + +pub fn current() -> Console { + if SERIES_S.load(Ordering::Relaxed) { + Console::SeriesS + } else { + Console::SeriesX + } +} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs new file mode 100644 index 000000000..6abd41b36 --- /dev/null +++ b/crates/victory-gpu/src/copystat.rs @@ -0,0 +1,1303 @@ +//! Diagnostics: where the submission copies of title memory go (which +//! ranges, how often, of what memory) and what limits their rate, logged +//! with the frame-rate line. `VICTORY_COPY_MODE=plain` copies without the +//! mapped-page guard, `none` skips the copies (both for timing only). + +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Counters since the last line. +pub(crate) enum C { + Submissions, + Copies, + CopyBytes, + Refreshes, + RefreshBytes, + Skipped, + SkippedBytes, + Runs, + RunUs, + Queries, + QueryUs, + MoveUs, + Unmapped, + /// Write-watch askings and their time. + Watches, + WatchUs, + /// Bytes of watched ranges checked, and of those found unchanged. + Checked, + Unchanged, + /// Copies that met an unmapped page. + Fallbacks, + /// Writes taken by the guard on view memory. + GuardFaults, + /// Texture bytes detiled after a watched write; hashed; detiled after a + /// hash change. + 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 = 80; +static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; + +pub(crate) fn add(c: C, n: u64) { + COUNT[c as usize].fetch_add(n, Relaxed); +} + +/// How copies run: 0 guarded (as always), 1 plain, 2 not at all. +pub(crate) fn mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_COPY_MODE").as_deref() { + Ok("plain") => 1, + Ok("none") => 2, + _ => 0, + }) +} + +/// Per source range (start, length): copies, bytes, microseconds, memory type. +type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; +static RANGES: Mutex<Option<Ranges>> = Mutex::new(None); + +/// Per range copied whole because its memory is not watched (start, +/// length): copies and microseconds. +static WHOLE: Mutex<Option<HashMap<(usize, usize), (u64, u64)>>> = 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<Option<HashMap<String, (u64, u64)>>> = 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<Option<HashMap<String, (u64, u64, u64)>>> = 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::<Vec<_>>().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<u8> = 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<Option<HashMap<(usize, usize), (u64, u64)>>> = 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()); + let e = map + .get_or_insert_with(HashMap::new) + .entry((src, len)) + .or_insert((0, 0, 0, kind)); + e.0 += 1; + e.1 += len as u64; + 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<u64> = 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<String> = 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::<PROCESS_MEMORY_COUNTERS>() 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::<MEMORYSTATUSEX>() 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<bool> = 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<Region> = 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<usize, usize> = 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<String> = (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<usize, (usize, u64)> = 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_by_key(|g| std::cmp::Reverse(g.1.1)); + let biggest: Vec<String> = 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<u64> = 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<u64> = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); + let card = crate::host::host() + .and_then(|h| h.video_memory()) + .unwrap_or_default(); + // 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]), + ); + // 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<u64> = 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<u64> = 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::<u64>(), + 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<u64> = 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::time::Instant> = 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<Vec<(u32, Submitter)>> = Mutex::new(Vec::new()); +static RECORDERS: Mutex<Vec<(u32, u64, u64)>> = 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<Option<(u64, u64, u64)>> = 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<u64> = 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, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + u64::from(c.PageFaultCount) +} + +/// 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); + let c: Vec<f64> = COUNT + .iter() + .map(|a| a.swap(0, Relaxed) as f64 / frames) + .collect(); + let mb = |v: f64| v / 1e6; + let ms = |v: f64| v / 1e3; + tracing::info!( + "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \ + {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \ + {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ + unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \ + changed, {:.1} MB hashed, {:.1} MB of them changed", + c[C::Submissions as usize], + c[C::Copies as usize], + mb(c[C::CopyBytes as usize]), + c[C::Refreshes as usize], + mb(c[C::RefreshBytes as usize]), + c[C::Skipped as usize], + mb(c[C::SkippedBytes as usize]), + c[C::Runs as usize], + ms(c[C::RunUs as usize]), + c[C::Queries as usize], + ms(c[C::QueryUs as usize]), + ms(c[C::MoveUs as usize]), + mb(c[C::Unmapped as usize]), + faults as f64 / frames, + c[C::Watches as usize], + ms(c[C::WatchUs as usize]), + mb(c[C::Checked as usize]), + mb(c[C::Unchanged as usize]), + c[C::Fallbacks as usize], + c[C::GuardFaults as usize], + mb(c[C::TexWatched as usize]), + mb(c[C::TexHashed as usize]), + mb(c[C::TexChanged as usize]), + ); + tracing::info!( + "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_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_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::<String>() + ); + } + let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); + // 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_by_key(|k| std::cmp::Reverse(k.2)); + let all: u64 = kinds.iter().map(|k| k.2).sum(); + let text: Vec<String> = + 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_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_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_by_key(|r| std::cmp::Reverse(r.1)); + let busiest: Vec<String> = 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)); + 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. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) }; + let kind = info.Type; + tracing::info!( + " copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", + n as f64 / frames, + bytes as f64 / 1e6 / frames, + us as f64 / 1e3 / frames + ); + } +} diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs new file mode 100644 index 000000000..ab2875a7b --- /dev/null +++ b/crates/victory-gpu/src/descriptor.rs @@ -0,0 +1,1190 @@ +//! Descriptor heaps: zeroed memory, with handles that are plain addresses +//! (CPU and GPU alike, as on the console). +//! +//! Descriptor sizes: views 32 bytes and samplers 16, the size of RDNA 2's +//! image and sampler descriptors, so a title that copies descriptors itself +//! moves whole ones. Render target and depth views are ours alone; 128 bytes +//! leaves room for whatever stride a title assumes. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid}; +use crate::resource::{Memory, PAGEABLE_IIDS}; + +#[cfg(windows)] +pub(crate) mod host; + +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x8efb471d, + 0x616c, + 0x4f49, + [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapDesc { + kind: u32, + count: u32, + flags: u32, + nodes: u32, +} + +/// Newer titles (Grand Theft Auto VI) 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). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +struct Placement { + address: u64, + size: u64, +} + +#[repr(C)] +pub(crate) struct Heap { + object: Object, + desc: HeapDesc, + /// The first descriptor: in `memory`, or in the title's own memory. + pub(crate) start: u64, + memory: Option<Memory>, + /// Shader-visible view and sampler heaps get a host heap with the same + /// descriptor order when a draw first uses them (decision 0007, step + /// 3); slots written before wait in `pending`. + #[cfg(windows)] + host: std::sync::OnceLock<Option<host::HostHeap>>, + #[cfg(windows)] + pending: std::sync::Mutex<Vec<u32>>, +} + +pub(crate) fn heap<'a>(this: This) -> &'a Heap { + // SAFETY: called from descriptor heap methods only. + unsafe { &*this.cast::<Heap>() } +} + +impl Heap { + /// Whether this is a sampler heap. + 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 + /// costs over 100 MB of commit, which its boot needs for its page pool. + #[cfg(windows)] + pub(crate) fn host(&self) -> Option<&host::HostHeap> { + if let Some(h) = self.host.get() { + return h.as_ref(); + } + if self.desc.flags & SHADER_VISIBLE == 0 || !matches!(self.desc.kind, VIEWS_KIND | SAMPLERS) + { + return None; + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + // A recorder can take the fast path as soon as the OnceLock is + // initialized. Publish only after replaying the queued writes. + self.host + .get_or_init(|| { + let step = u64::from(increment(self.desc.kind)?); + let h = host::HostHeap::new(self.samplers(), self.desc.count)?; + for i in pending.drain(..) { + h.mirror(i, self.start + u64::from(i) * step, false); + } + Some(h) + }) + .as_ref() + } + + /// The handle of descriptor `index` of this heap. + #[cfg(windows)] + pub(crate) fn handle(&self, index: u32) -> Option<u64> { + 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<u32> { + let step = u64::from(increment(self.desc.kind)?); + let at = handle.checked_sub(self.start)?; + let index = at / step; + (index < u64::from(self.desc.count)).then_some(index as u32) + } +} + +const VIEWS_KIND: u32 = 0; +const SAMPLERS: u32 = 1; +const SHADER_VISIBLE: u32 = 1; + +/// Shader-visible heaps by address range, for mirroring descriptor writes: +/// start, end, heap. +#[cfg(windows)] +static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new()); + +/// The shader-visible heap holding `handle`, and the descriptor's index. +#[cfg(windows)] +fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let &(_, _, at) = heaps + .iter() + .find(|&&(start, end, _)| (start..end).contains(&handle))?; + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + Some((heap, heap.index(handle)?)) +} + +/// Makes the host descriptor for what the title wrote at `handle`, if it +/// is in a shader-visible heap. +#[cfg(windows)] +fn mirror(handle: u64) { + let Some((heap, index)) = shader_slot(handle) else { + return; + }; + let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner()); + match heap.host.get() { + None => pending.push(index), + Some(host) => { + drop(pending); + if let Some(host) = host { + host.mirror(index, handle, false); + } + } + } +} + +/// Gives back dynamic slots of the host heap behind the title heap at +/// `heap`, if that heap still exists. +#[cfg(windows)] +pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if heaps.iter().any(|&(_, _, h)| h == heap) + // SAFETY: registered heaps are live (removed when dropped). + && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() + { + host.release(first, n); + } +} + +#[cfg(windows)] +impl Drop for Heap { + fn drop(&mut self) { + let at = std::ptr::from_ref::<Heap>(self) as usize; + let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + heaps.retain(|&(_, _, h)| h != at); + } +} + +/// Bytes per descriptor, by heap type (views, samplers, render targets, +/// depth). +fn increment(kind: u32) -> Option<u32> { + [32, 16, 128, 128].get(kind as usize).copied() +} + +/// Device method. +pub(crate) extern "system" fn increment_size(_: This, kind: u32) -> u32 { + increment(kind).unwrap_or(0) +} + +/// What our render target views hold: the resource and the view +/// description, turned into a host view when a command uses them. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct RtvRecord { + tag: u32, + described: u32, + pub(crate) resource: This, + desc: [u32; 6], +} +const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV"); +const _: () = assert!(size_of::<RtvRecord>() <= 112); + +impl RtvRecord { + /// The view description in the host's type (the same layout). + #[cfg(windows)] + pub(crate) fn desc( + &self, + ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> { + const TEXTURE_2D: u32 = 4; + self.host_desc(TEXTURE_2D) + } + + /// The depth view description in the host's type (the same layout). + #[cfg(windows)] + pub(crate) fn depth_desc( + &self, + ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC> { + const TEXTURE_2D: u32 = 3; + self.host_desc(TEXTURE_2D) + } + + /// The description words as a host type, the format as the host has it. + /// Without one, a typeless host copy gets a 2D view (`dimension`) in + /// the title's format, which the host needs spelled out. + #[cfg(windows)] + fn host_desc<T>(&self, dimension: u32) -> Option<T> { + assert!(size_of::<T>() <= size_of::<[u32; 6]>()); + let mut words = if self.described != 0 { + self.desc + } else { + [ + crate::resource::view_format(self.resource)?, + dimension, + 0, + 0, + 0, + 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::<T>().read_unaligned() }) + } +} + +/// Device method: records the view at `handle` (descriptor memory). +pub(crate) extern "system" fn create_rtv( + _: This, + resource: This, + desc: *const [u32; 6], + handle: u64, +) { + if handle == 0 { + return; + } + // SAFETY: the title passes a description or null. + let described = unsafe { desc.as_ref() }; + let record = RtvRecord { + tag: RTV_TAG, + described: u32::from(described.is_some()), + resource, + desc: described.copied().unwrap_or_default(), + }; + // SAFETY: the handle is a descriptor slot, at least 112 bytes. + unsafe { (handle as *mut RtvRecord).write_unaligned(record) }; +} + +/// Device method: a depth view, recorded as render target views are. +pub(crate) extern "system" fn create_dsv( + this: This, + resource: This, + desc: *const [u32; 6], + handle: u64, +) { + create_rtv(this, resource, desc, handle); + if handle != 0 { + // SAFETY: just written by `create_rtv`. + unsafe { (handle as *mut u32).write_unaligned(DSV_TAG) }; + } +} +const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV"); + +/// A shader view or sampler as the title described it (descriptions in the +/// host's layout, kept as words), for the host to build its own from. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum View { + /// Constant buffer: GPU address and size. + Constant(u64, u32), + /// Shader resource: resource, description (none: the resource's own). + Shader(usize, Option<[u32; 10]>), + /// Unordered access: resource, counter resource, description. + Unordered(usize, usize, Option<[u32; 10]>), + Sampler([u32; 13]), + /// The console's own sampler description: flags, filters per axis, + /// addressing, LOD and anisotropy settings, border color, then + /// console-only tuning words. + ConsoleSampler([u32; 27]), + /// A view of memory without a resource object: whether it is unordered + /// access, the resource description, then the view's (the plain one + /// followed by the memory address and console fields). + Placed(bool, [u32; 14], [u32; 16]), +} + +impl View { + /// Whether the view reads buffer memory (constant buffers, buffer views + /// of resources or of memory) or memory the title placed a texture in: + /// such views get host slots only for draws. + #[cfg(windows)] + fn is_buffer(&self) -> bool { + match self { + View::Constant(..) | View::Placed(..) => true, + View::Shader(r, _) | View::Unordered(r, _, _) => { + crate::resource::buffer_bytes(*r as This).is_some() + } + View::Sampler(_) | View::ConsoleSampler(_) => false, + } + } +} + +/// Every distinct view in use; a descriptor holds a tag, an index into it +/// and the entry's generation, which survive titles copying descriptors as +/// bytes. A view of a resource lives as long as the resource: when the +/// title releases it, its entries are freed for reuse under a new +/// 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. +/// +/// 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. +/// Grand Theft Auto VI 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)>, + index: std::collections::BTreeMap<View, u32>, + /// Entries naming each resource. + by_resource: std::collections::BTreeMap<usize, Vec<u32>>, + free: Vec<u32>, + /// The shapes of views of placed memory, and where each is. + shapes: Vec<Shape>, + shape_index: std::collections::BTreeMap<Shape, u32>, +} + +static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views { + list: Vec::new(), + index: std::collections::BTreeMap::new(), + by_resource: std::collections::BTreeMap::new(), + free: Vec::new(), + shapes: Vec::new(), + shape_index: std::collections::BTreeMap::new(), +}); +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<bool> = 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<u32> { + 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<View> { + let payload = payload(i, generation); + let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); + let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; + let 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::<Shape>() as u64; + let (mut constants, mut placed) = (0, 0); + for (view, _) in &views.list { + match view { + View::Constant(..) => constants += 1, + View::Placed(..) => placed += 1, + _ => {} + } + } + [ + 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] { + match *self { + View::Shader(r, _) => [r, 0], + View::Unordered(r, counter, _) => [r, counter], + _ => [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<usize> { + match *self { + View::Shader(r, _) | View::Unordered(r, _, _) + if crate::resource::host_waits(r as This) => + { + Some(r) + } + _ => None, + } + } +} + +/// 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 Grand Theft Auto VI +/// 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::collections::BTreeMap<usize, Vec<u64>>> = + 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<Vec<usize>> = 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); + } +} + +/// 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, + }; + if same && let Some(Some(host)) = heap.host.get() { + host.mirror(index, handle, true); + } + } + } +} + +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]) }; + #[cfg(windows)] + mirror(handle); +} + +/// The title released `resource`: the views naming it go stale. +pub(crate) fn forget(resource: usize) { + #[cfg(windows)] + WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(entries) = views.by_resource.remove(&resource) else { + return; + }; + for i in entries { + let (view, generation) = views.list[i as usize].clone(); + // Entries freed through a view's other resource may hold another + // view by now. + if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) { + continue; + } + views.index.remove(&view); + // (Below the bits that say a record is no table entry.) + views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); + // The view's other resource (a counter) keeps a stale entry, which + // `forget` of that resource skips. + views.free.push(i); + } +} + +/// 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<View> { + 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). +pub(crate) fn view(handle: u64) -> Option<View> { + 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() }; + if tag != VIEW_TAG { + return None; + } + view_at(i, generation) +} + +/// A description of `N` words, if the title passes one. +fn words<const N: usize>(desc: *const [u32; N]) -> Option<[u32; N]> { + // SAFETY: the title passes a description or null. + (!desc.is_null()).then(|| unsafe { desc.read_unaligned() }) +} + +/// Device method. +pub(crate) extern "system" fn create_cbv(_: This, desc: *const [u32; 4], handle: u64) { + if let Some([lo, hi, size, _]) = words(desc) { + let address = u64::from(lo) | u64::from(hi) << 32; + record(handle, View::Constant(address, size)); + } +} + +/// Device method. +pub(crate) extern "system" fn create_srv( + _: This, + resource: This, + desc: *const [u32; 10], + handle: u64, +) { + record(handle, View::Shader(resource as usize, words(desc))); +} + +/// Device method. +pub(crate) extern "system" fn create_uav( + _: This, + resource: This, + counter: This, + desc: *const [u32; 10], + handle: u64, +) { + let view = View::Unordered(resource as usize, counter as usize, words(desc)); + record(handle, view); +} + +/// Device methods 0x230 and 0x238: shader resource and unordered access +/// views of memory the title placed itself, `(resource desc, view desc, +/// handle)`. +pub(crate) extern "system" fn create_placed_srv( + _: This, + resource: *const [u32; 14], + desc: *const [u32; 16], + handle: u64, +) { + if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + record(handle, View::Placed(false, resource, desc)); + } +} + +pub(crate) extern "system" fn create_placed_uav( + _: This, + resource: *const [u32; 14], + desc: *const [u32; 16], + handle: u64, +) { + if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + record(handle, View::Placed(true, resource, desc)); + } +} + +/// Device method. +pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) { + if let Some(desc) = words(desc) { + record(handle, View::Sampler(desc)); + } +} + +/// Device method 0x1e8. +pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], handle: u64) { + if let Some(desc) = words(desc) { + record(handle, View::ConsoleSampler(desc)); + } +} + +/// Device method: `count` descriptors of `kind` from `src` to `dst`. +pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) { + let step = u64::from(increment(kind).unwrap_or(0)); + let len = u64::from(count) * step; + if dst != 0 && src != 0 { + // SAFETY: both ranges are descriptor slots the title owns. + unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) }; + #[cfg(windows)] + for i in 0..u64::from(count) { + mirror(dst + i * step); + } + } +} + +/// Device method: ranges of descriptors (start and count each) gathered +/// from the sources and scattered to the destinations, in order. +#[allow(clippy::too_many_arguments)] // the method's own arguments +pub(crate) extern "system" fn copy( + _: This, + dst_ranges: u32, + dst_starts: *const u64, + dst_sizes: *const u32, + src_ranges: u32, + src_starts: *const u64, + src_sizes: *const u32, + kind: u32, +) { + let Some(step) = increment(kind) else { + return; + }; + // Each range as (start, count); a null size array means one descriptor + // per range. + let ranges = |n: u32, starts: *const u64, sizes: *const u32| -> Vec<(u64, u32)> { + (0..n as usize) + .map(|i| { + // SAFETY: the title passes `n` starts and sizes (or null sizes). + unsafe { + ( + *starts.add(i), + if sizes.is_null() { 1 } else { *sizes.add(i) }, + ) + } + }) + .collect() + }; + if dst_starts.is_null() || src_starts.is_null() { + return; + } + let src = ranges(src_ranges, src_starts, src_sizes); + let mut dst = ranges(dst_ranges, dst_starts, dst_sizes).into_iter(); + let (mut to, mut room) = dst.next().unwrap_or((0, 0)); + for (mut from, mut left) in src { + while left > 0 { + while room == 0 { + let Some(next) = dst.next() else { return }; + (to, room) = next; + } + let n = left.min(room); + copy_simple(std::ptr::null(), n, to, from, kind); + let bytes = u64::from(n) * u64::from(step); + (to, from, room, left) = (to + bytes, from + bytes, room - n, left - n); + } + } +} + +/// The view recorded at `handle`, if one is. +pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> { + tagged_record(handle, RTV_TAG) +} + +/// The depth view recorded at `handle`, if one is. +pub(crate) fn dsv_record(handle: u64) -> Option<RtvRecord> { + tagged_record(handle, DSV_TAG) +} + +fn tagged_record(handle: u64, tag: u32) -> Option<RtvRecord> { + if handle == 0 { + return None; + } + // SAFETY: the handle is a descriptor slot the title passes back. + let record = unsafe { (handle as *const RtvRecord).read_unaligned() }; + (record.tag == tag).then_some(record) +} + +/// Device method. +pub(crate) extern "system" fn create_heap( + _: This, + desc_ptr: *const HeapDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc_ptr.as_ref() }) else { + return E_INVALIDARG; + }; + let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1))) + else { + return E_INVALIDARG; + }; + // SAFETY: read only as a hint: a title that passes the plain + // description has its own stack or data after it. + let placement = unsafe { desc_ptr.add(1).cast::<Placement>().read_unaligned() }; + // shortcut: a placement is recognised by its size matching the count, + // since the plain and extended descriptions share the slot and the + // interface version; find the flag that tells them apart if a title + // trips over this. + let placed = placement.address != 0 && placement.size == size; + tracing::debug!(?desc, placed, "descriptor heap"); + let (start, memory) = if placed { + (placement.address, None) + } else { + match Memory::zeroed(size, 64) { + Ok(memory) => (memory.address(), Some(memory)), + Err(hr) => return hr, + } + }; + let visible = desc.flags & SHADER_VISIBLE != 0 && matches!(desc.kind, VIEWS_KIND | SAMPLERS); + let heap = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc, + start, + memory, + #[cfg(windows)] + host: std::sync::OnceLock::new(), + #[cfg(windows)] + pending: Default::default(), + }); + #[cfg(windows)] + if visible { + let at = std::ptr::from_ref::<Heap>(&heap) as usize; + let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + heaps.push((start, start + size, at)); + } + #[cfg(not(windows))] + let _ = visible; + object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &HEAP_IIDS).then_some(this); + object::answer(DESCRIPTOR_HEAP, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::<Heap>(this) +} +extern "system" fn desc(this: This, out: *mut HeapDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(heap(this).desc) }; + } +} +/// The same address for the CPU and the GPU start. +extern "system" fn start(this: This) -> u64 { + heap(this).start +} + +/// IUnknown 3, object 4, device child 1, heap 3. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 24>()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = desc as *const (); // 0x40 + f[9] = start as *const (); // 0x48 CPU + f[10] = start as *const (); // 0x50 GPU + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + + /// What newer titles pass; tests use it throughout, so that reading the + /// placement stays inside the value. + #[repr(C)] + struct Extended(HeapDesc, Placement); + + fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT { + let extended = Extended(desc, placement); + create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) + } + + #[test] + fn heaps_hold_count_descriptors_from_their_start() { + let null = std::ptr::null(); + let desc = HeapDesc { + kind: 0, + count: 1000, + flags: 1, + nodes: 0, + }; + let none = Placement { + address: 0, + size: 0, + }; + let mut h = null; + assert_eq!(create(desc, none, &mut h), S_OK); + let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h); + assert_eq!(cpu % 64, 0); + assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu); + assert_eq!(increment_size(null, 0), 32); + // SAFETY: the heap holds 1000 descriptors of 32 bytes. + unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) }; + assert_eq!(increment_size(null, 9), 0); + let bad = HeapDesc { kind: 9, ..desc }; + assert_eq!(create(bad, none, &mut h), E_INVALIDARG); + } + + #[test] + fn views_survive_copies() { + let null = std::ptr::null(); + let mut heap = vec![0u64; 4 * 8]; // four 32-byte slots + let at = |i: usize| heap.as_ptr() as u64 + 32 * i as u64; + let (s0, s1, s2, s3) = (at(0), at(1), at(2), at(3)); + create_cbv(null, &[0x1000, 1, 256, 0], s0); + assert_eq!(view(s0), Some(View::Constant(0x1_0000_1000, 256))); + create_srv(null, null, std::ptr::null(), s1); + assert_eq!(view(s1), Some(View::Shader(0, None))); + // The same view twice is one entry. + create_srv(null, null, std::ptr::null(), s2); + // SAFETY: both slots are in `heap`. + assert_eq!(unsafe { *(s1 as *const [u32; 3]) }, unsafe { + *(s2 as *const [u32; 3]) + }); + // Two ranges of one into one range of two. + let (dst, dst_n, src, src_n) = ([s2], [2u32], [s0, s1], [1u32, 1]); + copy( + null, + 1, + dst.as_ptr(), + dst_n.as_ptr(), + 2, + src.as_ptr(), + src_n.as_ptr(), + 0, + ); + assert_eq!(view(s2), view(s0)); + assert_eq!(view(s3), view(s1)); + assert_eq!(view(at(0) + 8), None); + 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] + fn views_die_with_their_resource() { + let null = std::ptr::null(); + let slots = [0u64; 2 * 4]; + let (a, b) = (slots.as_ptr() as u64, slots.as_ptr() as u64 + 32); + let resource = 0x7777_0000usize as This; + create_srv(null, resource, std::ptr::null(), a); + assert_eq!(view(a), Some(View::Shader(0x7777_0000, None))); + forget(0x7777_0000); + assert_eq!(view(a), None, "stale after release"); + create_srv(null, resource, std::ptr::null(), b); + assert_eq!(view(b), Some(View::Shader(0x7777_0000, None))); + // SAFETY: both slots are in `slots`. + let (old, new) = unsafe { (*(a as *const [u32; 3]), *(b as *const [u32; 3])) }; + assert_ne!(old, new, "a new generation"); + } + + /// Grand Theft Auto VI 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() { + let mut memory = vec![0u8; 64 * 32]; + let address = memory.as_mut_ptr() as u64; + let desc = HeapDesc { + kind: 0, + count: 64, + flags: 1, + nodes: 1, + }; + let mut h = std::ptr::null(); + assert_eq!( + create( + desc, + Placement { + address, + size: 64 * 32 + }, + &mut h + ), + S_OK + ); + assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address); + assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), address); + // A size that does not match the count is not a placement. + assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK); + assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address); + } +} diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs new file mode 100644 index 000000000..cc061c735 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -0,0 +1,2473 @@ +//! Host descriptor heaps behind the title's shader-visible heaps (decision +//! 0007, step 3). Translated shaders index the heaps directly at the +//! title's descriptor positions, so each host heap keeps the title heap's +//! order: slot `i` is made from what the title wrote at slot `i`, when it +//! writes it (view creation and descriptor copies) and again when a draw +//! reads it through a table and finds the slot changed. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::{VIEW_TAG, View, view_at}; +use crate::host::host; + +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`: [`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, + sampler: bool, + /// The record (view index and generation) each slot was last made from. + made: Mutex<Vec<u64>>, + /// The host resource each slot views, held while the slot does: shaders + /// index heaps directly, so a slot the title has not rewritten since it + /// released the resource may still be read, and a freed host resource + /// read there is a GPU page fault (the console reads stale memory). + kept: Mutex<Vec<Option<ID3D12Resource>>>, + /// Where the search for free dynamic slots starts, and which are taken + /// (by lists not yet reset). + next: Mutex<(u32, Vec<bool>)>, + /// How many dynamic slots are free (changed under `next`'s lock): with + /// fewer than a table needs, the search is not made. Once the world + /// had taken them all, every later table of the frame searched every + /// slot before it was refused. + free: std::sync::atomic::AtomicU32, + /// The shortest table that found no run of free slots since slots were + /// last given back (changed under `next`'s lock; `u32::MAX`: none). + /// Until something is given back the free runs only shrink, so a table + /// of that length or longer is refused without the search. Enough + /// slots were free, but in pieces, and every such table walked the + /// whole ring before it was refused: 0.33 ms each with 131,072 slots, + /// 1.0 s of the recording threads in a frame that refused 3,143 (run + /// 45), under the lock all of them need. (A free run that lies across + /// the place the search starts from is seen by neither.) + too_long: std::sync::atomic::AtomicU32, + /// 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<std::collections::BTreeSet<u32>>, + /// Of those and of the slots that left the set: the ones written since + /// [`HostHeap::buffer_changes`] last took them. + changed: Mutex<std::collections::HashSet<u32>>, + /// 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<TextureQueue>, + /// 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 (Grand Theft Auto VI: 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<std::sync::atomic::AtomicU32>, + /// 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<Spans>, +} + +/// Title memory by the placed texture views that describe it: per span of +/// memory (its start, its end) the title slots holding a view of a +/// texture that takes exactly that span. Spans never overlap: a console +/// title need not clear a descriptor when it streams a texture out, so a +/// view written over memory that older views describe otherwise (another +/// start or another length: another texture) is all that says the older +/// ones are stale. Views of one span with different descriptions (the +/// formats of one family, say) are one texture's. +/// No host heap is needed, so it is tested without one. +#[derive(Default)] +pub(crate) struct Spans { + by_start: std::collections::BTreeMap<u64, (u64, std::collections::BTreeSet<u32>)>, + by_slot: std::collections::HashMap<u32, u64>, + /// 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<u64>>, +} + +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<u64> { + 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)`. + fn overlapping(&self, start: u64, end: u64) -> Vec<u64> { + 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 describe that + /// memory otherwise are stale: they are returned, and forgotten. + /// Otherwise (a draw made the slot from what it held) a view that + /// overlaps other spans is left out. + fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec<u32> { + let same = |span: Option<&(u64, std::collections::BTreeSet<u32>)>| 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 mut stale = Vec::new(); + for at in self.overlapping(start, end) { + if at == start && same(self.by_start.get(&at)) { + continue; + } + if !newer { + return stale; + } + if let Some((_, slots)) = self.by_start.remove(&at) { + 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<u32> { + 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<Vec<(u64, u64)>> = 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]; + +/// Whether a view written over memory that older views describe otherwise +/// makes those stale; `VICTORY_STALE_TEXTURES=0` leaves them as they are. +fn stale_out() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_STALE_TEXTURES").is_none_or(|v| v != "0")) +} + +/// 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 +/// Grand Theft Auto VI 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<bool> = 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, +} + +/// 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<u32, Waiting>, + 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 }); + } + + 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)); + } + } + + /// 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 }); + } + + /// 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<String> { + 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<u32> { + 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 +/// device-removed reports: a shader indexing a heap past its end faults. +static GPU_RANGES: Mutex<Vec<(u64, u64, u64, bool)>> = Mutex::new(Vec::new()); + +/// For device-removed reports: where host GPU address `va` lies against +/// the host descriptor heaps. +pub(crate) fn near_heaps(va: u64) -> String { + let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let mut text = String::new(); + for &(start, bytes, step, sampler) in ranges.iter() { + let kind = if sampler { "sampler" } else { "view" }; + let place = if va < start { + format!("{:#x} below", start - va) + } else if va < start + bytes { + format!("inside, slot {}", (va - start) / step) + } else { + format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) + }; + text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); + } + text +} + +/// 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; + +/// Asks the host, once, whether it caps view heaps at [`PORTABLE_VIEWS`], +/// and if so tells the translator now (`set_view_heap_limit`) instead of +/// when the title's heap is made: a shader keeps the limit it was +/// translated with, and Grand Theft Auto VI makes 25 pipelines (their +/// shaders translated at once) before it makes its view heap. Those would +/// read a view index past the heap unclamped, the read that hangs NVIDIA. +/// Called before a shader is translated. +/// shortcut: the limit is the capped heap's last slot whatever size the +/// title's heap turns out to have; a heap that fits is not capped and +/// keeps no null slot there (an index past it is as undefined as before). +pub(crate) fn probe_view_limit() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let Some(host) = host() else { return }; + // SAFETY: plain heap creation; the heap is released at once. + let made: windows::core::Result<ID3D12DescriptorHeap> = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: PORTABLE_VIEWS + 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + }; + if made.is_err() { + tracing::info!("the host caps view heaps at {PORTABLE_VIEWS}: view indices are clamped from the first shader on"); + victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1); + } + }); +} + +/// 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 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<Self> { + let host = host()?; + let kind = if sampler { + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + } else { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV + }; + let make = |count: u32| -> windows::core::Result<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, + }) + } + }; + let extra = if sampler { 0 } else { DYNAMIC }; + let (heap, count, size) = match make(count + extra) { + Ok(heap) => (heap, count, count + extra), + Err(e) if !sampler && count + extra > PORTABLE_VIEWS => { + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. The heap's last slot stays null, and shaders read it for + // any view index from there on (`set_view_heap_limit`): a read past the heap's + // end hung NVIDIA's GPU (the title's heap is a little over 1 000 000 views). + tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}; views past it read a null slot"); + victory_shader::emit::set_view_heap_limit(PORTABLE_VIEWS - 1); + (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra - 1, PORTABLE_VIEWS) + } + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; + } + }; + // SAFETY: a live heap. + let (cpu, step) = unsafe { + ( + heap.GetCPUDescriptorHandleForHeapStart().ptr, + host.device.GetDescriptorHandleIncrementSize(kind), + ) + }; + tracing::debug!(count, sampler, "host descriptor heap"); + // SAFETY: a live shader-visible heap. + let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; + GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( + gpu, + u64::from(count + extra) * u64::from(step), + u64::from(step), + sampler, + )); + 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, + sampler, + made: Mutex::new(vec![0; count as usize]), + kept: Mutex::new(vec![None; (count + extra) as usize]), + next: Mutex::new((0, vec![false; DYNAMIC as usize])), + free: std::sync::atomic::AtomicU32::new(DYNAMIC), + 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 + // used-resource entry names) read a wild address. Every slot starts + // null instead. + let started = std::time::Instant::now(); + 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"); + Some(h) + } + + /// Makes the first `total` slots null: one null slot in a CPU-side heap, + /// doubled by copies to a block, the block copied over the heap. + fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { + const BLOCK: u32 = 1 << 16; + let Some(host) = host() else { return Ok(()) }; + // 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() + })?; + let start = block.GetCPUDescriptorHandleForHeapStart(); + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + (i * self.step) as usize, + }; + if self.sampler { + null_sampler(start); + } else { + null_view(start); + } + let mut filled = 1; + while filled < BLOCK { + let n = filled.min(BLOCK - filled); + 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); + done += n; + } + } + Ok(()) + } + + /// A plain point sampler at slot `index`, for sampler slots without a + /// view. + fn null_sampler(&self, index: u32) { + null_sampler(self.cpu(index)); + } +} + +/// A plain point sampler at `at`. +fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = 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, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + ..Default::default() + }; + // SAFETY: a slot of a sampler heap of ours. + unsafe { host.device.CreateSampler(&desc, at) }; +} + +impl HostHeap { + /// `n` consecutive free dynamic slots (view heaps only), taken until + /// [`HostHeap::release`]: the first's index. + pub(crate) fn dynamic(&self, n: u32) -> Option<u32> { + 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.take(if enough { DYNAMIC as usize } else { 0 }) { + // A run cannot wrap past the end. + if at != last.wrapping_add(1) { + run = 0; + } + last = at; + run = if taken[at] { 0 } else { run + 1 }; + if run == n { + found = Some(at + 1 - n); + break; + } + } + let Some(first) = found else { + if enough { + self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::DynamicRefused, 1); + add(C::DynamicNs, started.elapsed().as_nanos() as u64); + } + return None; + }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); + taken[first..first + n].fill(true); + self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); + *next = ((first + n) % DYNAMIC as usize) as u32; + Some(self.count + first as u32) + } + + /// 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 GPU address of the table of element strides by title slot (view + /// heaps). + pub(crate) fn strides_gpu(&self) -> Option<u64> { + 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)) + } + + /// 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), + } + } + + /// 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<u32> = { + 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() + } + + /// 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<u32> { + 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<u32> { + 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<u32> { + 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.note(index, start, end, !seen && stale_out()) + } + 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`] + /// returned). + /// + /// [`dynamic`]: HostHeap::dynamic + pub(crate) fn release(&self, first: u32, n: u32) { + let Some(at) = first.checked_sub(self.count) else { + return; + }; + let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let end = (at + n).min(self.dynamic) as usize; + if let Some(slots) = guard.1.get_mut(at as usize..end) { + let given = slots.iter().filter(|taken| **taken).count() as u32; + self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); + self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); + slots.fill(false); + } + } + + /// Makes slot `index` (a dynamic one) from `view`; a null view if the + /// host cannot. + pub(crate) fn make_at(&self, index: u32, view: &View) { + let kept = make(view, self.cpu(index)); + if kept.is_none() { + null_for(view, self.cpu(index)); + } + self.keep(index, kept.flatten()); + } + + /// Makes slot `index` read nothing: a null view, or a plain sampler. + pub(crate) fn make_null(&self, index: u32) { + if self.sampler { + self.null_sampler(index); + } else { + null_view(self.cpu(index)); + } + self.keep(index, None); + } + + /// Slot `index` now views `resource` (or nothing of the host's). + fn keep(&self, index: u32, resource: Option<ID3D12Resource>) { + 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); + } + } + } + + /// 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, + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer covering the range. + unsafe { + 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 + /// `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: offset / 4, + NumElements: elements, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer covering the range. + unsafe { + host.device.CreateUnorderedAccessView( + buffer, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; + self.keep(index, Some(buffer.clone())); + } + + /// 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`. + pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { + // SAFETY: a live shader-visible heap. + let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: start + u64::from(index) * u64::from(self.step), + } + } + + /// 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); + let Some(host) = host() else { return }; + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu, + SizeInBytes: size.next_multiple_of(256), + }; + // SAFETY: a slot of our heap; the memory is the caller's. + unsafe { + host.device + .CreateConstantBufferView(Some(&desc), self.cpu(index)) + }; + } + + fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.cpu + index as usize * self.step as usize, + } + } + + /// Makes host slot `index` from the record the title has at `handle` + /// if it changed since, and returns the view recorded there. Buffer + /// views are made only for draws (`for_draw`), which also copy their + /// data: a host copy of a buffer is made on first use. + pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> { + if index >= self.count { + // Diagnostic (NVIDIA heap cap): the highest title slot past the + // host heap seen so far. + static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index { + tracing::warn!( + index, + count = self.count, + for_draw, + "title slot past the host heap" + ); + } + return None; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + // Generations start at 1, so a made slot's key is never 0. + let key = u64::from(generation) << 32 | u64::from(i); + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); + let Some(view) = view else { + // Not a view of ours (never written, or of a resource the + // title released): nothing to read. + 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; + }; + if made[index as usize] != key { + // 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 + } else { + make(&view, self.cpu(index)) + }; + if kept.is_none() && !self.sampler { + null_for(&view, self.cpu(index)); + } + self.keep(index, kept.flatten()); + } + 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<bool> { + 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)) + } + + /// 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<String> { + let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + if key == 0 { + return Some("null".into()); + } + let view = view_at(key as u32, (key >> 32) as u32)?; + let mut text: String = format!("{view:?}").chars().take(120).collect(); + if let Some((address, len)) = buffer_range(&view) { + let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address)); + text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}")); + } + Some(text) + } +} + +/// Logs `what` the first time it happens. +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +/// A view description from its words, with the format as the host has it. +fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC { + let mut words = *words; + words[0] = crate::resource::pc_format(words[0]); + // SAFETY: 40 bytes in the host's layout. + unsafe { + std::ptr::from_ref(&words) + .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>() + .read_unaligned() + } +} + +fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut words = *words; + words[0] = crate::resource::pc_format(words[0]); + // SAFETY: 40 bytes in the host's layout. + unsafe { + std::ptr::from_ref(&words) + .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>() + .read_unaligned() + } +} + +/// A buffer view of title memory at `address` on its host copy: the first +/// element moves by the copy's offset. +/// Bytes per element of a buffer view. +fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 { + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + } +} + +/// The title memory a buffer shader or unordered access view reads: its +/// address and length. +pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { + let (base, words): (u64, &[u32; 10]) = match view { + View::Shader(r, Some(desc)) => ( + crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64, + desc, + ), + View::Placed(false, resource, desc) if resource[0] == 1 => ( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + desc[..10].try_into().ok()?, + ), + View::Unordered(r, _, Some(desc)) => { + let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64; + return unordered_range(base, desc); + } + View::Placed(true, resource, desc) if resource[0] == 1 => { + let base = u64::from(desc[10]) | u64::from(desc[11]) << 32; + return unordered_range(base, desc[..10].try_into().ok()?); + } + _ => return None, + }; + let desc = srv_desc(words); + let element = element_size(&desc); + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + Some(( + base + buffer.FirstElement * element, + u64::from(buffer.NumElements) * element, + )) +} + +/// 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<bool> = 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<crate::shadow::Shadow>, 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); + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + let element = if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32)?.0 + }; + Some(( + base + buffer.FirstElement * element, + u64::from(buffer.NumElements) * element, + )) +} + +/// The host resource a slot made by [`make`] views, if any. +type Kept = Option<ID3D12Resource>; + +/// 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; + } + 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() +} + +/// 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, + len: u64, + mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) -> Option<Kept> { + 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 }; + 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!( + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "buffer view the host would refuse left null" + ); + return None; + } + // 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 { + host.device + .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) + }; + Some(Some(shadow.buffer.clone())) +} + +/// An unordered access view of title buffer memory at `address` (`len` +/// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be +/// written by shaders (upload memory). +/// shortcut: what shaders write stays in the host copy; title memory (and +/// so the CPU, and copies run on the CPU) does not see it. +fn buffer_uav( + address: u64, + len: u64, + mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) -> Option<Kept> { + let shadow = crate::shadow::find(address, len)?; + // SAFETY: a live buffer. + let flags = unsafe { shadow.buffer.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + once!("unordered access to a buffer whose host copy shaders cannot write"); + return None; + } + // SAFETY: a buffer view's union member. + let buffer = unsafe { &mut desc.Anonymous.Buffer }; + let element = if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let offset = shadow.offset(address); + // A structured view as a raw view of the same bytes (see `raw_window`). + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) + .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!( + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "unordered buffer view the host would refuse left null" + ); + return None; + } + let host = host()?; + // SAFETY: a live buffer and a slot of our heap. + unsafe { + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) + }; + Some(Some(shadow.buffer.clone())) +} + +/// Whether the host can make a shader (or unordered access) view of +/// `texture` in `format` (none: the texture's own). The console allows any +/// view; the host refuses (and removes the device for) views without the +/// resource's permission, of typed depth, and in another format than a +/// typed resource's. A view of a typed texture in another format of its +/// family takes the texture's format. +/// shortcut: such a view (sRGB of UNORM, say) reads without its +/// conversion; cast with castable formats if colors come out wrong. +fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool { + use crate::resource::{DEPTH_FORMATS, family}; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + let allowed = if unordered { + d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 + } else { + d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0 + }; + 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, + flags = d.Flags.0, + "view the host does not allow" + ); + return false; + } + // Every family has more than one format, its typeless one first. + let typeless = family(own) == own && family(own + 1) == own; + if let Some(format) = format.as_deref_mut() + && unordered + && let Some(&(_, linear)) = crate::resource::SRGB + .iter() + .find(|&&(s, _)| s == format.0 as u32) + { + format.0 = linear as i32; + } + let view = format.as_ref().map_or(0, |f| f.0 as u32); + 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; + } + if let Some(format) = format + && !typeless + { + *format = d.Format; + } + true +} + +/// 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<D3D12_UNORDERED_ACCESS_VIEW_DESC> { + // 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() + }; + 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_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 +/// views, or `None` if it cannot. +fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> { + let host = host()?; + let device = &host.device; + match view { + &View::Constant(address, size) => { + let shadow = crate::shadow::find(address, u64::from(size))?; + let gpu = shadow.gpu(address); + if gpu % 256 != 0 { + once!( + address = format_args!("{address:#x}"), + "constant buffer not 256-byte aligned on the host" + ); + return None; + } + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu, + SizeInBytes: size.next_multiple_of(256), + }; + // SAFETY: a slot of our heap; the range lies in the host copy. + unsafe { device.CreateConstantBufferView(Some(&desc), at) }; + Some(Some(shadow.buffer.clone())) + } + View::Shader(resource, desc) => { + let resource = *resource as crate::object::This; + if let Some(texture) = crate::resource::host_resource(resource) { + // The title's views of textures with a stencil plane, as it + // describes them (format, dimension, component mapping, a + // pad, then first level, levels, plane): each distinct one + // once. They say how its shaders read the stencil plane + // (the lighting takes each pixel's material class and its + // "inside a room" bit from it). + #[cfg(feature = "diagnostics")] + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }.Format.0; + if matches!(own, 19..=22 | 44..=47) { + static SEEN: Mutex<Vec<(i32, Option<[u32; 10]>)>> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.len() < 64 && !seen.contains(&(own, *desc)) { + seen.push((own, *desc)); + tracing::info!( + ?resource, + texture_format = own, + view = ?desc, + "shader view of a depth-stencil texture" + ); + } + } + } + let mut desc = desc.as_ref().map(srv_desc); + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { + return None; + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateShaderResourceView( + texture, + desc.as_ref().map(std::ptr::from_ref), + at, + ) + }; + Some(Some(texture.clone())) + } else if let (Some((data, len)), Some(desc)) = + (crate::resource::buffer_bytes(resource), desc) + { + buffer_srv(data as u64, len, srv_desc(desc), at) + } else { + None + } + } + View::Unordered(resource, _counter, desc) => { + let resource = *resource as crate::object::This; + let Some(texture) = crate::resource::host_resource(resource) else { + return match (crate::resource::buffer_bytes(resource), desc) { + (Some((data, len)), Some(desc)) => { + buffer_uav(data as u64, len, uav_desc(desc), at) + } + _ => 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; + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateUnorderedAccessView( + texture, + None::<&ID3D12Resource>, + desc.as_ref().map(std::ptr::from_ref), + at, + ) + }; + Some(Some(texture.clone())) + } + View::Sampler(words) => { + // SAFETY: 13 words in the host's layout. + let desc = unsafe { + std::ptr::from_ref(words) + .cast::<D3D12_SAMPLER_DESC>() + .read_unaligned() + }; + // SAFETY: a slot of our sampler heap. + unsafe { device.CreateSampler(&desc, at) }; + Some(None) + } + View::ConsoleSampler(words) => { + let desc = crate::sampler::console(words); + // SAFETY: a slot of our sampler heap. + unsafe { device.CreateSampler(&desc, at) }; + Some(None) + } + View::Placed(unordered, resource, desc) => { + if let Some(view) = placed_texture(view) { + return make(&view, at); + } + const BUFFER: u32 = 1; + if resource[0] != BUFFER { + // 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"); + return None; + } + // The resource description's width, after the alignment. + let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); + if *unordered { + buffer_uav(address, len, uav_desc(words), at) + } else { + buffer_srv(address, len, srv_desc(words), at) + } + } + } +} + +/// 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<bool> = 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<View> { + const BUFFER: u32 = 1; + let View::Placed(false, resource, desc) = view else { + return None; + }; + if resource[0] == BUFFER { + return None; + } + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let texture = crate::resource::texture_at(address, resource)?; + Some(View::Shader(texture as usize, desc[..10].try_into().ok())) +} + +/// A null view of the kind `view` is, for a slot whose view the host +/// cannot make: unordered access (to a buffer or a 2D texture) or a shader +/// view. Writes to it are dropped, reads give zeros. +fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); + // Unordered views: whether a buffer, and the title's view dimension. + let (buffer, dimension) = match view { + View::Unordered(r, _, desc) => ( + is_buffer(r) || desc.is_some_and(|d| d[1] == 1), + desc.map(|d| d[1]), + ), + View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])), + // Shader views of buffers read nothing through a null buffer view: + // a null 2D view where the shader expects a buffer is a mismatch + // the hardware does not survive in general (GPU-based validation + // reports it). + View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => { + return null_buffer_view(at); + } + View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at), + // Textures: a null view of the title's dimension (1D, arrays, 3D, + // cubes), not always 2D. + View::Shader(_, Some(desc)) => return null_like(desc, at), + View::Placed(false, _, desc) => { + return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at); + } + View::Constant(..) => { + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); + // SAFETY: a slot of our heap; a zero location makes a null view. + return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) }; + } + _ => return null_view(at), + }; + let desc = if buffer { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + } + } else { + null_uav_desc(dimension) + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + at, + ) + }; +} + +/// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays, +/// 3D), 2D if it names none: a 2D null view where the shader writes a 3D +/// texture is a mismatch GPU-based validation reports (the world's wind +/// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24). +fn null_uav_desc(dimension: Option<u32>) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) { + Some(D3D12_UAV_DIMENSION_TEXTURE1D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + } + Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE3D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + desc.Anonymous.Texture3D = D3D12_TEX3D_UAV { + WSize: u32::MAX, + ..Default::default() + }; + } + _ => {} + } + desc +} + +/// A buffer view that reads zeros (raw, as translated shaders mostly read +/// buffers). +fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + 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 { + NumElements: 1, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +/// A texture view that reads zeros with the dimension (and mip and array +/// counts) of the title's description `words`; 2D if it names none. +fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { + const TEXTURES: std::ops::RangeInclusive<u32> = 2..=10; + if !TEXTURES.contains(&words[1]) { + return null_view(at); + } + let Some(host) = host() else { return }; + // One mip, one slice or cube, plane 0: fields a null view still checks. + let mut w = [0u32; 10]; + w[1] = words[1]; + match words[1] { + 6 => {} + 7 => w[5] = 1, + 3 | 5 | 10 => (w[5], w[7]) = (1, 1), + _ => w[5] = 1, + } + let mut desc = srv_desc(&w); + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +/// A view that reads zeros, for slots whose view the host cannot make. +/// shortcut: slots with no view at all (kind unknown) get this null 2D +/// view; null buffer views there did not stop the world's low-address +/// page faults (2026-11-24, run w10), so they are not the cause. +fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A null texture UAV keeps the title's dimension (3D for the world's + /// wind field), and is 2D when the title names none. + #[test] + fn null_uavs_keep_the_titles_dimension() { + let d = null_uav_desc(Some(8)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX); + let d = null_uav_desc(Some(5)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1); + let dimension = |d| null_uav_desc(d).ViewDimension; + assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D); + assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D); + assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D); + // Multisampled UAVs need a cap; they stay 2D. + 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() { + let Some(host) = host() else { + return; // no host GPU + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0])); + null_for(&view, heap.cpu(0)); + // SAFETY: a plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + + /// 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<u32> = 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)); + } + + /// 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::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<u32> { 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<u32> { 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 { + return; // no host GPU + }; + let a = heap.dynamic(heap.dynamic - 100).unwrap(); + let b = heap.dynamic(60).unwrap(); + assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); + // 40 left at the end: 50 do not fit until something is given back. + assert_eq!(heap.dynamic(50), None); + heap.release(a, 50); + assert_eq!(heap.dynamic(50), Some(4)); + assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); + } +} diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs new file mode 100644 index 000000000..3b19f538a --- /dev/null +++ b/crates/victory-gpu/src/device.rs @@ -0,0 +1,587 @@ +//! The device titles get from device creation, laid out as their inlined +//! code expects: the object header, then device fields. Its table starts +//! like the PC device interface (IUnknown, the object methods, then the +//! device methods in PC order); console additions follow. Methods we have +//! not written log their table offset and fail, so a run shows what to +//! write next. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; + +use crate::object::{ + self, E_INVALIDARG, E_NOINTERFACE, E_NOTIMPL, HRESULT, Iid, Object, S_FALSE, S_OK, Table, This, + guid, guid_text, +}; +use crate::{ + descriptor, dxgi, fence, frame, list, pipeline, query, queue, resource, root, signature, +}; + +/// What D3D returns when none of the requested feature levels is supported. +const UNSUPPORTED: HRESULT = 0x887A_0004_u32 as i32; + +/// The device interface id (the same as on PC). Titles also import it as +/// data. +pub static IID: Iid = guid( + 0x189819f1, + 0x1db6, + 0x4b57, + [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], +); + +/// The levels the device answers to, as on PC: `ID3D12Device1` to +/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates +/// its device as. Each level's table is the one before plus its methods. +const LEVEL_IIDS: [Iid; 9] = [ + guid( + 0x77acce80, + 0x638e, + 0x4e65, + [0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e], + ), + guid( + 0x30baa41e, + 0xb15b, + 0x475c, + [0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28], + ), + guid( + 0x81dadc15, + 0x2bad, + 0x4392, + [0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98], + ), + guid( + 0xe865df17, + 0xa9ee, + 0x46f9, + [0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5], + ), + guid( + 0x8b4f173b, + 0x2fea, + 0x4b80, + [0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d], + ), + guid( + 0xc70b221b, + 0x40e4, + 0x4a17, + [0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc], + ), + guid( + 0x5c014b53, + 0x68a1, + 0x4b9b, + [0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b], + ), + guid( + 0x728f1fa2, + 0xea11, + 0x4a9f, + [0x9b, 0x52, 0x9b, 0x42, 0xa4, 0x84, 0xd5, 0xc9], + ), + guid( + 0x5405c344, + 0xd457, + 0x444e, + [0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39], + ), +]; + +/// Whether `iid` names the device: its first interface or a newer level. +pub(crate) fn is_device(iid: *const Iid) -> bool { + object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS) +} + +/// The interface version these layouts were checked against (2.4). Both +/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it. +pub const CHECKED_VERSION: u32 = 0x0002_0004; + +/// Feature level 12_2, what the console hardware supports. +const HIGHEST_FEATURE_LEVEL: u32 = 0xc200; + +#[repr(C)] +pub struct Device { + object: Object, + /// GPU address of a null constant buffer; none yet. + null_constant_buffer: u64, + /// Byte 0 non-zero: calls the title would otherwise inline come to the + /// table. The rest is reserved. + out_of_line: [u32; 16], +} +const _: () = assert!(size_of::<Device>() == 0x58); + +/// One device per process, as on the console. +pub(crate) static DEVICE: Device = Device { + object: Object::new(&FUNCTIONS), + null_constant_buffer: 0, + out_of_line: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +}; + +pub(crate) fn device() -> This { + (&raw const DEVICE).cast() +} + +/// Device creation: `(adapter, parameters, iid, out)`. The parameters start +/// with the interface version; the rest (ring and scratch sizes, features +/// to leave out) does not matter to us yet. +pub extern "system" fn create( + _adapter: *const c_void, + parameters: *const u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if parameters.is_null() || iid.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes its parameters and an id. + let (version, iid) = unsafe { (parameters.read(), &*iid) }; + tracing::info!(version = format_args!("{version:#x}"), "D3D12.X device"); + if version != CHECKED_VERSION { + tracing::warn!( + version = format_args!("{version:#x}"), + "device layouts were checked against {CHECKED_VERSION:#x} only" + ); + } + if !is_device(iid) { + tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface"); + return E_NOINTERFACE; + } + if out.is_null() { + return S_FALSE; + } + if *iid == LEVEL_IIDS[8] { + NEWER.store(true, std::sync::atomic::Ordering::Relaxed); + } + object::answer(object::DEVICE, iid, Some(device()), out) +} + +/// Set when the title creates the device as `ID3D12Device11`. Its lists and +/// 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); +/// look for a better one if a title breaks the rule. +static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(crate) fn newer() -> bool { + NEWER.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The device, or its DXGI side. +extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = if is_device(iid) { + Some(this) + } else if object::is(iid, &dxgi::DEVICE_IIDS) { + Some(dxgi::device()) + } else { + None + }; + object::answer(object::DEVICE, iid, found, out) +} + +/// What `D3D12ConfigureVirtualMemoryX` takes and fills in. +#[repr(C)] +pub struct VirtualMemory { + flags: u32, + /// GPU page table size in 4 MiB pages. + page_table_pages: u32, + /// Memory kept across title processes for the frame buffer. + preserved_bytes: u32, + /// Out: the range graphics addresses fall in. + lowest: u64, + highest: u64, +} +const _: () = assert!(size_of::<VirtualMemory>() == 0x20); + +/// `d3d12_xs!D3D12ConfigureVirtualMemoryX`, called before any graphics +/// allocation. The inputs size console structures we do not have; the +/// range out is all of user space, since GPU addresses are CPU addresses. +pub extern "system" fn configure_virtual_memory(config: *mut VirtualMemory) -> HRESULT { + // SAFETY: the title passes its configuration (null is tolerated). + let Some(config) = (unsafe { config.as_mut() }) else { + return E_INVALIDARG; + }; + tracing::info!( + flags = config.flags, + page_table_pages = config.page_table_pages, + preserved_bytes = config.preserved_bytes, + "graphics virtual memory" + ); + (config.lowest, config.highest) = user_space(); + S_OK +} + +fn user_space() -> (u64, u64) { + #[cfg(windows)] + { + use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO}; + // SAFETY: plain data, filled in by the call. + let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer. + unsafe { GetSystemInfo(&mut info) }; + ( + info.lpMinimumApplicationAddress as u64, + info.lpMaximumApplicationAddress as u64, + ) + } + #[cfg(not(windows))] + (0x1_0000, 0x7fff_fffe_ffff) +} + +extern "system" fn node_count(_: This) -> u32 { + 1 +} + +/// Feature query 2: the highest of the requested feature levels we support. +#[repr(C)] +struct FeatureLevels { + count: u32, + requested: *const u32, + highest: u32, +} + +/// Feature query 0, what an RDNA 2 GPU reports. The console's layout has +/// one field more than PC's (index 11). +const OPTIONS: [u32; 16] = [ + 1, // double-precision shader operations + 1, // output-merger logic operations + 2, // minimum precision: 16-bit + 3, // tiled resources tier + 3, // resource binding tier + 1, // stencil reference from pixel shaders + 1, // typed UAV loads of more formats + 1, // rasterizer-ordered views + 3, // conservative rasterization tier + 40, // GPU address bits per resource + 0, // 64 KiB standard swizzle + 0, // console-only field + 0, // cross-node sharing tier + 0, // cross-adapter row-major textures + 1, // viewport and render target index from any stage + 2, // resource heap tier +]; + +extern "system" fn check_feature_support( + _: This, + feature: u32, + data: *mut c_void, + size: u32, +) -> HRESULT { + const OPTIONS_QUERY: u32 = 0; + const ARCHITECTURE: u32 = 1; + const FEATURE_LEVELS: u32 = 2; + const FORMAT_SUPPORT: u32 = 3; + const MULTISAMPLE: u32 = 4; + let expected = match feature { + OPTIONS_QUERY => size_of_val(&OPTIONS), + ARCHITECTURE => 16, + FEATURE_LEVELS => size_of::<FeatureLevels>(), + FORMAT_SUPPORT => 12, + MULTISAMPLE => 16, + _ => { + tracing::warn!(feature, size, "device feature query not implemented"); + return E_NOTIMPL; + } + }; + if data.is_null() || size as usize != expected { + return E_INVALIDARG; + } + match feature { + OPTIONS_QUERY => { + // SAFETY: checked size and non-null. + unsafe { data.cast::<[u32; 16]>().write_unaligned(OPTIONS) }; + S_OK + } + ARCHITECTURE => { + // SAFETY: checked size and non-null. + let a = unsafe { &mut *data.cast::<[u32; 4]>() }; + if a[0] != 0 { + return E_INVALIDARG; // one node only + } + // Not tile-based; unified, cache-coherent memory. + a[1..].copy_from_slice(&[0, 1, 1]); + S_OK + } + FORMAT_SUPPORT => { + // SAFETY: checked size and non-null. + let q = unsafe { &mut *data.cast::<[u32; 3]>() }; + // shortcut: every use of every format; answer from the host + // device once there is one. + q[1] = 0x7fff_ffff; + q[2] = 0xffff; + S_OK + } + MULTISAMPLE => { + // SAFETY: checked size and non-null. + let q = unsafe { &mut *data.cast::<[u32; 4]>() }; + // Format, sample count, flags in; one quality level out for the + // counts the hardware has. + q[3] = u32::from(matches!(q[1], 1 | 2 | 4 | 8)); + S_OK + } + _ => feature_levels(data), + } +} + +fn feature_levels(data: *mut c_void) -> HRESULT { + // SAFETY: the caller checked size and non-null. + let query = unsafe { &mut *data.cast::<FeatureLevels>() }; + if query.requested.is_null() { + return E_INVALIDARG; + } + // SAFETY: the title passes `count` levels. + let requested = unsafe { std::slice::from_raw_parts(query.requested, query.count as usize) }; + match requested + .iter() + .copied() + .filter(|&l| l <= HIGHEST_FEATURE_LEVEL) + .max() + { + Some(level) => { + query.highest = level; + S_OK + } + None => UNSUPPORTED, + } +} + +/// Device methods 0x1c8 and 0x218 (`SLOT`). Grand Theft Auto VI 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<const SLOT: usize>( + _: 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<Vec<u64>> { + 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::<Vec<u64>>; + 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 +/// `ID3D12Device9` to `ID3D12Device11`, whose console layout is unknown. +/// Every slot exists so that a call to one we have not written logs it. +static FUNCTIONS: Table<160> = { + let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 160>()); + f[0] = query_interface as *const (); // 0x00 + f[7] = node_count as *const (); // 0x38 + f[8] = queue::create as *const (); // 0x40 + f[9] = list::create_allocator as *const (); // 0x48 + f[12] = list::create_list as *const (); // 0x60 + f[10] = pipeline::create_graphics as *const (); // 0x50 + f[11] = pipeline::create_compute as *const (); // 0x58 + f[13] = check_feature_support as *const (); // 0x68 + f[14] = descriptor::create_heap as *const (); // 0x70 + f[15] = descriptor::increment_size as *const (); // 0x78 + f[16] = root::create as *const (); // 0x80 + f[17] = descriptor::create_cbv as *const (); // 0x88 + f[18] = descriptor::create_srv as *const (); // 0x90 + f[19] = descriptor::create_uav as *const (); // 0x98 + f[20] = descriptor::create_rtv as *const (); // 0xa0 + f[21] = descriptor::create_dsv as *const (); // 0xa8 + f[22] = descriptor::create_sampler as *const (); // 0xb0 + f[23] = descriptor::copy as *const (); // 0xb8 + f[24] = descriptor::copy_simple as *const (); // 0xc0 + f[25] = resource::allocation_info as *const (); // 0xc8 + f[26] = resource::custom_heap_properties as *const (); // 0xd0 + f[27] = resource::create_committed as *const (); // 0xd8 + f[28] = resource::create_heap as *const (); // 0xe0 + f[29] = resource::create_placed as *const (); // 0xe8 + f[36] = fence::create as *const (); // 0x120 + f[38] = resource::copyable_footprints as *const (); // 0x130 + 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 + f[73] = list::create_list_x as *const (); // 0x248 + f[74] = resource::register_page_pool as *const (); // 0x250 + f[75] = resource::unregister_page_pool as *const (); // 0x258 + // CreateCommittedResourceX: its description is PC's plus DCC options, + // which we have no use for (the AMD upscaler's, on Series S). + f[76] = resource::create_committed as *const (); // 0x260 + f[78] = frame::set_interval as *const (); // 0x270 + f[79] = frame::schedule as *const (); // 0x278 + f[80] = frame::wait as *const (); // 0x280 + f[81] = frame::statistics as *const (); // 0x288 + f[86] = pipeline::create_stream as *const (); // 0x2b0 + f[108] = resource::allocation_info2 as *const (); // 0x360 + f[127] = resource::create_committed3 as *const (); // 0x3f8 + f[133] = resource::create_at_address as *const (); // 0x428 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + fn create_as(iid: &Iid) -> (HRESULT, This) { + let version = CHECKED_VERSION; + let mut device = std::ptr::null(); + let hr = create(std::ptr::null(), &version, iid, &mut device); + (hr, device) + } + + #[test] + fn creation_hands_out_the_device() { + let (hr, device) = create_as(&IID); + assert_eq!(hr, S_OK); + assert_eq!(device, super::device()); + // The title tests byte 0x18 before inlining a device call. + // SAFETY: the device is 0x58 bytes. + assert_ne!(unsafe { device.cast::<u8>().add(0x18).read() }, 0); + assert_eq!(create_as(&[0; 16]).0, E_NOINTERFACE); + assert_eq!( + slot::<extern "system" fn(This) -> u32>(device, 0x38)(device), + 1 + ); + let missing = slot::<extern "system" fn() -> HRESULT>(device, 0xf0); + assert_eq!(missing(), E_NOTIMPL); + } + + #[test] + fn newer_device_levels_are_the_same_device() { + // ID3D12Device11, as Grand Theft Auto VI 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(); + assert_eq!(query_interface(device, &LEVEL_IIDS[4], &mut same), S_OK); + assert_eq!(same, device); + // A Device8 method we have not written fails without crashing. + let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x3a0); + assert_eq!(missing(), E_NOTIMPL); + } + + /// A device child, and the DXGI device, hand out the device as any + /// interface the device itself answers to. + #[test] + fn the_device_is_found_at_every_level_through_others() { + type Get = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + let fence_iid = &crate::fence::FENCE_IIDS[0]; + let mut fence = std::ptr::null(); + assert_eq!( + crate::fence::create(std::ptr::null(), 0, 0, fence_iid, &mut fence), + S_OK + ); + let get_device = slot::<Get>(fence, 0x38); + let dxgi = dxgi::device(); + let query = slot::<Get>(dxgi, 0); + for iid in std::iter::once(&IID).chain(&LEVEL_IIDS) { + let mut found = std::ptr::null(); + assert_eq!(get_device(fence, iid, &mut found), S_OK, "{iid:02x?}"); + assert_eq!(found, device()); + let mut found = std::ptr::null(); + assert_eq!(query(dxgi, iid, &mut found), S_OK, "{iid:02x?}"); + assert_eq!(found, device()); + } + // What the device is not, it is not through them either. + let mut found = device(); + assert_eq!(get_device(fence, fence_iid, &mut found), E_NOINTERFACE); + assert!(found.is_null()); + slot::<extern "system" fn(This) -> u32>(fence, 0x10)(fence); + } + + /// The host's: a fence's `GetDevice` for `ID3D12Device5`. + #[cfg(windows)] + #[test] + fn the_hosts_children_hand_out_newer_device_levels() { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FENCE_FLAG_NONE, ID3D12Device5, ID3D12Fence, + }; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + // SAFETY: plain calls on the host device and its fence. + unsafe { + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut device: Option<ID3D12Device5> = None; + assert!(fence.GetDevice(&mut device).is_ok()); + assert!(device.is_some()); + } + } + + #[test] + fn virtual_memory_configuration_reports_user_space() { + let mut config = VirtualMemory { + flags: 0, + page_table_pages: 7, + preserved_bytes: 0, + lowest: 0, + highest: 0, + }; + assert_eq!(configure_virtual_memory(&mut config), S_OK); + assert!(0 < config.lowest && config.lowest < config.highest); + let heap = Box::new(0u8); + assert!((config.lowest..=config.highest).contains(&(&raw const *heap as u64))); + assert_eq!(configure_virtual_memory(std::ptr::null_mut()), E_INVALIDARG); + } + + #[test] + fn feature_levels_pick_the_highest_supported() { + type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; + let device = device(); + let check = slot::<Check>(device, 0x68); + let query = |levels: &[u32], size| { + let mut query = FeatureLevels { + count: levels.len() as u32, + requested: levels.as_ptr(), + highest: 0, + }; + let hr = check(device, 2, (&raw mut query).cast(), size); + (hr, query.highest) + }; + let levels = [0xb000, 0xb100, 0xc000, 0xc100, 0xd000]; + assert_eq!(query(&levels, 0x18), (S_OK, 0xc100)); + assert_eq!(query(&levels, 0x10).0, E_INVALIDARG); + assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs new file mode 100644 index 000000000..f9937b1fc --- /dev/null +++ b/crates/victory-gpu/src/draw.rs @@ -0,0 +1,2692 @@ +//! Draws on the host GPU (decision 0007, step 3). A list keeps the state +//! the title sets for its draws (pipeline, descriptor heaps, root +//! arguments, vertex and index buffers, targets); each draw then brings the +//! host list up to date: the host pipeline and our root signature, the +//! user data the translated shaders read, the host copies of the buffers +//! and descriptors they read, and the states of the textures involved. +//! State the host keeps across draws (viewports, scissors, blend factor, +//! stencil reference, topology, targets) is set on the host list as the +//! title sets it. + +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; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::core::Interface; + +use crate::host::HostList; +use crate::object::This; +use crate::pipeline::host::HostPipeline; + +/// A root argument as the title set it. +#[derive(Debug, Clone, Default)] +enum Root { + #[default] + None, + /// A descriptor table's first descriptor (an address in a heap). + Table(u64), + Constants(Vec<u32>), + /// A root view's GPU address. + View(u64), +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct VertexView { + address: u64, + size: u32, + stride: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct IndexView { + address: u64, + size: u32, + format: 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<bool> = const { std::cell::Cell::new(true) }; +} + +/// 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<bool> = 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 Grand Theft Auto VI 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<bool> = 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. +#[derive(Default)] +pub(crate) struct State { + pipeline: usize, + /// View heap, sampler heap. + heaps: [usize; 2], + graphics: Vec<Root>, + compute: Vec<Root>, + vertex: [VertexView; 32], + index: IndexView, + /// Bound render target and depth resources, for their host states. + targets: Vec<usize>, + 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<u64>, + depth_handle: u64, + targets_set: bool, + viewports: Vec<D3D12_VIEWPORT>, + scissors: Vec<RECT>, + blend: Option<[f32; 4]>, + stencil: Option<u32>, + /// The indirect records clamped last, if later draws may still read + /// them ([`windows`]). + window: Option<Window>, + /// 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, slot count, contents) → first + /// dynamic slot. + 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, +} + +impl Drop for State { + fn drop(&mut self) { + for &(heap, first, n) in &self.dynamic { + crate::descriptor::release_dynamic(heap, first, n); + } + } +} + +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. Grand Theft Auto VI'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<bool> = 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<u8> = 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:<hex digits>[:<hex digits>]`: 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<Option<(String, String)>> = 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); + +/// Draws run on the host so far. +pub(crate) fn drawn() -> u64 { + DRAWN.load(Ordering::Relaxed) +} + +/// The draws traced since the last present (diagnostics builds, with +/// debug logging for this module): logged when the frame comes out black. +#[cfg(feature = "diagnostics")] +static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); + +/// The draws traced since the last call. +#[cfg(feature = "diagnostics")] +pub(crate) fn take_frame() -> Vec<String> { + std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner())) +} + +/// Draws, mesh dispatches and dispatches recorded but not run on the host +/// (no host pipeline) since the last call. +pub(crate) fn take_dropped() -> u64 { + DROPPED.swap(0, Ordering::Relaxed) +} +/// A root SRV's dynamic slot in a list, and the host copy it shows. +type RootSlot = (u32, Option<std::sync::Arc<crate::shadow::Shadow>>); + +/// 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); +/// 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. +#[cfg(feature = "diagnostics")] +fn dropped(pipeline: usize) { + crate::pipeline::note_drop(pipeline as This); + if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() { + last.push_str(" DROPPED"); + } +} + +/// Dispatches run on the host so far. +static DISPATCHED: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn dispatched() -> u64 { + DISPATCHED.load(Ordering::Relaxed) +} + +/// The host address of a root view: its buffer's host copy, or for a +/// constant buffer not 256-byte aligned there (the console needs 16) a +/// copy in upload memory. +/// shortcut: a root view has no size; constant buffers are taken as 64 KiB +/// (cut at their buffer's end), other views as all that is left of their +/// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex +/// streams of a cutscene frame reach further, and what lay past the first +/// megabyte was never brought up to date - meshes without bodies, exploded +/// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.) +fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> { + static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_VIEW_MB") + .ok() + .and_then(|v| v.parse::<u64>().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); + let shadow = crate::shadow::find(address, 1)?; + let len = shadow + .left(address) + .min(if srv { limit } else { 1 << 16 }); + let gpu = shadow.gpu(address); + if srv || gpu % 256 == 0 { + shadow.refresh(list, address, len); + return Some(gpu); + } + let (gpu, to) = list.scratch(len)?; + list.defer_fill(to, address as *const u8, len as usize); + Some(gpu) +} + +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +fn set(roots: &mut Vec<Root>, slot: u32, root: Root) { + let slot = slot as usize; + if roots.len() <= slot { + roots.resize(slot + 1, Root::None); + } + roots[slot] = root; +} + +impl State { + pub(crate) fn reset(&mut self, pipeline: This) { + *self = State::default(); + self.pipeline = pipeline as usize; + } + + /// The title's topology; console-only ones become host lists (see + /// [`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 => { + once!(topology, "console topology drawn as a triangle list"); + 4 + } + t => t, + }; + // SAFETY: an open list. + unsafe { + list.list + .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32)) + }; + } + + pub(crate) fn set_pipeline(&mut self, pipeline: This) { + self.pipeline = pipeline as usize; + } + + pub(crate) fn set_heaps(&mut self, heaps: &[This]) { + self.heaps = [0; 2]; + for &h in heaps { + if !h.is_null() { + let samplers = crate::descriptor::heap(h).samplers(); + self.heaps[usize::from(samplers)] = h as usize; + } + } + } + + fn roots(&mut self, compute: bool) -> &mut Vec<Root> { + if compute { + &mut self.compute + } else { + &mut self.graphics + } + } + + pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) { + set(self.roots(compute), slot, Root::Table(handle)); + } + + pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) { + set(self.roots(compute), slot, Root::View(address)); + } + + pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) { + let roots = self.roots(compute); + let s = slot as usize; + if !matches!(roots.get(s), Some(Root::Constants(_))) { + set(roots, slot, Root::Constants(Vec::new())); + } + if let Root::Constants(c) = &mut roots[s] { + let end = offset as usize + values.len(); + if c.len() < end { + c.resize(end, 0); + } + c[offset as usize..end].copy_from_slice(values); + } + } + + pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) { + for (i, v) in views.iter().enumerate() { + if let Some(slot) = self.vertex.get_mut(start as usize + i) { + *slot = *v; + } + } + } + + 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) { + *slot = VertexView::default(); + } + } + + pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { + self.index = view.copied().unwrap_or_default(); + } + + /// Render targets and depth, set on the host list at once. + pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { + 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 { + let Some(record) = crate::descriptor::rtv_record(h) else { + once!( + handle = format_args!("{h:#x}"), + "render target without a recorded view" + ); + continue; + }; + let Some(texture) = crate::resource::host_resource(record.resource) 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(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())) + }); + // SAFETY: an open list; the views were just made. + unsafe { + list.list.OMSetRenderTargets( + rtvs.len() as u32, + (!rtvs.is_empty()).then_some(rtvs.as_ptr()), + false, + dsv.as_ref().map(std::ptr::from_ref), + ) + }; + } + + /// 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); + } + + /// `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); + } + } + + /// The user-data value of a root argument, as translated shaders read + /// it: a table's byte offset in its heap, a constant's value. + fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { + match (self.roots_ref(compute).get(usize::from(slot)), root) { + (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) { + Some(heap) => (handle - heap.start) as u32, + None => { + once!( + handle = format_args!("{handle:#x}"), + "descriptor table outside the bound heaps" + ); + 0 + } + }, + (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, + ?root, + "a shader reads a root argument the title did not set" + ); + 0 + } + } + } + + /// 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<crate::memory::Ready> { + 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 + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| h.index(handle).is_some()) + } + + /// Brings the host list up to date for a draw; false if the draw cannot + /// run on the host. + fn prepare(&mut self, list: &HostList, indexed: bool) -> bool { + self.prepare_for(list, indexed, false) + } + + /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches. + fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool { + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + return false; + } + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return false; + }; + if p.compute || p.mesh != mesh { + 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; + } + let l = &list.list; + // Vertex buffers the input layout reads. + let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; + let mut count = 0; + for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() { + if p.slots & 1 << slot == 0 { + continue; + } + count = slot + 1; + if v.address == 0 || v.size == 0 { + continue; + } + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { + continue; + }; + shadow.refresh(list, v.address, u64::from(v.size)); + *view = D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: shadow.gpu(v.address), + SizeInBytes: v.size, + StrideInBytes: v.stride, + }; + } + // SAFETY: an open list; the views name live host buffers. + unsafe { + if count > 0 { + l.IASetVertexBuffers(0, Some(&views[..count])); + } + } + if indexed { + let v = self.index; + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { + return false; + }; + shadow.refresh(list, v.address, u64::from(v.size)); + let view = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: shadow.gpu(v.address), + SizeInBytes: v.size, + Format: DXGI_FORMAT(v.format as i32), + }; + // SAFETY: an open list; the view names a live host buffer. + unsafe { l.IASetIndexBuffer(Some(&view)) }; + } + const RENDER_TARGET: u32 = 0x4; + for &t in &self.targets { + crate::list::ensure_state(list, t as This, RENDER_TARGET); + } + if self.depth != 0 { + // A depth texture shaders also write: what they wrote, first. + list.twin_use(self.depth as This, false, true); + // A view that writes neither plane keeps the texture readable: + // the depth read state, together with the shader read states + // if this draw's shaders read the same texture (the write state + // 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 + /// it changed, constant data copied, textures made readable. + /// 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 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; + // Heaps first: a root signature with directly indexed heaps must be + // set after them. + if self.host_heaps != self.heaps { + let heaps: Vec<Option<ID3D12DescriptorHeap>> = self + .heaps + .iter() + .filter(|&&h| h != 0) + .filter_map(|&h| crate::descriptor::heap(h as This).host()) + .map(|h| Some(h.heap.clone())) + .collect(); + heaps.iter().flatten().for_each(|h| list.keep(h)); + // SAFETY: an open list and shader-visible heaps. + unsafe { l.SetDescriptorHeaps(&heaps) }; + self.host_heaps = self.heaps; + self.host_roots = [0; 2]; + } + // 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 compute { + l.SetComputeRootSignature(&p.root); + } else { + l.SetGraphicsRootSignature(&p.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 != p.pso.as_raw() as usize { + // SAFETY: an open list and a live pipeline. + unsafe { l.SetPipelineState(&p.pso) }; + self.host_pipeline = p.pso.as_raw() as usize; + list.used_pipeline(&p.name); + // The title may release the pipeline before it submits the list. + list.keep(&p.pso); + list.keep(&p.root); + } + for stage in &p.stages { + let t = stage.translated(); + 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 + }; + if let Some((param, dwords)) = stage.user_data { + 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 => self.user_value(compute, u.slot, u.root, u.dword), + }; + } + // SAFETY: an open list; `values` covers the parameter. + unsafe { + if compute { + l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } else { + l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } + } + } + for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { + for &(slot, param) in views { + 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; + } + 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; + }; + // 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 (compute, srv) { + (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), + (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), + (true, false) => l.SetComputeRootConstantBufferView(param, gpu), + (true, true) => l.SetComputeRootShaderResourceView(param, gpu), + } + } + } + } + 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 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, + address: Option<u64>, + param: u32, + compute: bool, + writes: bool, + ) -> bool { + const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0; + static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_UAV_MB") + .ok() + .and_then(|v| v.parse::<u64>().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 ready = |a: u64, s: &std::sync::Arc<crate::shadow::Shadow>| { + let len = s.left(a).min(limit); + s.refresh(list, a, len); + if writes { + s.gpu_writes(list, a, len); + } + }; + 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 compute { + list.list.SetComputeRootUnorderedAccessView(param, gpu); + } else { + list.list.SetGraphicsRootUnorderedAccessView(param, gpu); + } + } + return true; + } + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + 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 => { + 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 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); + } + } + true + } + + /// 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, + address: Option<u64>, + param: u32, + compute: bool, + biased: bool, + ) -> bool { + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + 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; + }; + // 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) + } + }; + // 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); + } + } + true + } + + /// 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<u64> { + 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<u32, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)>; + static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> = + 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 + }; + *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<String> = 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<usize, (std::sync::Arc<crate::shadow::Shadow>, 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<Option<std::collections::HashMap<usize, u64>>> = 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<u64> = 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" + ); + } + Some(gpu) + } + + /// 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<bool> = 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. + const PER_FRAME: u64 = 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); + } + // 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. + const SPAN: std::time::Duration = std::time::Duration::from_millis(250); + let began = std::time::Instant::now(); + for (index, write) in due { + if SPENT.load(Ordering::Relaxed) >= PER_FRAME || 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.) + 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. + if !room { + refused += 1; + if refused > 256 { + break; + } + continue; + } + 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.) + 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); + host.texture_slot_done(index, write, again); + } + } + + /// 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), + "a dispatch without a host pipeline dropped" + ); + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + crate::pipeline::note_drop(self.pipeline as This); + self.list_dropped_roots([x, y, z]); + } + return; + }; + if !p.compute { + once!("a dispatch with a graphics pipeline"); + return; + } + 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)); + // 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 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; + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return kind; + }; + let mut text = format!("{kind} {}", p.name); + // 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<String> = 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): Grand Theft Auto VI 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 { + 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).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))); + let _ = write!(text, " root{slot}={address:#x} host {host:#x?}"); + } + } + } + let _ = write!(text, " tables {:?}", self.reads(compute)); + text + } + + /// 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); + let ran = mesh_test() != 1 + && mesh_kept(self.pipeline) + && self.prepare_for(list, false, true) + && match list.list.cast::<ID3D12GraphicsCommandList6>() { + Ok(l6) => { + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("mesh {x}"), false)); + 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 + } + Err(_) => false, + }; + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + } + + fn roots_ref(&self, compute: bool) -> &Vec<Root> { + if compute { + &self.compute + } else { + &self.graphics + } + } + + fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) { + let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { + return; + }; + let handle = table + u64::from(u.table_offset_dwords) * 4; + let Some(heap) = self.heap_of(handle) else { + return; + }; + let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else { + return; + }; + if let Some(view) = host.mirror(index, handle, true) { + 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); + } + } + } + + /// The descriptors a shader reads through tables. Tables holding a + /// constant buffer are made afresh for the draw in dynamic slots, with + /// the constant data copied to upload memory when the list is + /// submitted: the host wants constant buffers 256-byte aligned, the + /// console only 16. Returns those tables' new byte offsets by root + /// 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. + pub(crate) fn tables( + &mut self, + list: &HostList, + used: &[UsedResource], + indexed: &[RootIndexedView], + compute: bool, + ) -> Vec<(u8, u32)> { + let tables = |u: &&UsedResource| u.root == RootType::Table; + let mut fresh: Vec<u8> = used + .iter() + .filter(tables) + .filter(|u| u.kind == ResourceType::Cbv) + .map(|u| u.slot) + .collect(); + // Tables reaching past a host heap smaller than the title's (the + // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the + // title's slots there have no host slot of their own. + for u in used.iter().filter(tables) { + if fresh.contains(&u.slot) { + continue; + } + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { + continue; + }; + let end = table + u64::from(u.table_offset_dwords) * 4; + let Some(heap) = self.heap_of(table) else { + continue; + }; + let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { + continue; + }; + if index >= host.count() { + fresh.push(u.slot); + } + } + fresh.sort_unstable(); + fresh.dedup(); + for u in used.iter().filter(tables) { + if !fresh.contains(&u.slot) { + self.table_entry(list, u, compute); + } + } + let mut made = Vec::new(); + for slot in fresh { + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { + continue; + }; + let entries: Vec<&UsedResource> = used + .iter() + .filter(tables) + .filter(|u| u.slot == slot) + .collect(); + 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<u32> = 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) + .chain(selected.last().copied()) + .max() + .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}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for k in 0..n { + let at = table + u64::from(k) * 32; + // SAFETY: a descriptor slot in title memory. + unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); + } + (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.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 { + // 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((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 { + let index = first + k; + let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); + match crate::descriptor::view(table + u64::from(k) * 32) { + Some(View::Constant(address, size)) => { + let Some((gpu, to)) = list.scratch(u64::from(size)) else { + host.make_null(index); + continue; + }; + list.defer_fill(to, address as *const u8, size as usize); + host.constant_at(index, gpu, size); + } + Some(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) + { + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror(title + k, table + u64::from(k) * 32, true); + } + } + } + None => { + host.make_null(index); + if used.is_some() { + once!(slot, "a table entry without a view"); + } + } + } + } + made.push((slot, first * 32)); + } + made + } + + /// The first draws, at debug level: what they bind and read + /// (diagnostics builds). + #[cfg(feature = "diagnostics")] + fn trace(&self, kind: &str, count: u32, first: u32) { + static TRACED: AtomicU64 = AtomicU64::new(0); + if !tracing::enabled!(tracing::Level::DEBUG) { + return; + } + let listed = crate::capture::listed(crate::queue::presented() + 1); + let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64; + let targets: Vec<String> = self + .targets + .iter() + .filter_map(|&t| crate::resource::host_made(t as This)) + .map(|t| { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + format!("{}x{} f{}", d.Width, d.Height, d.Format.0) + }) + .collect(); + let v = self.vertex[0]; + let line = format!( + "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}", + self.topology, + self.pipeline, + v.address, + v.size, + v.stride, + self.reads(false) + ); + if logged { + tracing::debug!("draw {line}"); + } + let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner()); + if frame.len() < 256 { + frame.push(line); + } + } + + /// What a draw's shaders read, one line per used resource (diagnostics + /// builds). + #[cfg(feature = "diagnostics")] + fn reads(&self, compute: bool) -> Vec<String> { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return vec!["no host pipeline".into()]; + }; + let mut out = Vec::new(); + for stage in &p.stages { + let t = stage.translated(); + for u in &t.used { + let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) { + (RootType::Table, Some(Root::Table(table))) => { + let handle = table + u64::from(u.table_offset_dwords) * 4; + describe(crate::descriptor::view(handle).as_ref()) + } + (root, _) => format!("{root:?}"), + }; + out.push(format!( + "{} {:?} s{}+{}: {what}", + stage.shader.hash, u.kind, u.slot, u.table_offset_dwords + )); + } + } + out + } + + pub(crate) fn draw( + &mut self, + list: &HostList, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, + ) { + self.window = None; + #[cfg(feature = "diagnostics")] + self.trace("draw", 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 { + (vertices / 3 * 6, 0) + } else { + (vertices, first) + }; + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawInstanced(count, instances, from, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + } + + /// 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 { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return false; + }; + let rects = u64::from(count / 3); + for slot in 0..32 { + let elements: Vec<(u32, u32)> = p + .inputs + .iter() + .filter(|e| e.slot == slot && !e.per_instance) + .map(|e| (e.offset, e.format)) + .collect(); + if elements.is_empty() { + continue; + } + let v = self.vertex[slot as usize]; + let stride = u64::from(v.stride); + let from = v.address + u64::from(first) * stride; + if v.address == 0 + || stride == 0 + || u64::from(first + count) * stride > u64::from(v.size) + || crate::shadow::find(from, rects * 3 * stride).is_none() + { + once!(slot, "rectangle vertices outside their buffer"); + return false; + } + let Some((gpu, to)) = list.scratch(rects * 6 * stride) else { + return false; + }; + 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 { + ( + std::slice::from_raw_parts(from as *const u8, n * 3 * stride), + std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride), + ) + }; + crate::primitive::expand_rects(src, dst, stride, &elements); + }); + let view = D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: gpu, + SizeInBytes: (rects * 6 * stride as u64) as u32, + StrideInBytes: v.stride, + }; + // SAFETY: an open list; the view names live scratch memory. + unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) }; + } + true + } + + pub(crate) fn draw_indexed( + &mut self, + list: &HostList, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, + ) { + self.window = None; + #[cfg(feature = "diagnostics")] + self.trace("indexed", indices, first); + // 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 = !lost && self.prepare(list, true); + if ran { + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawIndexedInstanced(indices, instances, first, base, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + } +} + +impl State { + /// Indirect execution of a one-argument signature of `kind` (PC + /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with + /// records `stride` bytes apart at title address `arguments`, and the + /// record count at `count` if the title gives one: the GPU reads them + /// from the buffer's host copy, where earlier dispatches may have + /// written them. False if it cannot run on the host. + pub(crate) fn execute_indirect( + &mut self, + list: &HostList, + (kind, stride, max): (u32, u32, u32), + arguments: u64, + count: Option<u64>, + ) -> bool { + // Skip before the argument clamp can mutate the indirect buffer. + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + 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; + const MESH: u32 = 10; + #[cfg(feature = "diagnostics")] + let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); + #[cfg(not(feature = "diagnostics"))] + let why = |_: &str| {}; + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); + return false; + }; + // Indirect rectangles (Grand Theft Auto VI'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_any(arguments, len) else { + why("arguments outside title buffers"); + return false; + }; + let counter = match count { + Some(at) => match crate::shadow::find_any(at, 4) { + Some(s) => Some((s, at)), + None => { + why("count outside title buffers"); + return false; + } + }, + None => None, + }; + let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) + .then(|| host_signature(kind, stride)) + .flatten() + else { + why("no host signature"); + return false; + }; + if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { + why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); + return false; + } + // 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.prepare(list, kind == INDEXED), + MESH => self.prepare_for(list, false, true), + DISPATCH => self.bind(list, p, true), + _ => false, + }; + if !ran { + 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) + }); + 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, + &bounded, + at, + counter.as_ref().map(|(s, _)| &s.buffer), + counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), + ) + }; + if kind == MESH { + self.mesh_scissor(list, false); + } + crate::indirect::done(list, &bounded); + if kind == DISPATCH { + DISPATCHED.fetch_add(1, Ordering::Relaxed); + } else { + DRAWN.fetch_add(1, Ordering::Relaxed); + } + true + } +} + +/// The host command signature for one argument of `kind` with records +/// `stride` bytes apart (no root arguments, so no root signature), made +/// once. +fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> { + static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> = + std::sync::Mutex::new(Vec::new()); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) { + return Some(s.clone()); + } + let argument = 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: &argument, + NodeMask: 0, + }; + let mut signature: Option<ID3D12CommandSignature> = None; + // SAFETY: a description of one argument; no root arguments. + let result = unsafe { + crate::host::host()?.device.CreateCommandSignature( + &desc, + None::<&ID3D12RootSignature>, + &mut signature, + ) + }; + if let Err(e) = result { + once!(error = %e, kind, stride, "host command signature refused"); + return None; + } + let signature = signature?; + made.push(((kind, stride), signature.clone())); + Some(signature) +} + +/// Gets what a shader reads or writes through a view ready: buffer data +/// copied, textures moved to the state they need. +fn view_kind(view: &View) -> Option<ResourceType> { + 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. + if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) { + shadow.refresh(list, address, len); + if kind == ResourceType::Uav { + // A shader that cannot store to buffers leaves the range as + // the title has it: nothing to find afterwards. + if STORES.get() || !write_skip() { + 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, kind) { + (View::Shader(resource, _), ResourceType::Srv) => { + // A view the title placed, in another format, in the memory of + // a texture the host writes: that texture's texels, copied on + // the host (title memory does not have them). + let aliased = crate::resource::alias_of(*resource as This) + .is_some_and(|source| crate::texture::alias(list, *resource as This, source)); + if !aliased + && let Some(t) = crate::resource::host_resource(*resource as This) + && crate::texture::title_written(t) + { + crate::texture::upload(list, *resource as This, t); + } + // 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. + let d = unsafe { t.GetDesc() }; + if d.Flags.0 & 7 == 0 { + tracing::debug!( + resource = format_args!("{resource:#x}"), + ?d, + "a shader reads a texture the title fills" + ); + } + } + } + (View::Unordered(resource, _, _), ResourceType::Uav) => { + #[cfg(feature = "diagnostics")] + crate::capture::note_target(*resource as This); + // Unordered access to a depth texture is its colour twin's. + if !list.twin_use(*resource as This, true, true) { + crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + } + } + _ => {} + } +} + +/// A view in a few words (diagnostics builds). +#[cfg(feature = "diagnostics")] +fn describe(view: Option<&View>) -> String { + let texture = |r: This| { + crate::resource::host_made(r).map(|t| { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + 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))), + 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], + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[11], + u64::from(d[10]) | u64::from(d[11]) << 32 + ), + // The first four values, as a colour rectangle's constants are. + Some(View::Constant(address, size)) + if *size >= 16 && crate::texture::committed(*address as *const u8, 16) => + { + // SAFETY: 16 committed bytes of title memory. + let v = unsafe { (*address as *const [f32; 4]).read_unaligned() }; + format!("Constant({address:#x}, {size}) {v:?}") + } + Some(v) => format!("{v:?}").chars().take(60).collect(), + } +} + +/// The console's own primitive topologies. +const TRIANGLE_FAN: u32 = 6; +const RECTANGLES: u32 = 17; +const LINE_LOOP: u32 = 18; +const QUADS: u32 = 19; +const QUAD_STRIP: u32 = 20; + +/// Fixed-function state, straight onto the host list. +pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) { + // SAFETY: an open list. + unsafe { list.list.RSSetViewports(viewports) }; +} + +pub(crate) fn scissors(list: &HostList, rects: &[RECT]) { + // SAFETY: an open list. + unsafe { list.list.RSSetScissorRects(rects) }; +} + +pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { + // SAFETY: an open list. + unsafe { list.list.OMSetBlendFactor(factor) }; +} + +pub(crate) fn stencil_ref(list: &HostList, reference: u32) { + #[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) }; +} diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs new file mode 100644 index 000000000..58640ac40 --- /dev/null +++ b/crates/victory-gpu/src/dxgi.rs @@ -0,0 +1,341 @@ +//! The DXGI side of the device: one adapter with one output, reached from +//! the device by interface query. Tables follow the PC interfaces' order +//! (IUnknown, the object methods, then each interface's methods). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{ + self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, MORE_DATA, NOT_FOUND, OUTPUT, + Object, S_OK, Table, This, guid, +}; + +/// The DXGI device interfaces, base first (as on PC). +pub(crate) const DEVICE_IIDS: [Iid; 3] = [ + guid( + 0x54ec77fa, + 0x1377, + 0x44e6, + [0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c], + ), + guid( + 0x77db970f, + 0x6276, + 0x48ba, + [0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c], + ), + guid( + 0x05008617, + 0xfbfd, + 0x4051, + [0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, 0xa9], + ), +]; +const ADAPTER_IIDS: [Iid; 3] = [ + guid( + 0x2411e7e1, + 0x12ac, + 0x4ccf, + [0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0], + ), + guid( + 0x29038f61, + 0x3839, + 0x4626, + [0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05], + ), + guid( + 0x0aa1ae0a, + 0xfa0e, + 0x4b84, + [0x86, 0x44, 0xe0, 0x5f, 0xf8, 0xe5, 0xac, 0xb5], + ), +]; +const FACTORY_IIDS: [Iid; 3] = [ + guid( + 0x7b7166ec, + 0x21c7, + 0x44ae, + [0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69], + ), + guid( + 0x770aae78, + 0xf26f, + 0x4dba, + [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87], + ), + guid( + 0x50c83a1c, + 0xe072, + 0x4c48, + [0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0], + ), +]; +const OUTPUT_IIDS: [Iid; 1] = [guid( + 0xae02eedb, + 0xc735, + 0x4690, + [0x8d, 0x52, 0x5a, 0x8d, 0xc2, 0x02, 0x13, 0xaa], +)]; + +static DEVICE: Object = Object::new(&DEVICE_FUNCTIONS); +static ADAPTER_OBJECT: Object = Object::new(&ADAPTER_FUNCTIONS); +static FACTORY_OBJECT: Object = Object::new(&FACTORY_FUNCTIONS); +static OUTPUT_OBJECT: Object = Object::new(&OUTPUT_FUNCTIONS); + +pub(crate) fn device() -> This { + &DEVICE +} + +/// `found` if `iid` is one of `known`. +fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut This) -> HRESULT { + object::answer(kind, iid, object::is(iid, known).then_some(found), out) +} + +/// The DXGI device also answers for the D3D12 device. +extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + if crate::device::is_device(iid) { + return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out); + } + query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out) +} +extern "system" fn device_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(DXGI_DEVICE, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out) +} +extern "system" fn device_adapter(_: This, out: *mut This) -> HRESULT { + object::answer(DXGI_DEVICE, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out) +} + +extern "system" fn adapter_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(ADAPTER, iid, &ADAPTER_IIDS, this, out) +} +extern "system" fn adapter_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(ADAPTER, iid, &FACTORY_IIDS, &FACTORY_OBJECT, out) +} +extern "system" fn adapter_outputs(_: This, index: u32, out: *mut This) -> HRESULT { + if index != 0 { + return NOT_FOUND; + } + object::answer(ADAPTER, &OUTPUT_IIDS[0], Some(&OUTPUT_OBJECT), out) +} + +#[repr(C)] +struct AdapterDescription { + name: [u16; 128], + vendor: u32, + device: u32, + subsystem: u32, + revision: u32, + dedicated_video_memory: usize, + dedicated_system_memory: usize, + shared_system_memory: usize, + luid: [u32; 2], +} +const _: () = assert!(size_of::<AdapterDescription>() == 0x130); + +const AMD: u32 = 0x1002; + +extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let mut name = [0; 128]; + for (slot, unit) in name.iter_mut().zip("VIctory console GPU".encode_utf16()) { + *slot = unit; + } + // shortcut: memory sizes are the title's split (GPU-optimal, standard), + // not measured; revisit once memory is emulated. + let (gpu_optimal, standard) = crate::console::current().title_memory(); + let description = AdapterDescription { + name, + vendor: AMD, + device: 0, + subsystem: 0, + revision: 0, + dedicated_video_memory: gpu_optimal, + dedicated_system_memory: 0, + shared_system_memory: standard, + luid: [1, 0], + }; + // SAFETY: checked non-null; the title passes room for the description. + unsafe { out.write(description) }; + S_OK +} + +extern "system" fn factory_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(FACTORY, iid, &FACTORY_IIDS, this, out) +} +extern "system" fn factory_adapters(_: This, index: u32, out: *mut This) -> HRESULT { + if index != 0 { + return NOT_FOUND; + } + object::answer(FACTORY, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out) +} + +extern "system" fn output_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(OUTPUT, iid, &OUTPUT_IIDS, this, out) +} +extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(OUTPUT, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out) +} + +/// IUnknown 3, object 4, device 5 + 2 + 3. +static DEVICE_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::<DXGI_DEVICE, 32>(); + f[0] = device_query as *const (); + f[6] = device_parent as *const (); // 0x30 + f[7] = device_adapter as *const (); // 0x38 + Table(f) +}; + +/// IUnknown 3, object 4, adapter 3 + 1 + 1. +static ADAPTER_FUNCTIONS: Table<24> = { + let mut f = object::missing_table::<ADAPTER, 24>(); + f[0] = adapter_query as *const (); + f[6] = adapter_parent as *const (); // 0x30 + f[7] = adapter_outputs as *const (); // 0x38 + f[8] = adapter_description as *const (); // 0x40 + Table(f) +}; + +/// IUnknown 3, object 4, factory 5 + 2 + 11. +static FACTORY_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::<FACTORY, 32>(); + f[0] = factory_query as *const (); + f[7] = factory_adapters as *const (); // 0x38 + f[12] = factory_adapters as *const (); // 0x60, the same for version 1 + Table(f) +}; + +/// A display mode as the console lists it: size, refresh rate (numerator, +/// denominator), format, scanline order, scaling, flags. +#[repr(C)] +struct Mode { + width: u32, + height: u32, + refresh: [u32; 2], + format: u32, + scanlines: u32, + scaling: u32, + flags: u32, +} +const _: () = assert!(size_of::<Mode>() == 32); + +/// 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::<u32>().ok()?, h.trim().parse::<u32>().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 (Grand Theft Auto VI 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. +extern "system" fn modes( + _: This, + _format: u32, + _flags: u32, + count: *mut u32, + out: *mut Mode, +) -> HRESULT { + // SAFETY: the title passes its count (null is tolerated). + let Some(count) = (unsafe { count.as_mut() }) else { + return E_INVALIDARG; + }; + if out.is_null() { + *count = 1; + return S_OK; + } + if *count < 1 { + return MORE_DATA; + } + *count = 1; + let (width, height) = display_size(); + let mode = Mode { + width, + height, + refresh: [60, 1], + format: 0, + scanlines: 1, // progressive + scaling: 0, + flags: 0, + }; + // SAFETY: checked non-null; room for `count` >= 1 modes. + unsafe { out.write(mode) }; + S_OK +} + +/// IUnknown 3, object 4, output 15 (12 as on PC, then 3 console ones). +static OUTPUT_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::<OUTPUT, 32>(); + f[0] = output_query as *const (); + f[6] = output_parent as *const (); // 0x30 + f[21] = modes as *const (); // 0xa8 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{E_NOINTERFACE, slot}; + + type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + type Get = extern "system" fn(This, *mut This) -> HRESULT; + type Indexed = extern "system" fn(This, u32, *mut This) -> HRESULT; + type Describe = extern "system" fn(This, *mut AdapterDescription) -> HRESULT; + + /// Minecraft's startup: device → DXGI device (newest first) → adapter → + /// description, factory, first output. + #[test] + fn startup_walks_from_device_to_output() { + let d3d = crate::device::device(); + let newest_pc = guid( + 0x6007896c, + 0x3244, + 0x4afd, + [0xbf, 0x18, 0xa6, 0xd3, 0xbe, 0xda, 0x50, 0x23], + ); + let mut dxgi = std::ptr::null(); + let qi = slot::<Query>(d3d, 0); + assert_eq!(qi(d3d, &newest_pc, &mut dxgi), E_NOINTERFACE); + assert!(dxgi.is_null()); + assert_eq!(qi(d3d, &DEVICE_IIDS[2], &mut dxgi), S_OK); + assert_eq!(dxgi, device()); + + let mut adapter = std::ptr::null(); + assert_eq!(slot::<Get>(dxgi, 0x38)(dxgi, &mut adapter), S_OK); + let mut description = std::mem::MaybeUninit::<AdapterDescription>::uninit(); + assert_eq!( + slot::<Describe>(adapter, 0x40)(adapter, description.as_mut_ptr()), + S_OK + ); + // SAFETY: written above. + assert_eq!(unsafe { description.assume_init() }.vendor, AMD); + + let mut factory = std::ptr::null(); + let parent = slot::<Query>(adapter, 0x30); + assert_eq!(parent(adapter, &FACTORY_IIDS[2], &mut factory), S_OK); + let mut again = std::ptr::null(); + assert_eq!(slot::<Indexed>(factory, 0x38)(factory, 0, &mut again), S_OK); + assert_eq!(again, adapter); + + let mut output = std::ptr::null(); + let outputs = slot::<Indexed>(adapter, 0x38); + assert_eq!(outputs(adapter, 0, &mut output), S_OK); + assert!(!output.is_null()); + assert_eq!(outputs(adapter, 1, &mut output), NOT_FOUND); + } +} diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs new file mode 100644 index 000000000..771246118 --- /dev/null +++ b/crates/victory-gpu/src/fence.rs @@ -0,0 +1,193 @@ +//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a +//! GPU yet, so only signals (the title's, later our queues') move one. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +pub(crate) const FENCE_IIDS: [Iid; 4] = [ + guid( + 0x0a753dcf, + 0xc4d8, + 0x4b91, + [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +struct Fence { + object: Object, + /// Titles also read it straight from memory, at the fence's GPU + /// address. + value: AtomicU64, + flags: u32, + /// Events to set once the value reaches theirs (handles as integers). + waiters: Mutex<Vec<(u64, usize)>>, +} + +fn fence<'a>(this: This) -> &'a Fence { + // SAFETY: called from fence methods only. + unsafe { &*this.cast::<Fence>() } +} + +pub(crate) extern "system" fn create( + _: This, + initial: u64, + flags: u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + tracing::debug!(initial, flags, "fence"); + let fence = Box::new(Fence { + object: Object::new(&FUNCTIONS), + value: AtomicU64::new(initial), + flags, + waiters: Mutex::new(Vec::new()), + }); + object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out) +} + +fn set_event(event: usize) { + #[cfg(windows)] + // SAFETY: the title passed an event handle. + unsafe { + windows_sys::Win32::System::Threading::SetEvent(event as *mut c_void) + }; + #[cfg(not(windows))] + let _ = event; +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + FENCE, + iid, + object::is(iid, &FENCE_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::<Fence>(this) +} +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 { + let fence = fence(this); + let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); + if fence.value.load(Ordering::Acquire) >= value { + if !event.is_null() { + set_event(event as usize); + } + 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"); + return E_NOTIMPL; + } + waiters.push((value, event as usize)); + S_OK +} +/// 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); + waiters.retain(|&(wanted, event)| { + let reached = wanted <= value; + if reached { + set_event(event); + } + !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 +} + +extern "system" fn creation_flags(this: This) -> u32 { + fence(this).flags +} +/// Where the value lives (GPU addresses are CPU addresses). +extern "system" fn gpu_address(this: This) -> u64 { + (&raw const fence(this).value) as u64 +} + +/// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console +/// one among them). +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<FENCE, 24>()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = completed as *const (); // 0x40 + f[9] = set_event_on_completion as *const (); // 0x48 + f[10] = signal as *const (); // 0x50 + f[11] = creation_flags as *const (); // 0x58 + f[12] = gpu_address as *const (); // 0x60 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + #[cfg(windows)] + #[test] + fn signals_set_waiting_events() { + use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + let mut f = std::ptr::null(); + assert_eq!(create(std::ptr::null(), 1, 0, &FENCE_IIDS[0], &mut f), S_OK); + assert_eq!(slot::<extern "system" fn(This) -> u64>(f, 0x40)(f), 1); + // SAFETY: plain auto-reset event. + let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + assert!(!event.is_null()); + let wait = slot::<extern "system" fn(This, u64, *mut c_void) -> HRESULT>(f, 0x48); + let signal = slot::<extern "system" fn(This, u64) -> HRESULT>(f, 0x50); + assert_eq!(wait(f, 5, event), S_OK); + // SAFETY: a valid event. + assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(signal(f, 5), S_OK); + // SAFETY: as above. + assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(wait(f, 5, event), S_OK, "already reached"); + // 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. + let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f); + // SAFETY: the fence's value. + assert_eq!(unsafe { *(at as *const u64) }, 5); + // SAFETY: ours. + unsafe { CloseHandle(event) }; + assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0); + } +} diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs new file mode 100644 index 000000000..0b591d9a8 --- /dev/null +++ b/crates/victory-gpu/src/frame.rs @@ -0,0 +1,246 @@ +//! Frame pacing: the title sets a frame interval and waits for each frame +//! 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 +//! with "token on time-out" (starting its next frame at once) and is paced +//! by a blocking wait for the flip before each present. +//! +//! shortcut: event offsets are ignored (every event is at the tick); tie +//! the clock to presentation if a title paces by them. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use crate::object::{HRESULT, S_FALSE, S_OK, This}; + +/// What a wait returns when its time is up first. +const TIMEOUT: HRESULT = S_FALSE; +/// The frame-origin event: the one that starts frames and makes tokens. +const ORIGIN: u32 = 0; +/// Make the frame's token even if the wait times out (the title starts the +/// frame early). +const TOKEN_ON_TIMEOUT: u32 = 2; +const SIXTIETH: Duration = Duration::from_micros(16_667); + +struct Clock { + start: Instant, + interval: Duration, + /// The tick number at `start` (ticks go on across interval changes). + first: u64, +} + +static CLOCK: Mutex<Option<Clock>> = Mutex::new(None); +static FRAME: AtomicU64 = AtomicU64::new(0); + +fn clock() -> std::sync::MutexGuard<'static, Option<Clock>> { + CLOCK.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Device method: a frame every `length` microseconds. The period is how +/// many intervals a frame may take to reach the display (pipeline depth), +/// not part of the rate. +pub(crate) extern "system" fn set_interval( + _: This, + _output: This, + length: u32, + _period: u32, + _flags: u32, +) -> HRESULT { + let interval = match length { + 0 => SIXTIETH, + us => Duration::from_micros(u64::from(us)), + }; + tracing::info!(?interval, "frame interval"); + // A new interval starts from now, after the last tick handed out. + let first = LAST + .iter() + .map(|t| t.load(Ordering::Relaxed)) + .max() + .unwrap_or(0); + *clock() = Some(Clock { + start: Instant::now(), + interval, + first, + }); + S_OK +} + +/// Device method: events are scheduled at every tick. +pub(crate) extern "system" fn schedule( + _: This, + _kind: u32, + _offset: u32, + _list: *const u8, + _flags: u32, +) -> HRESULT { + S_OK +} + +/// Frames begun so far (frame waits that ended). +pub(crate) fn current() -> u64 { + FRAME.load(Ordering::Relaxed) +} + +/// Per event kind (origin, vblank, flip and later kinds): the last tick a +/// wait for it ended on. +static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +fn last(kind: u32) -> &'static AtomicU64 { + &LAST[(kind as usize).min(LAST.len() - 1)] +} + +/// The next tick after now and after the last one a wait for `kind` ended +/// on (an event happens once per tick: a wait woken a little early must not +/// let the next one end on the same tick), and how long until it. +fn next_tick(kind: u32) -> (u64, Duration) { + let mut clock = clock(); + let c = clock.get_or_insert_with(|| Clock { + start: Instant::now(), + interval: SIXTIETH, + first: 0, + }); + let elapsed = c.start.elapsed().as_nanos(); + let interval = c.interval.as_nanos().max(1); + let tick = + (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); + let at = u128::from(tick - c.first) * interval; + ( + tick, + Duration::from_nanos(at.saturating_sub(elapsed) as u64), + ) +} + +/// Device method: blocks until the next tick (or the time-out); an origin +/// wait then hands out the new frame's token. Other events keep the token +/// the title passes. Ticks are absolute (start plus whole intervals), so +/// lateness never accumulates. +pub(crate) extern "system" fn wait( + _: This, + kind: u32, + timeout_ms: u32, + _list: *const u8, + flags: u32, + token: *mut u64, +) -> HRESULT { + let origin = kind == ORIGIN; + 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<bool> = 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 + } else { + std::thread::sleep(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. + let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1; + if !token.is_null() { + // SAFETY: checked non-null; the title passes its token. + unsafe { token.write(frame) }; + } + } + #[cfg(feature = "diagnostics")] + tracing::debug!( + kind, + timeout_ms, + flags, + hr, + tick, + wait_us = wait.as_micros() as u64, + frame = current(), + "frame wait" + ); + hr +} + +/// Device method: no statistics are kept, so none are returned. +pub(crate) extern "system" fn statistics( + _: This, + _token: u64, + _kinds: u32, + count: *mut u32, + _out: *mut u8, +) -> HRESULT { + if !count.is_null() { + // SAFETY: checked non-null. + unsafe { count.write(0) }; + } + S_OK +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waits_end_on_ticks_and_count_frames() { + let null = std::ptr::null(); + assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK); + let mut first = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK); + let before = Instant::now(); + let mut second = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); + assert!(second > first); + assert!(before.elapsed() <= Duration::from_millis(50)); + assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); + // Tokens count frames, a frame started early on a time-out too. + let mut early = 0; + let flags = TOKEN_ON_TIMEOUT; + assert_eq!( + wait(null, 0, 0, std::ptr::null(), flags, &mut early), + TIMEOUT + ); + let mut next = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK); + assert!(early == second + 1 && next == early + 1); + assert!(LAST[0].load(Ordering::Relaxed) >= 2); + + // The title's loop (the clock is global, so in the same test): an + // origin poll that times out (and starts the frame), then a + // blocking flip wait. Each flip takes its own tick. + const FLIP: u32 = 2; + assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + let mut token = 0; + let flips: Vec<u64> = (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect(); + assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); + // Even when a flip wait begins on the tick another just ended on. + let (tick, _) = next_tick(FLIP); + assert!(tick > flips[3]); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs new file mode 100644 index 000000000..113f38aea --- /dev/null +++ b/crates/victory-gpu/src/host.rs @@ -0,0 +1,6683 @@ +//! 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 +//! (unless `VICTORY_LATE_WAIT=1`, see [`late`]); +//! overlap them with per-submission fences once more than clears run. + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::Win32::UI::WindowsAndMessaging::*; +use windows::core::{Interface, PCWSTR, w}; + +/// Resource states without the console's own bits (compression hints from +/// bit 25 up), which the host rejects. +pub(crate) fn pc_state(state: u32) -> u32 { + state & 0x01ff_ffff +} + +/// A console state as a host texture state: PC bits only, and none of the +/// buffer-only ones the console allows on textures (vertex, constant and +/// index buffer, stream out, indirect arguments, as in "generic read"). +pub(crate) fn texture_state(state: u32) -> u32 { + const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200; + pc_state(state) & !BUFFER_ONLY +} + +/// Render target views live only until their command is recorded, so a +/// ring of host descriptors is enough. +const RTV_RING: u32 = 1024; + +pub(crate) struct Host { + pub(crate) device: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + /// The last value signalled on `fence`, behind the submission lock. + submitted: Mutex<u64>, + event: HANDLE, + rtvs: ID3D12DescriptorHeap, + rtv_size: u32, + /// A ring of depth views, used as `rtvs`. + dsvs: ID3D12DescriptorHeap, + dsv_size: u32, + next_dsv: AtomicU32, + /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug + /// layer's messages. + messages: Option<ID3D12InfoQueue>, + next_rtv: AtomicU32, + presenter: Mutex<Option<Presenter>>, + /// The adapter the device is on, for its memory budget + /// ([`Host::video_memory`]); `None` if the system does not name it. + adapter: Option<IDXGIAdapter3>, +} + +// SAFETY: D3D12 devices, queues, fences and descriptor heaps are +// free-threaded; the event handle is only waited on under `submitted`. +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<Vec<(u64, Retired)>> = 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<dyn std::any::Any>); +// 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<std::time::Instant> = 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 +} + +/// 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<bool> = 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<T: 'static>(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<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new()); +/// The entries kept. +const TRAIL_MOST: usize = 96; + +fn trail_on() -> bool { + static ON: OnceLock<bool> = 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<std::time::Instant> = 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)]; + +/// 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)]; + +/// 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. +pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + 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::<PROCESS_MEMORY_COUNTERS>() 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. +static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new(); + +/// Sets what a host GPU failure does (the runtime's crash report). +pub fn on_failure(report: fn(&str) -> !) { + let _ = ON_FAILURE.set(report); +} + +/// Ends the run on a host GPU failure: what failed, the removal reason and +/// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a +/// diagnostics build names the command). +pub(crate) fn fail(what: std::fmt::Arguments) -> ! { + let mut text = what.to_string(); + if let Some(host) = host() { + // SAFETY: a plain query. + if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { + text.push_str(&format!("; device removed: {e}")); + 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 => {} + } + } + 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(), + } +} + +/// The host GPU, created on first use; `None` without one (a run then +/// behaves as before: nothing executes). +pub(crate) fn host() -> Option<&'static Host> { + static HOST: OnceLock<Option<Host>> = OnceLock::new(); + HOST.get_or_init(|| match create() { + Ok(host) => Some(host), + Err(e) => { + tracing::warn!(error = %e, "no host D3D12 device; command lists will not run"); + None + } + }) + .as_ref() +} + +fn create() -> windows::core::Result<Host> { + // SAFETY: plain D3D12 object creation with valid descriptions. + unsafe { + // The debug layer only in builds with diagnostics. + let debug = + cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); + if debug { + let mut layer: Option<ID3D12Debug> = None; + match D3D12GetDebugInterface(&mut layer) { + Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), + Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"), + } + // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range + // descriptor heap indices and the like become messages naming + // the command instead of page faults. Without state tracking + // (directly indexed textures are not transitioned). + if std::env::var_os("VICTORY_D3D12_GBV").is_some() + && let Some(l) = &layer + { + if let Ok(d1) = l.cast::<ID3D12Debug1>() { + d1.SetEnableGPUBasedValidation(true); + } + if let Ok(d2) = l.cast::<ID3D12Debug2>() { + d2.SetGPUBasedValidationFlags( + D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING, + ); + } + tracing::info!("GPU-based validation on"); + } + } + // Diagnostics: device-removed data (the command that faulted, the + // faulting address), read when the device is removed. + if dred_on() { + let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None; + if D3D12GetDebugInterface(&mut dred).is_ok() + && let Some(dred) = dred + { + dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } + } + let mut device: Option<ID3D12Device> = None; + // Diagnostics: the software adapter, on which a shader's wild access + // is an access violation in this process (a crash report with the + // address and instruction) instead of a GPU fault and driver reset. + if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { + let adapter = warp_adapter()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; + tracing::info!("host device on the software adapter (WARP)"); + } else { + let adapter = chosen_adapter()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; + } + let device = device.ok_or_else(windows::core::Error::empty)?; + // `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::<ID3D12Device6>() + { + 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::<ID3D12InfoQueue>().ok()) + .flatten(); + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let rtvs: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: RTV_RING, + ..Default::default() + })?; + let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + let dsvs: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: RTV_RING, + ..Default::default() + })?; + let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid())) + .ok(); + tracing::info!("host D3D12 device ready"); + Ok(Host { + device, + queue, + fence, + submitted: Mutex::new(0), + event, + rtvs, + rtv_size, + dsvs, + dsv_size, + next_dsv: AtomicU32::new(0), + messages, + next_rtv: AtomicU32::new(0), + presenter: Mutex::new(None), + adapter, + }) + } +} + +/// The adapter to render on. Two cards with the same name (two 3090 Tis) +/// are told apart by the PCIe link: the widest link wins, so the card on +/// an x1 link is not used just because DXGI lists it first. +/// `VICTORY_ADAPTER` still filters by a case-insensitive part of the name. +/// `VICTORY_ADAPTER_BUS` pins one PCI bus number. +fn chosen_adapter() -> windows::core::Result<IDXGIAdapter> { + let want = std::env::var("VICTORY_ADAPTER") + .ok() + .filter(|w| !w.is_empty()) + .map(|w| w.to_lowercase()); + let bus_pin = std::env::var("VICTORY_ADAPTER_BUS") + .ok() + .and_then(|v| v.trim().parse::<u32>().ok()); + // SAFETY: plain DXGI and display-driver queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let mut best: Option<(u32, usize, IDXGIAdapter1, String, u32)> = None; + let mut i = 0u32; + let mut saw_name = false; + while let Ok(adapter) = factory.EnumAdapters1(i) { + i += 1; + let desc = adapter.GetDesc1()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + continue; + } + let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(128); + let name = String::from_utf16_lossy(&desc.Description[..len]); + let named = want.as_ref().is_none_or(|w| name.to_lowercase().contains(w)); + if named { + saw_name = true; + } + let bus = adapter_bus(desc.AdapterLuid); + let width = bus.map(pci_link_width).unwrap_or(0); + let mb = desc.DedicatedVideoMemory / (1024 * 1024); + tracing::warn!( + index = i - 1, + adapter = %name, + pci_bus = bus.unwrap_or(u32::MAX), + link_width = width, + dedicated_mb = mb, + "host adapter" + ); + if !named || bus_pin.is_some_and(|b| bus != Some(b)) { + continue; + } + let better = best.as_ref().is_none_or(|(w, mem, _, _, _)| { + width > *w || width == *w && desc.DedicatedVideoMemory > *mem + }); + if better { + best = Some((width, desc.DedicatedVideoMemory, adapter, name, bus.unwrap_or(u32::MAX))); + } + } + if want.is_some() && !saw_name { + tracing::error!(want = want.unwrap_or_default(), "no adapter matches VICTORY_ADAPTER"); + return Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_INVALIDARG, + )); + } + let Some((width, mem, adapter, name, bus)) = best else { + tracing::error!(?bus_pin, "no host adapter to render on"); + return Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )); + }; + tracing::warn!( + adapter = %name, + pci_bus = bus, + link_width = width, + dedicated_mb = mem / (1024 * 1024), + "host device on the widest PCIe link" + ); + adapter.cast() + } +} + +/// PCI bus of a DXGI adapter, from the display driver's own record. +fn adapter_bus(luid: windows::Win32::Foundation::LUID) -> Option<u32> { + #[repr(C)] + struct Open { + luid: windows::Win32::Foundation::LUID, + handle: u32, + } + #[repr(C)] + struct Addr { + bus: u32, + device: u32, + function: u32, + } + #[repr(C)] + struct Query { + handle: u32, + kind: i32, + data: *mut Addr, + size: u32, + } + #[repr(C)] + struct Close { + handle: u32, + } + #[link(name = "gdi32")] + unsafe extern "system" { + fn D3DKMTOpenAdapterFromLuid(open: *mut Open) -> i32; + fn D3DKMTQueryAdapterInfo(query: *const Query) -> i32; + fn D3DKMTCloseAdapter(close: *const Close) -> i32; + } + // SAFETY: the structs match the WDDM layout; the handle is closed. + unsafe { + let mut open = Open { luid, handle: 0 }; + if D3DKMTOpenAdapterFromLuid(&mut open) != 0 { + return None; + } + let mut addr = Addr { bus: 0, device: 0, function: 0 }; + let query = Query { + handle: open.handle, + kind: 6, // KMTQAITYPE_ADAPTERADDRESS + data: &mut addr, + size: std::mem::size_of::<Addr>() as u32, + }; + let ok = D3DKMTQueryAdapterInfo(&query) == 0; + let _ = D3DKMTCloseAdapter(&Close { handle: open.handle }); + ok.then_some(addr.bus) + } +} + +/// Current PCIe link width of the device on PCI `bus` (16, 8, 1, …). 0 if +/// the bus has no such property. +fn pci_link_width(bus: u32) -> u32 { + #[repr(C)] + struct Key { + data1: u32, + data2: u16, + data3: u16, + data4: [u8; 8], + pid: u32, + } + #[link(name = "cfgmgr32")] + unsafe extern "system" { + fn CM_Get_Device_ID_List_SizeW(len: *mut u32, filter: *const u16, flags: u32) -> u32; + fn CM_Get_Device_ID_ListW(filter: *const u16, buf: *mut u16, len: u32, flags: u32) -> u32; + fn CM_Locate_DevNodeW(node: *mut u32, id: *const u16, flags: u32) -> u32; + fn CM_Get_DevNode_PropertyW( + node: u32, + key: *const Key, + ty: *mut u32, + buf: *mut u8, + len: *mut u32, + flags: u32, + ) -> u32; + } + const FILTER: u32 = 0x0000_0001 | 0x0000_0100; + const BUS: Key = Key { + data1: 0xa45c_254e, + data2: 0xdf1c, + data3: 0x4efd, + data4: [0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0], + pid: 23, + }; + const LINK: Key = Key { + data1: 0x3ab2_2e31, + data2: 0x8264, + data3: 0x4b4e, + data4: [0x9a, 0xf5, 0xa8, 0xd2, 0xd8, 0xe3, 0x3e, 0x62], + pid: 10, + }; + let prop = |node: u32, key: &Key| -> Option<u32> { + let mut ty = 0u32; + let mut len = 4u32; + let mut value = 0u32; + // SAFETY: `node` came from Locate; the buffer is 4 bytes. + let rc = unsafe { + CM_Get_DevNode_PropertyW(node, key, &mut ty, (&mut value as *mut u32).cast(), &mut len, 0) + }; + (rc == 0 && ty == 7).then_some(value) + }; + // SAFETY: the list buffer is the size the call asked for. + unsafe { + let filter: Vec<u16> = "PCI".encode_utf16().chain([0]).collect(); + let mut chars = 0u32; + if CM_Get_Device_ID_List_SizeW(&mut chars, filter.as_ptr(), FILTER) != 0 || chars < 2 { + return 0; + } + let mut buf = vec![0u16; chars as usize]; + if CM_Get_Device_ID_ListW(filter.as_ptr(), buf.as_mut_ptr(), chars, FILTER) != 0 { + return 0; + } + let mut widest = 0u32; + let mut at = 0usize; + while at < buf.len() && buf[at] != 0 { + let mut node = 0u32; + if CM_Locate_DevNodeW(&mut node, buf[at..].as_ptr(), 0) == 0 + && prop(node, &BUS) == Some(bus) + { + widest = widest.max(prop(node, &LINK).unwrap_or(0)); + } + at += buf[at..].iter().position(|&c| c == 0).unwrap_or(0) + 1; + } + widest + } +} + +/// 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<IDXGIAdapter> { + // SAFETY: plain DXGI adapter queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; + let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + tracing::warn!( + vendor = format_args!("{:#x}", desc.VendorId), + flags = format_args!("{:#x}", desc.Flags), + "DXGI did not identify the WARP adapter as software; refusing device" + ); + return Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )); + } + Ok(adapter) + } +} + +#[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::<u8>(); + 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] + fn warp_adapter_accepts_only_software() { + // This probes DXGI without creating a D3D12 device or running a title. + // SAFETY: plain DXGI adapter queries. + let raw = unsafe { + let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + else { + return; + }; + factory.EnumWarpAdapter::<IDXGIAdapter>() + }; + let Ok(raw) = raw else { return }; + // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements + // IDXGIAdapter1; `raw` owns that interface. + let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() }; + eprintln!( + "EnumWarpAdapter: vendor={:#x}, flags={:#x}", + desc.VendorId, desc.Flags + ); + assert_eq!( + warp_adapter().is_ok(), + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, + ); + } +} + +/// A host command list and its allocator, always used together. +pub(crate) struct HostList { + allocator: ID3D12CommandAllocator, + pub(crate) list: ID3D12GraphicsCommandList, + /// Work for submission time, in recorded order. + deferred: Mutex<Deferred>, + /// Upload memory for data the list's draws make (expanded vertices), + /// reused after a reset. + scratch: Mutex<Scratch>, + /// Host texture states the list assumes, by host copy: at its start and + /// at its end. Lists are recorded on many threads and run in submission + /// order, so the transitions from a texture's real state are made at + /// submission, in `prelude`. Holding the copies keeps every texture the + /// list names alive until it is reset, even if the title releases the + /// resource first. + states: Mutex<States>, + /// What the list does with depth textures that have a colour twin, by + /// twin ([`TwinUse`]). + twins: Mutex<std::collections::HashMap<usize, TwinUse>>, + /// The list that runs those transitions just before this one, made + /// when the list first has such transitions ([`lazy_prelude`]). + prelude: OnceLock<Option<Prelude>>, + /// The pipelines the list binds, for reports of slow submissions. + pipelines: Mutex<std::collections::BTreeSet<String>>, + /// The work its indirect executions may still do (`indirect`): a + /// shader-writable word, zeroed when the list is submitted. + budget: OnceLock<Option<(ID3D12Resource, usize)>>, + /// Device-local scratch buffer for clamped indirect arguments (`indirect`), + /// grown to the largest indirect execution recorded on the list. + indirect_args: Mutex<Option<(ID3D12Resource, u64)>>, + /// 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")] + notes: Mutex<Vec<Note>>, + /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command + /// and at the end, and where they are read back. + #[cfg(feature = "diagnostics")] + stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>, +} + +/// 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<bool> = 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; + +/// A marker's text and the host range its command reads (diagnostics). +#[cfg(feature = "diagnostics")] +type Note = (String, Option<(u64, u64)>); + +type States = std::collections::HashMap< + usize, + (u32, u32, std::sync::Arc<crate::resource::HostTexture>), +>; + +/// 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<crate::resource::HostTexture>, + twin: std::sync::Arc<crate::resource::Twin>, + /// 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<bool>; 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, +} + +/// 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 +/// Grand Theft Auto VI'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); +} +"#; +const PLANE_STEPS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray<uint> 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); +} +"#; +const PLANE_FLOATS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray<float> twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return twin.Load(int4(int2(p.xy), 0, 0)); +} +"#; + +/// 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; + +/// 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<Vec<(bool, i32, Option<PlanePipeline>)>>, +} + +/// The pass's root signature and pipeline for one kind of twin and one +/// depth format. +type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState); + +// 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<Option<PlanePass>> = 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() +} + +/// 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<Vec<u8>> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option<ID3DBlob> = None; + let mut errors: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("victory"), + 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::<u8>(), + 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::<u8>(), 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<PlanePipeline> { + 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<PlanePipeline> { + 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 Grand Theft Auto VI + // 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<bool> = 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<bool> = 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::<ID3D12Object>() + { + // 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<bool> = 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<T> { + kept: Vec<(T, u64)>, + bytes: u64, +} + +impl<T> Spare<T> { + 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<T> { + 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<T> { + 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<Spare<Chunk>> = 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<Chunk> { + 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<Prelude>, + /// After them, in the same submission: the compare of the declared + /// ranges with their bytes from before. As `sync`. + check: Vec<Prelude>, + /// 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<Option<CardWork>> = 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<bool> = 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<bool> = 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<crate::shadow::Shadow>, + /// 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<CardRange>, + /// The compare, run after the submission's lists. + check: Option<ID3D12CommandList>, + /// The copies whose card side was brought up to date, alive until the + /// submission has run. + _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>, + /// 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<crate::shadow::Shadow>, usize, usize), + /// Work that may write title memory. + Run(Box<dyn Fn() + Send>), + /// Work that writes host memory only. + Host(Box<dyn Fn() + Send>), + /// Shaders write a range (address, bytes) of a buffer's host copy. + GpuWrite(std::sync::Arc<crate::shadow::Shadow>, 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<crate::texture::Staging>), +} + +/// 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<Step>, + uploads: Vec<ID3D12Resource>, + /// 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<windows::core::IUnknown>, + /// 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<usize>, + /// 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<u8> = 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<bool> = 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<bool> = OnceLock::new(); + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_some_and(|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<u64> = 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<u64>], 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`, 128; 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<usize> = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128).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<bool> = 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<crate::shadow::Shadow>, 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<CardPlan>, + back: Vec<Declared>, + /// 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<crate::list::Detached>, + order: Vec<usize>, + card: Option<CardPlan>, + back: Vec<Declared>, +} + +/// 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<Late>, + /// 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<crate::list::Detached>, Vec<usize>)>, + /// 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<Line> = 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<Item = (usize, usize)>) { + 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<usize> { + 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<usize> { + 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<crate::shadow::Shadow>, 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<RelayFetch> = 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<Option<u64>> = 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<Late> = 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<crate::shadow::Shadow>, 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<f64> = 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<f64> = 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<f64> = 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<bool> = 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<Declared> { + let mut back: Vec<Declared> = 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 +} + +/// 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::<u8>().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); + } + 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<crate::shadow::Shadow>, 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<bool> = OnceLock::new(); + *MESH.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: each query writes its own structure of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + && self + .device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut model).cast(), + size_of_val(&model) as u32, + ) + .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 + }) + } + + /// A new list, open for recording. + pub(crate) fn new_list(&self) -> windows::core::Result<HostList> { + #[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<Prelude> { + // SAFETY: plain object creation. + let made: windows::core::Result<Prelude> = 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<HostList> { + // 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<Option<CardClock>> = 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::<ID3D12Fence>(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<bool> = 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<CardWork> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the 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::<u8>(), 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<CardPlan> { + 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<crate::shadow::Shadow>, 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<Arc<crate::shadow::Shadow>> = 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<crate::shadow::CardSpan> = 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::<u64>(), 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<ID3D12CommandList> { + 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<RelayFetch> { + 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<RelayFetch>) { + let differs = { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) + }; + let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + 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<u64> { + 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::<ID3D12CommandList>()?)]; + // 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) }; + written += shadow.card_merge_relay(*lo, gpu, after, &mut title); + } + 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<Late>, fetch: &mut Option<RelayFetch>) { + 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<Declared> = 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<Vec<std::sync::atomic::AtomicUsize>> = + 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<Box<dyn FnOnce() + Send>> = pieces + .chunks(each) + .map(|chunk| { + let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, 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) }; + counts[i].fetch_add(shadow.card_merge(lo, gpu, &mut title), Ordering::Relaxed); + } + }) as Box<dyn FnOnce() + Send> + }) + .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) }; + written[i] += plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + } + } + } + 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<crate::list::Detached>, order: Vec<usize>) { + 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 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<Declared> = 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())), + } + } + } + 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 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); + } + + /// [`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()); + 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")] + let lock = (started - called).as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Submissions, 1); + let mut lists: Vec<Option<ID3D12CommandList>> = 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<usize, (usize, usize)> = 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(); + 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")] + 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<ID3D12CommandList>]> = 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.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); + 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 timing() { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + 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<String> = 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<String> = runs + .iter() + .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"); + } + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + fail(format_args!( + "host GPU device removed after a submission of {} lists{}{}", + runs.len(), + self.removal_data(runs), + 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(); + // 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()); + } + 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 + /// it lies in (by the names we give them) or the title memory copy just + /// below it; for each list that did not finish, the command it stopped + /// at and what the draws and dispatches in flight there run (or, in + /// lists that never started, the pipelines they bind). + fn removal_data(&self, runs: &[&HostList]) -> String { + let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else { + return String::new(); + }; + let mut text = String::new(); + let mut fault_va = None; + // SAFETY: the outputs are the runtime's, valid while the device + // lives; nodes are walked as linked, histories have their counts. + unsafe { + if let Ok(fault) = dred.GetPageFaultAllocationOutput1() + && fault.PageFaultVA != 0 + { + let va = fault.PageFaultVA; + fault_va = Some(va); + text.push_str(&format!("; page fault at {va:#x}")); + for (what, head) in [ + ("inside", fault.pHeadExistingAllocationNode), + ("inside freed", fault.pHeadRecentFreedAllocationNode), + ] { + let mut names = Vec::new(); + let mut node = head; + while let Some(n) = node.as_ref() + && names.len() < 8 + { + let name = if n.ObjectNameW.is_null() { + "unnamed".to_owned() + } else { + n.ObjectNameW.to_string().unwrap_or_default() + }; + names.push(format!("{name} (type {})", n.AllocationType.0)); + node = n.pNext; + } + if !names.is_empty() { + text.push_str(&format!("; {what} {names:?}")); + } + } + text.push_str(&crate::shadow::near(va)); + text.push_str(&crate::descriptor::host::near_heaps(va)); + } + // The plain output: the extended one (with marker texts) came + // back without stopped lists on this host. + let crumbs = match dred.GetAutoBreadcrumbsOutput() { + Ok(crumbs) => crumbs, + Err(e) => { + text.push_str(&format!("; no breadcrumbs ({e})")); + return text; + } + }; + // Every list's progress (done/count), in the runtime's order. + let mut progress = Vec::new(); + let mut node = crumbs.pHeadAutoBreadcrumbNode; + while let Some(p) = node.as_ref() { + let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); + let ours = p.pCommandList.as_ref().map(|l| l.as_raw()); + let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours); + progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount)); + node = p.pNext; + } + text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}")); + let mut plain = crumbs.pHeadAutoBreadcrumbNode; + while let Some(p) = plain.as_ref() { + let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); + if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() { + let history = + std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize); + text.push_str(&format!( + "; a list stopped at command {done} of {} (op {})", + p.BreadcrumbCount, history[done as usize].0 + )); + let list = p.pCommandList.as_ref().map(|l| l.as_raw()); + let run = runs.iter().find(|r| Some(r.list.as_raw()) == list); + // The k-th marker command is the k-th note. + #[cfg(feature = "diagnostics")] + let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| { + let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + history + .iter() + .enumerate() + .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) + .zip(notes.iter()) + .map(|((at, _), (note, range))| { + let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r)); + (at as u32, format!("{note}{}", place.unwrap_or_default())) + }) + .collect() + }); + #[cfg(not(feature = "diagnostics"))] + let markers: Vec<(u32, String)> = Vec::new(); + #[cfg(not(feature = "diagnostics"))] + let _ = fault_va; + if done > 0 { + text.push_str(&in_flight(history, &markers, done as usize)); + } else if let Some(r) = run { + let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + text.push_str(&format!(", its pipelines {pipelines:?}")); + } + } + plain = p.pNext; + } + } + text + } + + /// Moves the debug layer's messages into our log; returns the first + /// error among them. + pub(crate) fn log_messages(&self) -> Option<String> { + let Some(queue) = &self.messages else { + return None; + }; + let mut first_error = None; + // SAFETY: each message is read into a buffer of the size the queue + // reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}"); + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { + first_error = Some(text.to_owned()); + } + } + } + queue.ClearStoredMessages(); + } + first_error + } + + /// A host render target view of `resource`, valid until it is recorded. + pub(crate) fn rtv( + &self, + resource: Option<&ID3D12Resource>, + desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, + ) -> 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, 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); + handle + } + } + + /// A host depth view of `resource`, valid until it is recorded. + pub(crate) fn dsv( + &self, + resource: &ID3D12Resource, + desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>, + ) -> D3D12_CPU_DESCRIPTOR_HANDLE { + let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING; + // SAFETY: a slot of our heap and a live resource. + unsafe { + let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart(); + handle.ptr += (slot * self.dsv_size) as usize; + self.device + .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle); + handle + } + } +} + +impl HostList { + /// The timestamp heap and its read-back buffer (diagnostics, timing on). + #[cfg(feature = "diagnostics")] + fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> { + if !timing() { + return None; + } + self.stamps + .get_or_init(|| { + let device = &host()?.device; + let mut heap: Option<ID3D12QueryHeap> = None; + let mut back: Option<ID3D12Resource> = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(STAMPS) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation. + unsafe { + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 }, + &mut heap, + ) + .ok()?; + device + .CreateCommittedResource( + &readback, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .ok()?; + } + Some((heap?, back?)) + }) + .as_ref() + } + + /// The noted commands that took longest on the GPU, longest first, as + /// (milliseconds, text) (diagnostics, timing on, after the list ran). + #[cfg(feature = "diagnostics")] + fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> { + let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner()); + let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else { + return Vec::new(); + }; + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 }; + // SAFETY: a read-back buffer the finished list resolved into. + let stamps: Vec<u64> = unsafe { + if back.Map(0, Some(&range), Some(&mut data)).is_err() { + return Vec::new(); + } + let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec(); + back.Unmap(0, None); + s + }; + 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()) + }) + .collect(); + times.sort_by(|a, b| b.0.total_cmp(&a.0)); + times.truncate(n); + times + } + + pub(crate) fn close(&self) { + 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); + // 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); + } + } + // SAFETY: our list. + if let Err(e) = unsafe { self.list.Close() } { + fail(format_args!( + "a host command list did not close ({e}): a command recorded into it was invalid" + )); + } + } + + /// 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.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); + // 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 { + self.allocator + .Reset() + .and_then(|()| self.list.Reset(&self.allocator, None)) + }; + if let Err(e) = reset { + fail(format_args!("a host command list did not reset ({e})")); + } + #[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 + /// list: the host texture and the state it leaves, if that is a change. + /// The list's first use of a texture records nothing: its prelude brings + /// the texture there at submission. + pub(crate) fn transition( + &self, + resource: crate::object::This, + wanted: u32, + ) -> Option<(&'static ID3D12Resource, u32)> { + let texture = crate::resource::host_resource(resource)?; + let copy = crate::resource::host_copy(resource)?; + let wanted = legal_state(texture, wanted); + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + match states.entry(std::sync::Arc::as_ptr(©) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, copy)); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let before = std::mem::replace(&mut o.get_mut().1, wanted); + (before != wanted).then_some((texture, before)) + } + } + } + + /// 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<crate::resource::HostTexture>, 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, copy.clone())); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let before = std::mem::replace(&mut o.get_mut().1, wanted); + (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]) }; + } + } + + /// 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, + 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<crate::resource::HostTexture>, + twin: &crate::resource::Twin, + ) { + 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); + } + + /// 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<crate::resource::HostTexture>, + 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 Grand Theft Auto VI 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. 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<ID3D12CommandList> { + 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()); + // 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]; + } + } + 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(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 { + (&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() && syncs.is_empty() { + return None; + } + 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 !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); + } + for (depth, twin, colour) in &syncs { + record_twin_copy(list, &depth.texture, twin, *colour); + } + if !barriers.is_empty() { + list.ResourceBarrier(&barriers); + } + list.Close() + }) + }; + if let Err(e) = recorded { + fail(format_args!("a host state prelude did not record ({e})")); + } + list.cast().ok() + } + + /// Notes what the command about to be recorded does, as a marker + /// command whose text the list keeps (diagnostics, with device-removed + /// data on): the report pairs the breadcrumbs' marker commands with the + /// texts in order and names the commands a fault stopped among. + #[cfg(feature = "diagnostics")] + pub(crate) fn note_op(&self, what: impl FnOnce() -> String) { + self.note(what, None); + } + + /// As [`HostList::note_op`], for a copy that reads the host GPU range + /// `(address, bytes)`: the report places the faulting address in it. + #[cfg(feature = "diagnostics")] + pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) { + self.note(what, Some(range)); + } + + #[cfg(feature = "diagnostics")] + fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { + 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 { + // 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<u16> = 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.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. + pub(crate) fn used_pipeline(&self, name: &str) { + let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + if !pipelines.contains(name) { + pipelines.insert(name.to_owned()); + } + } + + fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> { + self.deferred.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// 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)); + deferred.refreshed.clear(); + } + + /// Copies `len` bytes of title memory at `src` into the list's upload + /// memory at `dst` when the list is submitted. + pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) { + self.deferred() + .copies + .push(Step::Fill(dst as usize, src as usize, len)); + } + + /// Brings `[address, address + len)` of a buffer's host copy up to date + /// when the list is submitted (once per range until a title copy + /// intervenes), keeping the copy alive until the list is reset. + pub(crate) fn defer_refresh( + &self, + shadow: &std::sync::Arc<crate::shadow::Shadow>, + address: usize, + len: usize, + ) { + let mut deferred = self.deferred(); + let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + if deferred.refreshed.insert(key) { + deferred + .copies + .push(Step::Refresh(shadow.clone(), address, len)); + } + } + + /// Shaders of the list write `[address, address + len)` of a buffer's + /// host copy: copied back into title memory once the list has run. + pub(crate) fn defer_gpu_write( + &self, + shadow: &std::sync::Arc<crate::shadow::Shadow>, + address: usize, + len: usize, + ) { + self.deferred() + .copies + .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)); + } + + /// A mapped upload buffer of `size` bytes, alive until the list is + /// reset. + /// + /// shortcut: one buffer per copy; pool them once uploads are frequent. + 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().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 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().hold_upload(buffer, len); + return Some((gpu, data)); + } + // 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 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 (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 + /// submission of the list from the first use after a reset on. + pub(crate) fn budget(&self) -> Option<u64> { + let (buffer, data) = self + .budget + .get_or_init(|| { + let (b, d) = host()?.shared_buffer(256)?; + Some((b, d as usize)) + }) + .as_ref()?; + let mut deferred = self.deferred(); + if !deferred.budget_zeroed { + deferred.budget_zeroed = true; + let at = *data; + // 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 { + 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<ID3D12Resource> { + 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::<windows::core::IUnknown>() { + self.deferred().kept.push(object); + } + } + + /// Whether this is the first time since the reset that the list asks + /// about `key` (a texture to bring up to date). + pub(crate) fn first_use(&self, key: usize) -> bool { + self.deferred().textures.insert(key) + } + + /// Runs `work` when the list is submitted, in order with its copies. + /// `work` may write title memory (refreshes after it copy again). + pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::Run(Box::new(work))); + self.deferred().refreshed.clear(); + } + + /// As [`HostList::defer`], for work that writes only host memory. + pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::Host(Box::new(work))); + } + + /// Brings a texture's staging buffer up to date when the list is + /// submitted, keeping it alive until the list is reset. + pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) { + self.deferred().copies.push(Step::Texture(staging)); + } + + /// Runs the list's submission-time steps; refreshes go into `batch` + /// (the title's big buffers, a 174 MB one among them, are read by most + /// lists of a submission, through many ranges). + fn run_deferred(&self, batch: &mut Batch) { + #[cfg(feature = "diagnostics")] + use crate::copystat::{C, add}; + for step in &self.deferred().copies { + let started = std::time::Instant::now(); + let copied = match step { + &Step::Copy(dst, src, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Copies, 1); + add(C::CopyBytes, len as u64); + } + batch.title_written(); + 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) => { + #[cfg(feature = "diagnostics")] + { + add(C::Copies, 1); + add(C::CopyBytes, len as u64); + } + copy_mapped(dst as *mut u8, src as *const u8, len, false); + len + } + Step::Refresh(shadow, address, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Refreshes, 1); + add(C::RefreshBytes, *len as u64); + } + batch.add(shadow, *address, *len); + continue; + } + Step::Run(work) | Step::Host(work) => { + if matches!(step, Step::Run(_)) { + batch.title_written(); + } + 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); + add(C::RunUs, started.elapsed().as_micros() as u64); + } + continue; + } + Step::GpuWrite(shadow, address, len) => { + // 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) => { + if batch.texture_due(staging) { + staging.refresh(); + } + continue; + } + }; + PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + } + } +} + +/// 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<bool> = 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. +/// +/// Also the textures brought up to date in the submission so far: most +/// lists of a world submission sample the same textures, and a texture in +/// physical-page memory is hashed whole each time it is checked. Checked +/// once, it is checked again only after a step that writes title memory. +#[derive(Default)] +struct Batch { + refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, 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<usize, usize>, + /// Staging buffers (by address) refreshed since the last title write. + textures: std::collections::HashSet<usize>, +} + +impl Batch { + fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) { + let end = address + len; + 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<crate::shadow::Shadow>) { + 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<T>(&mut self, staging: &std::sync::Arc<T>) -> bool { + self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) + } + + /// Before a step that writes title memory: pending refreshes are done + /// first, and textures are checked again after it. + fn title_written(&mut self) { + self.flush(); + self.textures.clear(); + } + + fn flush(&mut self) { + 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<Box<dyn FnOnce() + Send>> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>) + .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(..) { + Self::update(&shadow, from, to); + } + } + if ahead { + crate::watch::ask_ahead_done(); + } + } +} + +/// Copies title memory at submission. The ranges were checked against their +/// resources when recorded, but the title may since have unmapped pages of +/// them (tiled memory, page mappings), which read as zeros here; a title +/// destination (`title_dst`) that is not all mapped is left alone. +/// +/// The source is read through the kernel (`ReadProcessMemory`), which +/// reports an unmapped page instead of faulting. Asking `VirtualQuery` first +/// cost about 2 ms per copy in the title's big pools (it walks the page +/// tables to the region's end), which made copies run at 100-200 MB/s. +pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) { + #[cfg(feature = "diagnostics")] + match crate::copystat::mode() { + 1 => { + // SAFETY: timing only: the caller vouches for the source. + unsafe { std::ptr::copy(src, dst, len) }; + return; + } + 2 => return, + _ => {} + } + 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<bool> = 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); + } + #[cfg(feature = "diagnostics")] + 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); + if whole { + return; + } + // 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| { + let to = dst.wrapping_add(at - src as usize); + if !read(at as *const u8, to, n) { + for_pieces(at, n, 4 << 10, |at, n| { + let to = dst.wrapping_add(at - src as usize); + if !read(at as *const u8, to, n) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, n as u64); + // SAFETY: inside the destination, which is mapped. + unsafe { to.write_bytes(0, n) }; + } + }); + } + }); +} + +/// Reads title memory at `src` into `dst`; false if a page of it is not +/// readable. +pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { + read(src, dst.as_mut_ptr(), dst.len()) +} + +/// Copies `len` bytes from `src` to `dst` unless a source page is not +/// readable. +fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut done = 0; + // SAFETY: the destination is mapped writable memory of `len` bytes; the + // kernel checks the source. + unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 } +} + +#[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; +} + +/// 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<bool> = 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 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 { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 } + }; + if len == 0 || write(dst as usize, len) { + return; + } + for_pieces(dst as usize, len, 64 << 10, |at, n| { + if !write(at, n) { + for_pieces(at, n, 4 << 10, |at, n| { + write(at, n); + }); + } + }); +} + +/// Calls `f` with the pieces of `[start, start + len)` cut at multiples of +/// `step`. +fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) { + let end = start + len; + let mut at = start; + while at < end { + let next = ((at / step + 1) * step).min(end); + f(at, next - at); + at = next; + } +} + +impl Host { + /// A buffer in the upload heap, mapped for writing. + /// A buffer of `size` bytes the card writes and we read (a read back), + /// in the state copies into it need. + pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..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, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a read-back buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no read-back buffer"); + None + } + } + } + + pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[0].fetch_add(1, Ordering::Relaxed); + MADE[1].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..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, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of an upload buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no upload buffer"); + None + } + } + } +} + +/// The swap chain formats a presented texture can be copied into: its own +/// family's. +fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> { + Some(match format.0 { + 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM, + 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM, + 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM, + 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT, + _ => return None, + }) +} + +const BUFFERS: u32 = 2; + +struct Presenter { + swap_chain: IDXGISwapChain3, + width: u32, + 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, +} + +/// The frame rate, shown in the window's caption every second and logged +/// every few seconds. +struct Meter { + since: std::time::Instant, + frames: u32, + #[cfg(feature = "diagnostics")] + copy_stats_frames: u64, + drawn: u64, + logged: std::time::Instant, + /// The caption the window had, once read. + caption: Option<Vec<u16>>, +} + +impl Meter { + fn new() -> Self { + let now = std::time::Instant::now(); + Meter { + since: now, + frames: 0, + #[cfg(feature = "diagnostics")] + copy_stats_frames: 0, + drawn: crate::draw::drawn(), + logged: now, + caption: None, + } + } + + /// Counts a presented frame. + 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")] + { + self.copy_stats_frames += 1; + } + let elapsed = self.since.elapsed(); + if elapsed < std::time::Duration::from_secs(1) { + return; + } + let drawn = crate::draw::drawn(); + let frames = f64::from(self.frames); + let fps = frames / elapsed.as_secs_f64(); + let ms = elapsed.as_secs_f64() * 1000.0 / frames; + 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 [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 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; 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")] + { + crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); + for (why, n) in drops.iter().take(40) { + tracing::info!( + "dropped {:.1}/frame without a host pipeline: {why}", + *n as f64 / frames + ); + } + } + } + if self.caption.is_none() { + // The window's own text, read without a message. + let mut buffer = vec![0u16; 512]; + // SAFETY: a window handle and a buffer of that length. + let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) }; + buffer.truncate(n.max(0) as usize); + self.caption = Some(buffer); + } + let Some(caption) = &self.caption else { return }; + let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"); + let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect(); + text.push(0); + // Setting the text waits for the window's thread (a title thread, + // which may not pump for a while), so a thread of ours does it and + // presenting never waits; it takes the newest text when free. + static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None); + static SETTER: std::sync::Once = std::sync::Once::new(); + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text)); + SETTER.call_once(|| { + let _ = std::thread::Builder::new() + .name("victory-caption".into()) + .spawn(|| { + loop { + let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take(); + match next { + // SAFETY: a window handle and a NUL-terminated text. + Some((hwnd, text)) => unsafe { + let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr())); + }, + None => std::thread::sleep(std::time::Duration::from_millis(100)), + } + } + }); + }); + } +} + +impl Host { + /// Shows `texture`, which is in `state` (a host state) and stays in it, + /// 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<bool> { + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + let Some(format) = swap_format(desc.Format) else { + tracing::warn!(format = desc.Format.0, "cannot present this format"); + return None; + }; + let (width, height) = (desc.Width as u32, desc.Height); + let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); + if presenter.is_none() { + *presenter = match self.presenter(width, height, format) { + Ok(p) => Some(p), + Err(e) => { + tracing::warn!(error = %e, "no swap chain"); + return None; + } + }; + } + 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), + Err(e) => { + tracing::warn!(error = %e, width, height, "swap chain not resized"); + return None; + } + } + } + let state = D3D12_RESOURCE_STATES(state as i32); + // SAFETY: our swap chain, list and a live source texture. + unsafe { + let index = p.swap_chain.GetCurrentBackBufferIndex(); + let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else { + return None; + }; + // 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( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_COPY_DEST, + ), + ]); + list.CopyResource(&back, texture); + #[cfg(feature = "diagnostics")] + let capture = crate::capture::wanted(frame) + .then(|| crate::capture::read_back(&self.device, list, texture)) + .flatten(); + #[cfg(feature = "diagnostics")] + let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + #[cfg(not(feature = "diagnostics"))] + let _ = frame; + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + ), + ]); + 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); + } + let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + p.meter.frame(p.hwnd); + #[cfg(feature = "diagnostics")] + return Some(probe.is_some_and(|b| crate::capture::black(&b))); + #[cfg(not(feature = "diagnostics"))] + Some(false) + } + } + + fn presenter( + &self, + width: u32, + height: u32, + format: DXGI_FORMAT, + ) -> windows::core::Result<Presenter> { + let hwnd = match title_window() { + Some(hwnd) => hwnd, + None => window(width, height)?, + }; + // SAFETY: plain object creation for our window. + unsafe { + let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: width, + Height: height, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: BUFFERS, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + ..Default::default() + }; + let swap_chain = factory + .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? + .cast::<IDXGISwapChain3>()?; + let copy = self.new_list()?; + copy.close(); + tracing::info!(width, height, format = format.0, "presenting to a window"); + Ok(Presenter { + swap_chain, + width, + height, + format, + copy, + ahead: Vec::new(), + hwnd, + meter: Meter::new(), + }) + } + } +} + +/// A visible top-level window of this process: the one the title made, if +/// it made one. +fn title_window() -> Option<HWND> { + extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL { + let mut process = 0; + // SAFETY: a window handle from the enumeration; `found` is ours. + unsafe { + GetWindowThreadProcessId(hwnd, Some(&mut process)); + if process == windows::Win32::System::Threading::GetCurrentProcessId() + && IsWindowVisible(hwnd).as_bool() + { + *(found.0 as *mut Option<HWND>) = Some(hwnd); + return false.into(); + } + } + true.into() + } + let mut found: Option<HWND> = None; + // SAFETY: the callback only writes `found`, which outlives the call. + let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) }; + found +} + +/// `state` without the bits the host texture's flags forbid: the console +/// lets the title name states its own resources allow (unordered access on +/// a depth target, whose host copy cannot have both). +pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 { + // SAFETY: a plain query. + legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state) +} + +/// [`legal_state`] for a texture with resource flags `flags`. +pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { + // (flag, set or clear forbids, state bits): render target, unordered + // access, depth, denied shader resource. + const FORBIDDEN: [(u32, bool, u32); 4] = [ + (0x1, false, 0x4), + (0x4, false, 0x8), + (0x2, false, 0x10 | 0x20), + (0x8, true, 0x40 | 0x80), + ]; + FORBIDDEN + .iter() + .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny) + .fold(state, |s, &(_, _, bits)| s & !bits) +} + +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()?; + } + Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) + } + + /// 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, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..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<ID3D12Resource> = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no shared buffer"); + None + } + } + } + + /// A device-local buffer shaders may write (unordered access) and indirect + /// execution may read, starting in the common state. + pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> { + 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<ID3D12Resource> = 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 +/// commands each list of the failed submission noted (diagnostics, with +/// `VICTORY_D3D12_DRED`). +fn last_notes(runs: &[&HostList]) -> String { + #[cfg(feature = "diagnostics")] + { + let mut text = String::new(); + 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 + } + #[cfg(not(feature = "diagnostics"))] + { + let _ = runs; + String::new() + } +} + +/// Where the faulting address `va` lies against a range `(start, bytes)` a +/// command reads (diagnostics). +#[cfg(feature = "diagnostics")] +fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { + let end = start + bytes; + if va < start { + format!(" (fault {:#x} below its source)", start - va) + } else if va < end { + format!(" (fault at source +{:#x})", va - start) + } else { + format!(" (fault {:#x} past its source's end)", va - end) + } +} + +/// The commands that may have been running where a list stopped at +/// command `done`: those between the barriers around it (work between +/// 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 { + 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 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; + // 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; + } + shown += 1; + let marker = i + .checked_sub(1) + .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) + .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m)) + .map_or("no marker", |(_, s)| s.as_str()); + text.push_str(&format!("; command {i} (op {}): {marker}", op.0)); + } + text +} + +pub(crate) fn transition( + resource: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(resource) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// A window of the given client size, owned by its own message thread. +fn window(width: u32, height: u32) -> windows::core::Result<HWND> { + let (sender, receiver) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("victory-window".into()) + .spawn(move || { + let made = make_window(width, height); + let ok = made.is_ok(); + let _ = sender.send(made.map(|h| h.0 as usize)); + if ok { + pump(); + } + }) + .map_err(|_| windows::core::Error::empty())?; + let hwnd = receiver + .recv() + .map_err(|_| windows::core::Error::empty())??; + Ok(HWND(hwnd as *mut _)) +} + +extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + // SAFETY: the default handling for our window. + unsafe { DefWindowProcW(hwnd, message, wparam, lparam) } +} + +fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> { + const CLASS: PCWSTR = w!("VIctory"); + // SAFETY: registers our class once and creates a window of it. + unsafe { + let instance = GetModuleHandleW(None)?; + let class = WNDCLASSEXW { + cbSize: size_of::<WNDCLASSEXW>() as u32, + lpfnWndProc: Some(window_proc), + hInstance: instance.into(), + lpszClassName: CLASS, + hCursor: LoadCursorW(None, IDC_ARROW)?, + ..Default::default() + }; + RegisterClassExW(&class); + let mut rect = RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }; + AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?; + CreateWindowExW( + WINDOW_EX_STYLE(0), + CLASS, + w!("VIctory"), + WS_OVERLAPPEDWINDOW | WS_VISIBLE, + CW_USEDEFAULT, + CW_USEDEFAULT, + rect.right - rect.left, + rect.bottom - rect.top, + None, + None, + Some(instance.into()), + None, + ) + } +} + +fn pump() { + let mut message = MSG::default(); + // SAFETY: the standard message loop of this thread's window. + unsafe { + while GetMessageW(&mut message, None, 0, 0).as_bool() { + let _ = TranslateMessage(&message); + DispatchMessageW(&message); + } + } +} + +#[cfg(test)] +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<u32> = 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; + + #[test] + fn a_texture_is_checked_once_per_submission() { + let mut batch = Batch::default(); + let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); + // The first list sampling each texture checks it ... + assert!(batch.texture_due(&a)); + assert!(batch.texture_due(&b)); + // ... later lists of the same submission do not. + assert!(!batch.texture_due(&a)); + assert!(!batch.texture_due(&a.clone())); + assert!(!batch.texture_due(&b)); + } + + #[test] + fn title_writes_make_textures_due_again() { + let mut batch = Batch::default(); + let a = Arc::new(1u32); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A copy into title memory or work that may write it may have + // changed the texture's memory. + batch.title_written(); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A fresh submission starts over. + let mut next = Batch::default(); + assert!(next.texture_due(&a)); + } + + /// The hashing a submission does for textures in physical-page memory, + /// with every list checking the textures it samples (before) and with + /// each checked once (after). Run with + /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`. + #[test] + #[ignore = "benchmark"] + fn texture_checks_per_submission() { + const TEXTURES: usize = 48; + const SIZE: usize = 4 << 20; + const LISTS: usize = 12; + let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES) + .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) + .collect(); + let submit = |dedupe: bool| { + let mut batch = Batch::default(); + let mut hashed = 0usize; + let started = std::time::Instant::now(); + for _ in 0..LISTS { + for t in &textures { + if !dedupe || batch.texture_due(t) { + std::hint::black_box(blake3::hash(t)); + hashed += 1; + } + } + } + (started.elapsed(), hashed) + }; + submit(false); // warm up + let (before, n_before) = submit(false); + let (after, n_after) = submit(true); + assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); + println!( + "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ + before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", + SIZE >> 20, + before.as_secs_f64() / after.as_secs_f64() + ); + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs new file mode 100644 index 000000000..8edcece02 --- /dev/null +++ b/crates/victory-gpu/src/indirect.rs @@ -0,0 +1,1216 @@ +//! Indirect execution's arguments, bounded before the GPU reads them. The +//! 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 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. +//! +//! 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 +//! dispatches, the budget) cut legitimate work beyond them; raise them if +//! the title needs more. + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::s; + +use crate::host::{HostList, host, transition}; + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind; + uint stride; + uint records; + uint args_offset; + // Bit 0: a count buffer bounds the records. Bit 1: the records are a + // window clamped ahead of their draws: one that asks for more than can + // run is left empty and costs nothing. + uint has_count; + uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint eff_count = records; + bool ahead = (has_count & 2u) != 0; + if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); + } + if (id.x >= eff_count) return; + uint src_at = args_offset + id.x * stride; + uint dst_at = id.x * stride; + uint cost; + uint2 draw_counts = uint2(0, 0); + uint3 groups = uint3(0, 0, 0); + if (kind <= 1) { + // Draws: vertex or index count, then instances. + uint2 asked = src_args.Load2(src_at); + if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { + asked = uint2(0, 0); + } + uint count = min(asked.x, 1u << 24); + uint instances = min(asked.y, (1u << 26) / max(count, 1u)); + cost = count * instances; + draw_counts = uint2(count, instances); + } else if (kind == 2) { + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + // x * y fits 32 bits; the whole count may not. + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + groups = g; + } else { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (Grand Theft Auto VI leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + // Diagnostics, in the budget buffer's next words: the largest + // group count a mesh record asked for, and the groups asked in all. + uint was; + budget.InterlockedMax(4, g.x, was); + budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; + } + bool over = false; + if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= BUDGET || BUDGET - before < cost; + } + if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } +} +"#; + +struct Clamp { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Clamp {} +// SAFETY: as above. +unsafe impl Sync for Clamp {} + +fn clamp() -> Option<&'static Clamp> { + static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new(); + CLAMP + .get_or_init(|| match make() { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no argument clamp: indirect execution dropped"); + None + } + }) + .as_ref() +} + +fn make() -> windows::core::Result<Clamp> { + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + make_for(device) +} + +fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> { + let mut code: Option<ID3DBlob> = None; + let mut errors: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + s!("clamp"), + None, + None, + s!("main"), + s!("cs_5_1"), + 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::<u8>(), + errors.GetBufferSize(), + ) + }; + tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + 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 = + std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), 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 }) + } +} + +/// Minimum record byte stride for a supported PC indirect argument `kind`. +fn min_stride(kind: u32) -> Option<u32> { + 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<u64>, +) -> Option<u64> { + 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 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, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), +) -> Option<ID3D12Resource> { + 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<ID3D12Resource> { + 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(bytes) = validate_layout( + (kind, stride, records), + src_offset, + count.map(|(_, off)| off), + ) else { + return false; + }; + // 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 (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 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 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.ResourceBarrier(&[transition( + scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]) + }; +} + +fn uav_barrier() -> D3D12_RESOURCE_BARRIER { + 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), + }), + }, + } +} + +#[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<Self> { + // 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::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + let 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<ID3D12Resource> = 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<ID3D12Resource> = 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<ID3D12CommandSignature> = 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<Clamp> { + let mut code: Option<ID3DBlob> = 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::<u8>(), + 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<u8> = (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::<u32>().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::<u32>().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() { + if super::host().is_none() { + return; // no host GPU here + } + assert!(super::clamp().is_some()); + } + + #[test] + 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); + } + + /// 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 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::<u32>().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); + } + + /// 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; + }; + 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 { + 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::<u32>().cast_const(), total / 4).to_vec(), + ) + }; + 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); + } + } + } + + #[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, + )]); + } + 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::<u32>().cast_const(), + total_bytes / 4, + ) + .to_vec(); + (spent, after_src, out_words) + }; + + 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]); + list.reset(); + } +} diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs new file mode 100644 index 000000000..25461dfad --- /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<u8> = 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<u8> = 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<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("VICTORY_INPLACE_MB").ok().and_then(|v| v.trim().parse::<u64>().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<Placed, Option<windows::core::Error>> { + 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<Placed> { + 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<u64> = 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<ID3D12Heap> { + // 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::<ID3D12Device3>()?.OpenExistingHeapFromAddress(at as *const c_void), + From::Part(at, bytes) => device.cast::<ID3D12Device13>()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), + From::Section(handle) => device.cast::<ID3D12Device3>()?.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<ID3D12Resource> { + let mut placed: Option<ID3D12Resource> = 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<usize, (usize, usize, u64)>, + /// Sections by handle: bytes, and whether made committed. + sections: Vec<(usize, u64, bool)>, +} + +static VIEWS: Mutex<Views> = 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<usize> = 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<usize, (usize, usize, u64)>, 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<T>(result: &windows::core::Result<T>) -> 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<Rig> { + // 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<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let mut buffer: Option<ID3D12Resource> = 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<Vec<u8>> { + 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::<u8>(), 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::<u8>(), 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<ID3DBlob> = 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::<u8>(), 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<f64> { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut to: Option<ID3D12Resource> = 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::<PROCESS_MEMORY_COUNTERS>() 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<String>, + /// 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::<ID3D12Device3>().is_ok(), + device.cast::<ID3D12Device13>().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::<u8>(); + 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<u8> = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); + let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); + let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); + let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + 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::<u8>(); + 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<u8> = (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<u8> = (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<u8> = (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<f64>| 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::<u8>(); + 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<ID3D12Resource> = 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<String> { + 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::<u64>()); + 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<String> { + 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::<u8>(); + 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<ID3D12Device> { + 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::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option<ID3D12Device> = 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::<ID3D12Device13>().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::<ID3D12Device13>().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::<u8>(); + 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 new file mode 100644 index 000000000..db53f110b --- /dev/null +++ b/crates/victory-gpu/src/lib.rs @@ -0,0 +1,66 @@ +//! D3D12.X on host D3D12. +//! +//! D3D12.X records commands from code inlined into the title, which writes +//! packets into the command list while its put pointer is below a limit and +//! calls the list's method otherwise. Our lists keep the limits at zero, so +//! every command arrives here as a call, to be run on host D3D12. The +//! title's GPU addresses are CPU addresses (console memory is unified). +//! +//! [`device`] is the device object titles create, [`dxgi`] its adapter side, +//! [`resource`] heaps and resources, [`fence`] fences, [`queue`] command +//! queues, [`list`] command allocators and lists, [`descriptor`] +//! descriptor heaps, [`root`] root signatures, [`query`] query heaps, +//! [`signature`] command signatures, [`pipeline`] pipeline states, +//! [`frame`] frame pacing, [`object`] what all console graphics objects +//! share, [`console`] which console model the title sees. Planned: +//! `present` (swap chain). + +#[cfg(all(windows, feature = "diagnostics"))] +mod capture; +pub mod console; +#[cfg(all(windows, feature = "diagnostics"))] +mod copystat; +pub mod descriptor; +pub mod device; +#[cfg(windows)] +mod draw; +pub mod dxgi; +pub mod fence; +pub mod frame; +#[cfg(windows)] +mod host; +#[cfg(windows)] +mod indirect; +#[cfg(windows)] +mod inplace; +pub mod list; +pub mod object; +pub mod pipeline; +#[cfg(windows)] +mod primitive; +pub mod query; +pub mod queue; +pub mod resource; +pub mod root; +#[cfg(windows)] +mod sampler; +#[cfg(windows)] +pub mod shader_cache; +#[cfg(windows)] +mod memory; +#[cfg(windows)] +mod shadow; +pub mod signature; +#[cfg(windows)] +mod texture; +#[cfg(windows)] +mod watch; + +#[cfg(windows)] +pub use host::on_failure; +#[cfg(windows)] +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 new file mode 100644 index 000000000..f004b0511 --- /dev/null +++ b/crates/victory-gpu/src/list.rs @@ -0,0 +1,2219 @@ +//! Command allocators and command lists. +//! +//! The title's inlined code writes packets into a list only while its put +//! pointer is below a limit, and calls the list's method otherwise. Our +//! lists keep the pointer and every limit at zero, so every command reaches +//! the table as a call. +//! +//! Each list records onto a host command list as its methods are called +//! (decision 0007); draw state lives in `crate::draw`. Methods not +//! written yet log once with their caller, so a run lists what to do next. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::mem::offset_of; + +use crate::object::{ + self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid, +}; +use crate::queue::Written; +use crate::resource::PAGEABLE_IIDS; + +const ALLOCATOR_IIDS: [Iid; 4] = [ + guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +/// 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 +/// device child's. +const LIST_IIDS: [Iid; 10] = [ + guid( + 0x7116d91c, + 0xe7e4, + 0x47ce, + [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5], + ), + guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ), + guid( + 0x553103fb, + 0x1fe7, + 0x4557, + [0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7], + ), + guid( + 0x38c3e585, + 0xff17, + 0x412c, + [0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28], + ), + guid( + 0x6fda83a7, + 0xb84c, + 0x4e38, + [0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d], + ), + guid( + 0x8754318e, + 0xd3a9, + 0x4541, + [0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74], + ), + guid( + 0x55050859, + 0x4024, + 0x474c, + [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74], + ), + guid( + 0xc3827890, + 0x4024, + 0x474c, + [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74], + ), + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +struct Allocator { + object: Object, + kind: u32, +} + +/// The layout the title's inlined code reads. +#[repr(C)] +struct List { + object: Object, + kind: u32, + /// The put pointer, then the plain, draw, API and unbiased API limits: + /// all zero, so every inline check fails. + put: [u64; 5], + reserved: [u32; 64], + /// State the inline code keeps for building packets; unused by us. + 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 + /// (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. + newer: [u32; 256], + /// Ours, after the console layout: memory handed out by + /// [`allocate_upload`], kept until the list is reset; the host list the + /// calls record into (decision 0007), and the draw state the title set. + uploads: std::sync::Mutex<Vec<Vec<u8>>>, + #[cfg(windows)] + host: Option<crate::host::HostList>, + #[cfg(windows)] + state: std::sync::Mutex<crate::draw::State>, + /// 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<Part>, + /// The waits recorded before the first work of `host`: the queue stands + /// at them before it runs `host`. + #[cfg(windows)] + gate: Vec<ValueWait>, +} + +/// 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<ValueWait>, + host: crate::host::HostList, +} +const _: () = assert!(offset_of!(List, put) == 0x18); +const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); + +/// Runs `f` with the host list and draw state of a title list, if there +/// is a host GPU. +#[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::<List>()).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::<List>() }; + 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. +#[cfg(windows)] +pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { + if this.is_null() { + return None; + } + // SAFETY: the title passes one of our lists. + unsafe { (*this.cast::<List>()).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<Vec<u8>>, + _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<Idle>, 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<bool> = 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<crate::host::HostList> { + 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<Detached>, 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::<List>() }; + 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>() }; + !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<ValueWait>, Vec<Detached>, Vec<usize>)>; + +/// 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::<List>() }; + 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<ValueWait>, 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<Detached>, Vec<usize>) { + 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::<List>(); + // 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, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + let allocator = Box::new(Allocator { + object: Object::new(&ALLOCATOR_FUNCTIONS), + kind, + }); + object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out) +} + +/// Lists start open, as in D3D12. +pub(crate) extern "system" fn create_list( + _: This, + _nodes: u32, + kind: u32, + allocator: This, + pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + new_list(kind, allocator, pipeline, iid, out) +} + +/// The console's list creation: type, flags, node mask and barrier batch +/// size in a description. +#[repr(C)] +#[derive(Debug)] +pub(crate) struct ListDesc { + kind: u32, + flags: u32, + nodes: u32, + barrier_batch: u32, +} + +pub(crate) extern "system" fn create_list_x( + _: This, + desc: *const ListDesc, + allocator: This, + pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "console command list"); + new_list(desc.kind, allocator, pipeline, iid, out) +} + +/// `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; + } + tracing::debug!(kind, "command list"); + let list = Box::new(List { + object: if crate::device::newer() { + Object::new(&NEWER_LIST_FUNCTIONS) + } else { + Object::new(&LIST_FUNCTIONS) + }, + kind, + 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: crate::host::host().and_then(|h| match h.new_list() { + Ok(list) => Some(list), + Err(e) => { + tracing::warn!(error = %e, "no host command list"); + None + } + }), + #[cfg(windows)] + 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) +} + +extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this); + object::answer(ALLOCATOR, iid, found, out) +} +extern "system" fn allocator_release(this: This) -> u32 { + object::release_boxed::<Allocator>(this) +} +/// Nothing is recorded, so there is nothing to free. +extern "system" fn allocator_reset(_: This) -> HRESULT { + S_OK +} + +extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out) +} +extern "system" fn list_release(this: This) -> u32 { + object::release_boxed::<List>(this) +} +extern "system" fn list_type(this: This) -> u32 { + // SAFETY: `this` is one of our lists. + unsafe { (*this.cast::<List>()).kind } +} +extern "system" fn close(this: This) -> HRESULT { + #[cfg(windows)] + if let Some(host) = host_list(this) { + host.close(); + } + 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::<List>()).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>() }; + list.earlier.clear(); + list.gate.clear(); + } + #[cfg(windows)] + with_state(this, |host, state| { + host.reset(); + state.reset(pipeline); + }); + #[cfg(not(windows))] + let _ = (this, pipeline); + S_OK +} + +/// A resource barrier as titles pass it: type, flags, then a resource and +/// either a subresource and two states (transition) or a second resource +/// (aliasing). The same layout as the host's. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct Barrier { + kind: u32, + flags: u32, + first: This, + second: u64, + last: u64, +} + +/// The barrier on host resources, or `None` if it names a resource the host +/// GPU does not have (buffers so far). +#[cfg(windows)] +fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> { + use windows::core::Interface; + let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast()); + match b.kind { + 0 => { + // A split barrier's first half: its second half transitions. + const BEGIN_ONLY: u32 = 1; + if b.flags & BEGIN_ONLY != 0 { + return None; + } + // shortcut: whole resources, from the state the list tracked + // (`HostList::transition`); subresources are not told apart. + let wanted = crate::host::texture_state(b.last as u32); + let (texture, before) = list.transition(b.first, wanted)?; + Some(Barrier { + kind: 0, + flags: 0, + first: texture.as_raw().cast_const().cast(), + second: 0xffff_ffff | (u64::from(before) << 32), + last: u64::from(crate::host::legal_state(texture, wanted)), + }) + } + 1 => Some(Barrier { + first: if b.first.is_null() { + b.first + } else { + host(b.first)? + }, + second: if b.second == 0 { + 0 + } else { + host(b.second as This)? as u64 + }, + ..*b + }), + 2 => Some(Barrier { + first: if b.first.is_null() { + b.first + } else { + // 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 + }), + _ => None, + } +} + +/// An unordered access barrier on every resource: earlier shader writes +/// finish before later work reads or writes. +const UAV_BARRIER: Barrier = Barrier { + kind: 2, + flags: 0, + first: std::ptr::null(), + second: 0, + last: 0, +}; + +/// Returns the console's barrier "actions" (none). +extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { + #[cfg(windows)] + if let Some(list) = host_list(this) + && !barriers.is_null() + { + // SAFETY: the title passes `count` barriers. + let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; + let mut host: Vec<Barrier> = barriers + .iter() + .filter_map(|b| host_barrier(list, b)) + .collect(); + // Buffers have host copies, not resources the barrier can name: + // a barrier on one waits for every shader write before it. + if barriers.iter().any(|b| { + b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() + }) { + host.push(UAV_BARRIER); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1); + } + if !host.is_empty() { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>()); + // SAFETY: the same layout; borrowed resource pointers, never + // released through this slice. + let host = unsafe { + std::slice::from_raw_parts( + host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(), + host.len(), + ) + }; + // SAFETY: an open list and live resources. + unsafe { list.list.ResourceBarrier(host) }; + } + } + 0 +} + +/// Moves a title texture's host copy to `state` in the list, if needed. +#[cfg(windows)] +pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + if let Some((texture, before)) = list.transition(resource, state) { + let state = crate::host::legal_state(texture, state); + let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } +} + +#[cfg(windows)] +const COPY_DEST: u32 = 0x400; +#[cfg(windows)] +const COPY_SOURCE: u32 = 0x800; + +/// `len` bytes at `offset` of a title buffer, if they are inside it. +#[cfg(windows)] +fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> { + let (data, size) = crate::resource::buffer_bytes(buffer)?; + let end = offset.checked_add(len)?; + if end > size { + tracing::warn!(offset, len, size, "copy outside its buffer"); + return None; + } + // SAFETY: inside the buffer, checked above. + Some(unsafe { data.add(offset as usize) }) +} + +/// Buffer to buffer: both are host memory, copied at submission. +extern "system" fn copy_buffer_region( + this: This, + dst: This, + dst_offset: u64, + src: This, + src_offset: u64, + len: u64, +) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let Some(to) = buffer_range(dst, dst_offset, len) + && let Some(from) = buffer_range(src, src_offset, len) + { + list.defer_copy(to, from, len as usize); + } + #[cfg(not(windows))] + 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(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), + ) { + 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); + crate::texture::host_written(dst); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("copy resource {src:?} to {dst:?}")); + // SAFETY: an open list and live textures. + unsafe { list.list.CopyResource(to, from) }; + } else if let (Some((to, a)), Some((from, b))) = ( + crate::resource::buffer_bytes(dst), + crate::resource::buffer_bytes(src), + ) { + list.defer_copy(to, from, a.min(b) as usize); + } + } + #[cfg(not(windows))] + let _ = (this, dst, src); +} + +extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) { + copy_resource(this, dst, src); +} + +/// A copy location as titles pass it, laid out as the host's: a resource, +/// then a subresource index (type 0) or a placed footprint (type 1). +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct CopyLocation { + resource: This, + kind: u32, + footprint: crate::resource::PlacedFootprint, +} + +/// Texture to texture on the GPU; buffer to texture through an upload +/// buffer filled at submission. Texture to buffer (read back) is not done +/// yet. +extern "system" fn copy_texture_region( + this: This, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], +) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION}; + use windows::core::Interface; + const FOOTPRINT: u32 = 1; + // SAFETY: the title passes both locations (null is tolerated). + let (Some(list), Some(&dst), Some(&src)) = + (host_list(this), unsafe { dst.as_ref() }, unsafe { + src.as_ref() + }) + else { + return; + }; + 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`). Grand Theft + // Auto VI 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; + }; + if unlike(dst.resource, src.resource) { + return; + } + let mut from = src; + let _upload; // keeps the source alive while this call records it + #[cfg(feature = "diagnostics")] + let mut read = None; + if src.kind == FOOTPRINT { + let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else { + return; + }; + let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else { + return; + }; + let Some((buffer, staging)) = list.upload(host, bytes) else { + return; + }; + // The list owns this mapped D3D12 upload buffer. Wine can report + // its address as MEM_FREE, so use the host-upload path. + list.defer_fill(staging, data, bytes as usize); + from.resource = buffer.as_raw().cast_const().cast(); + from.footprint.offset = 0; + #[cfg(feature = "diagnostics")] + { + // SAFETY: a live buffer. + read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes)); + } + _upload = buffer; + } else { + let Some(texture) = crate::resource::host_resource(src.resource) else { + return; + }; + 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::<D3D12_BOX>()); + #[cfg(feature = "diagnostics")] + { + let text = || { + // SAFETY: a live texture; the box is the title's or null. + let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) }; + format!( + "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}", + dst.resource, + d.Width, + d.Height, + d.Format.0, + dst.kind, + src.resource, + src.kind, + (src.kind == FOOTPRINT).then_some(src.footprint) + ) + }; + match read { + Some(range) => list.note_read(text, range), + None => list.note_op(text), + } + } + const _: () = + assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>()); + // SAFETY: an open list; both locations in the host's layout, naming + // live resources; the box is the title's (same layout). + unsafe { + list.list.CopyTextureRegion( + (&raw const to_location).cast(), + x, + y, + z, + (&raw const from).cast(), + host_box, + ) + }; + } + #[cfg(not(windows))] + 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<bool> = 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::<D3D12_BOX>()); + #[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, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], + _flags: u32, +) { + copy_texture_region(this, dst, x, y, z, src, source_box); +} + +extern "system" fn resolve( + this: This, + dst: This, + dst_sub: u32, + src: This, + src_sub: u32, + format: u32, +) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let (Some(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), + ) + { + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1, + }; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + 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); + #[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 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::<ID3D12GraphicsCommandList1>() { + // The console clips a larger source to the destination. + let rect = RECT { + left: 0, + top: 0, + right: a.Width.min(b.Width) as i32, + bottom: a.Height.min(b.Height) as i32, + }; + list1.ResolveSubresourceRegion( + to, + dst_sub, + 0, + 0, + from, + src_sub, + Some(&rect), + format, + D3D12_RESOLVE_MODE_AVERAGE, + ); + } + } + } + #[cfg(not(windows))] + let _ = (this, dst, dst_sub, src, src_sub, format); +} + +#[repr(C)] +pub(crate) struct Rect { + left: i32, + top: i32, + right: i32, + bottom: i32, +} + +extern "system" fn clear_rtv( + this: This, + handle: u64, + color: *const [f32; 4], + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + { + let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle)) + else { + return; + }; + let (Some(texture), Some(host)) = ( + crate::resource::host_resource(record.resource), + crate::host::host(), + ) else { + return; + }; + // SAFETY: the title passes four floats (null is tolerated). + let Some(color) = (unsafe { color.as_ref() }) else { + return; + }; + let rects = (count > 0 && !rects.is_null()).then(|| { + // SAFETY: the title passes `count` rectangles, laid out as the host's. + unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } + }); + const RENDER_TARGET: u32 = 0x4; + let rtv = host.rtv(Some(texture), record.desc().as_ref()); + // SAFETY: an open list, a fresh view of a live texture. + 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); +} + +/// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`; +/// flags: 1 depth, 2 stencil. +extern "system" fn clear_dsv( + this: This, + handle: u64, + flags: u32, + depth: f32, + stencil: u8, + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS; + let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle)) + else { + return; + }; + let (Some(texture), Some(host)) = ( + crate::resource::host_resource(record.resource), + crate::host::host(), + ) else { + return; + }; + let rects = (count > 0 && !rects.is_null()).then(|| { + // SAFETY: the title passes `count` rectangles, laid out as the host's. + 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()); + // 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) + }; + } + #[cfg(not(windows))] + let _ = (this, handle, flags, depth, stencil, count, rects); +} + +/// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses +/// are title memory, copied at submission like buffer copies (if mapped). +extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && dst != 0 + && src != 0 + { + let len = len as usize; + list.defer(move || { + if crate::texture::committed(src as *const u8, len) + && crate::texture::committed(dst as *const u8, len) + { + // SAFETY: both ranges are committed title memory. + unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) }; + } + }); + } + #[cfg(not(windows))] + let _ = (this, dst, src, len); +} + +/// `DriverHintX(feature, value)`: no hints for the host. +extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 { + 0 +} + +/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the +/// host has no use for (the ray-tracing builder dispatches this way). +extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) { + #[cfg(windows)] + state::dispatch(this, x, y, z); + #[cfg(not(windows))] + { + let _ = (this, x, y, z); + count_dispatch(); + } +} + +/// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when +/// resolved. +extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {} + +/// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes +/// each query's result into the buffer once the list has run. Timestamps +/// (type 2) are the GPU clock then; occlusion counts (0) say a million +/// samples passed and binary occlusion (1) visible, so nothing is culled +/// by a query. +/// shortcut: no query runs on the host GPU; results are plausible values, +/// not measured ones (time spans come out as the submission's length). +extern "system" fn resolve_queries( + this: This, + _heap: This, + kind: u32, + _first: u32, + count: u32, + buffer: This, + offset: u64, +) { + const OCCLUSION: u32 = 0; + const BINARY: u32 = 1; + const TIMESTAMP: u32 = 2; + const PIPELINE_STATISTICS: u32 = 3; + let Some((data, size)) = crate::resource::buffer_bytes(buffer) else { + return; + }; + let (what, bytes) = match kind { + OCCLUSION => (Written::Value(1 << 20), 8), + BINARY => (Written::Value(1), 8), + TIMESTAMP => (Written::GpuTimestamp, 8), + PIPELINE_STATISTICS => (Written::Value(0), 88), + _ => (Written::Value(0), 16), + }; + if offset + u64::from(count) * bytes > size { + return; + } + for i in 0..u64::from(count) { + // Wider results are written as 8-byte pieces. + for piece in 0..bytes / 8 { + // SAFETY: inside the buffer, checked above. + let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) }; + let what = if piece == 0 { what } else { Written::Value(0) }; + defer_write(this, at as u64, what, 8); + } + } +} + +/// IUnknown 3, object 4, device child 1, allocator 2. +static ALLOCATOR_FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>()); + f[0] = allocator_query as *const (); + f[2] = allocator_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = allocator_reset as *const (); // 0x40 + f[9] = object::ignore as *const (); // 0x48 allocation callback + Table(f) +}; + +extern "system" fn set_pipeline(this: This, pipeline: This) { + crate::pipeline::bound(pipeline); + #[cfg(windows)] + with_state(this, |_, state| state.set_pipeline(pipeline)); + #[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)`. 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. +extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT { + reset(this, allocator, pipeline) +} + +/// 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 +/// 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 { + return std::ptr::null_mut(); + }; + if this.is_null() || !align.is_power_of_two() { + return std::ptr::null_mut(); + } + let mut block = vec![0u8; len]; + let start = block.as_mut_ptr(); + // SAFETY: the offset is below `align`, so `size` bytes fit after it. + let at = unsafe { start.add(start.align_offset(align)) }; + // SAFETY: the title passes one of our lists. + let uploads = unsafe { &(*this.cast::<List>()).uploads }; + // Moving the vector keeps its heap block where it is. + 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 order and shading rate hints): any arguments, +/// nothing returned. +extern "system" fn ignored_state(_: This) {} + +/// Depth bounds `(min, max)`. +/// shortcut: not set on the host list (no host pipeline of ours enables +/// the test, `pipeline::host`); the first values are logged, so a run +/// shows whether the title uses the test at all. +extern "system" fn depth_bounds(_: This, min: f32, max: f32) { + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 { + tracing::info!(min, max, "the title sets depth bounds, which the host is not given"); + } +} + +/// 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, with_state}; + use crate::draw::{IndexView, VertexView}; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; + + /// `count` items at `items`, or none. + fn items<'a, T>(items: *const T, count: u32) -> &'a [T] { + if items.is_null() || count == 0 { + return &[]; + } + // SAFETY: the title passes `count` items. + unsafe { std::slice::from_raw_parts(items, count as usize) } + } + + pub(super) extern "system" fn topology(this: This, topology: u32) { + with_state(this, |list, s| s.set_topology(list, topology)); + } + pub(super) extern "system" fn viewports( + this: This, + count: u32, + viewports: *const D3D12_VIEWPORT, + ) { + // (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) { + 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]) { + with_state(this, |list, s| { + // SAFETY: the title passes four floats or null. + s.set_blend_factor(list, unsafe { factor.as_ref() }) + }); + } + pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { + with_state(this, |list, s| s.set_stencil_ref(list, reference)); + } + pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { + with_state(this, |_, s| s.set_heaps(items(heaps, count))); + } + pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) { + with_state(this, |_, s| s.set_table(true, slot, handle)); + } + pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) { + with_state(this, |_, s| s.set_table(false, slot, handle)); + } + pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) { + with_state(this, |_, s| s.set_constants(true, slot, &[value], offset)); + } + pub(super) extern "system" fn graphics_constant( + this: This, + slot: u32, + value: u32, + offset: u32, + ) { + with_state(this, |_, s| s.set_constants(false, slot, &[value], offset)); + } + pub(super) extern "system" fn compute_constants( + this: This, + slot: u32, + count: u32, + values: *const u32, + offset: u32, + ) { + with_state(this, |_, s| { + s.set_constants(true, slot, items(values, count), offset) + }); + } + pub(super) extern "system" fn graphics_constants( + this: This, + slot: u32, + count: u32, + values: *const u32, + offset: u32, + ) { + with_state(this, |_, s| { + s.set_constants(false, slot, items(values, count), offset) + }); + } + /// Root constant buffer, shader resource and unordered access views. + pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) { + with_state(this, |_, s| s.set_view(true, slot, address)); + } + pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) { + with_state(this, |_, s| s.set_view(false, slot, address)); + } + pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) { + // SAFETY: the title passes a view or null. + with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() })); + } + pub(super) extern "system" fn vertex_buffers( + this: This, + start: u32, + count: u32, + views: *const VertexView, + ) { + with_state(this, |_, s| { + if views.is_null() { + s.clear_vertex_buffers(start, count); + } else { + s.set_vertex_buffers(start, items(views, count)); + } + }); + } + /// `(count, handles, one range, depth)`: with one range, the handles + /// follow the first at the render target view size (128 bytes). + pub(super) extern "system" fn targets( + this: This, + count: u32, + handles: *const u64, + one_range: i32, + depth: *const u64, + ) { + let handles: Vec<u64> = if one_range != 0 && !handles.is_null() { + // SAFETY: the title passes the first handle. + let first = unsafe { *handles }; + (0..u64::from(count)).map(|i| first + 128 * i).collect() + } else { + items(handles, count).to_vec() + }; + // SAFETY: the title passes a handle or null. + let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0); + with_state(this, |list, s| s.set_targets(list, &handles, depth)); + } + pub(super) extern "system" fn draw( + this: This, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, + ) { + super::count_draw(); + with_state(this, |list, s| { + s.draw(list, vertices, instances, first, first_instance) + }); + } + pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) { + super::count_dispatch(); + with_state(this, |list, s| s.dispatch(list, x, y, z)); + } + /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh + /// programs take `x` groups only. + pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) { + super::count_draw(); + if y * z != 1 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups")); + } + with_state(this, |list, s| s.dispatch_mesh(list, x)); + } + /// `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, + _flags: u64, + indirect: u64, + _payload: u64, + ) { + super::count_draw(); + if indirect != 0 { + 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)); + } + pub(super) extern "system" fn draw_indexed( + this: This, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, + ) { + super::count_draw(); + with_state(this, |list, s| { + s.draw_indexed(list, indices, instances, first, base, first_instance) + }); + } +} + +/// Without a host GPU every draw state call is ignored. +#[cfg(not(windows))] +mod state { + pub(super) use super::dispatch; + pub(super) use super::draw; + pub(super) use super::draw as draw_indexed; + pub(super) use super::draw as dispatch_mesh; + pub(super) use super::draw as dispatch_mesh_x; + pub(super) use super::ignored_state as blend_factor; + pub(super) use super::ignored_state as compute_constant; + pub(super) use super::ignored_state as compute_constants; + pub(super) use super::ignored_state as compute_table; + pub(super) use super::ignored_state as compute_view; + pub(super) use super::ignored_state as graphics_constant; + pub(super) use super::ignored_state as graphics_constants; + pub(super) use super::ignored_state as graphics_table; + pub(super) use super::ignored_state as graphics_view; + 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 stencil_ref; + 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; + pub(super) use super::ignored_state as viewports; +} + +fn count_draw() { + DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Draws of the kinds the host does not run yet (indirect, mesh), and +/// dispatches, counted per frame for the log. +/// shortcut: dropped until their shaders translate (decision 0007). +#[cfg(not(windows))] +extern "system" fn draw(_: This) { + count_draw(); +} + +/// `ExecuteIndirect(signature, max count, arguments, offset, count buffer, +/// offset)`. Grand Theft Auto VI'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 +/// signature, the title passes none), run as a plain dispatch. They run +/// through the host's indirect execution (`State::execute_indirect`). +/// shortcut: signatures that change root arguments are dropped (logged +/// once per signature). +extern "system" fn execute_indirect( + this: This, + signature: This, + max: u32, + arguments: This, + offset: u64, + count: This, + count_offset: u64, +) { + count_draw(); + let Some((stride, args)) = crate::signature::layout(signature) else { + return; + }; + let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset); + let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); + let mut 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 }; + with_state(this, |list, s| { + ran = s.execute_indirect(list, (kind, stride, max), address, counter); + }); + } else { + #[cfg(all(windows, feature = "diagnostics"))] + crate::pipeline::note_why(format!( + "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}", + address.is_some(), + count.is_null() || counter.is_some() + )); + } + if ran { + return; + } + INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&(signature as usize)) { + seen.push(signature as usize); + tracing::info!( + stride, + ?args, + max, + address = ?address.map(|a| format!("{a:#x}")), + counted = !count.is_null(), + "indirect execution dropped (first time for this signature)" + ); + } +} + +/// Indirect executions dropped since the last call. +pub(crate) fn take_indirect() -> u64 { + INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed) +} +static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +fn count_dispatch() { + DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} +#[cfg(not(windows))] +extern "system" fn dispatch(_: This) { + count_dispatch(); +} +static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Draws (any kind, mesh and indirect included) and compute dispatches +/// recorded since the last call. +pub(crate) fn take_counts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) +} + +/// 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 (Grand Theft Auto VI 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<bool> = 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<Vec<(usize, ValueWait)>> = 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 (Grand Theft Auto VI: 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<ValueWait> { + 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<Vec<ValueWait>> { + 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 +/// title texture (clears, copies) moves its host copy to the state it needs +/// 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 { + 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::<Barrier, D3D12_RESOURCE_BARRIER>(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 +/// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the +/// 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; + const SYSTEM_TIMESTAMP: u32 = 2; + let what = match flags { + GPU_TIMESTAMP => Written::GpuTimestamp, + SYSTEM_TIMESTAMP => Written::SystemTimestamp, + _ => 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 +/// (Grand Theft Auto VI: 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<bool> = 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::<List>() }; + 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) { + if address == 0 { + return; + } + #[cfg(windows)] + if let Some(list) = host_list(this) { + list.defer_write(address as *mut u8, what, bytes); + return; + } + let _ = this; + // Without a host GPU nothing runs later: write now. + what.write(address as *mut u8, bytes); +} + +/// The list methods by their slot in older titles' lists (the 2020-era +/// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 +/// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 +/// + 13): 140 slots. +const METHODS: [(usize, *const ()); 52] = [ + (0, list_query as *const ()), + (2, list_release as *const ()), + (7, object::parent_device as *const ()), // 0x38 + (8, list_type as *const ()), // 0x40 + (9, close as *const ()), // 0x48 + (10, reset as *const ()), // 0x50 + (12, state::draw as *const ()), // 0x60 instanced + (13, state::draw_indexed as *const ()), // 0x68 indexed + (14, state::dispatch as *const ()), // 0x70 + (15, copy_buffer_region as *const ()), // 0x78 + (16, copy_texture_region as *const ()), // 0x80 + (17, copy_resource as *const ()), // 0x88 + (19, resolve as *const ()), // 0x98 + (20, state::topology as *const ()), // 0xa0 + (21, state::viewports as *const ()), // 0xa8 + (22, state::scissors as *const ()), // 0xb0 + (23, state::blend_factor as *const ()), // 0xb8 + (24, state::stencil_ref as *const ()), // 0xc0 + (25, set_pipeline as *const ()), // 0xc8 + (26, barrier as *const ()), // 0xd0 + (32, state::heaps as *const ()), // 0x100 + (33, ignored_state as *const ()), // 0x108 compute root signature + (34, ignored_state as *const ()), // 0x110 graphics root signature + (35, state::compute_table as *const ()), // 0x118 + (36, state::graphics_table as *const ()), // 0x120 + (37, state::compute_constant as *const ()), // 0x128 + (38, state::graphics_constant as *const ()), // 0x130 + (39, state::compute_constants as *const ()), // 0x138 + (40, state::graphics_constants as *const ()), // 0x140 + (41, state::compute_view as *const ()), // 0x148 CBV + (42, state::graphics_view as *const ()), // 0x150 CBV + (43, state::compute_view as *const ()), // 0x158 SRV + (44, state::graphics_view as *const ()), // 0x160 SRV + (45, state::compute_view as *const ()), // 0x168 UAV + (46, state::graphics_view as *const ()), // 0x170 UAV + (47, state::index_buffer as *const ()), // 0x178 + (48, state::vertex_buffers as *const ()), // 0x180 + (50, state::targets as *const ()), // 0x190 + (51, clear_dsv as *const ()), // 0x198 + (52, clear_rtv as *const ()), // 0x1a0 + (59, execute_indirect as *const ()), // 0x1d8 indirect + (60, copy_memory as *const ()), // 0x1e0 + (68, depth_bounds as *const ()), // 0x220 depth bounds + (69, write32 as *const ()), // 0x228 + (70, write64 as *const ()), // 0x230 + (71, wait_value as *const ()), // 0x238, 32 bits + (72, wait_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 + (124, ignored_state as *const ()), // 0x3e0 shading rate + (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch +]; +/// The rest of [`METHODS`], kept apart only to stay readable. +const MORE_METHODS: [(usize, *const ()); 9] = [ + (28, query_mark as *const ()), // 0xe0 BeginQuery + (29, query_mark as *const ()), // 0xe8 EndQuery + (30, resolve_queries as *const ()), // 0xf0 + (78, dispatch_x as *const ()), // 0x270 + (98, state::dispatch_mesh_x as *const ()), // 0x310 + (99, driver_hint as *const ()), // 0x318 + // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410. + (129, sync as *const ()), + (130, sync as *const ()), + (137, reset_x as *const ()), // 0x448 +]; + +/// Newer titles' lists have two more methods in the console part of the +/// 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 +/// 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 { + if slot >= 59 { slot + 2 } else { slot } +} + +/// 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. +/// shortcut: 0x470's purpose is unknown; ignored until a title shows it +/// matters. +const NEWER_METHODS: [(usize, *const ()); 3] = [ + (142, ignored_state as *const ()), + (146, barrier_groups as *const ()), + (148, allocate_upload as *const ()), +]; + +const fn list_table(newer: bool) -> [*const (); 160] { + let mut f = object::d3d12_object(object::missing_table::<LIST, 160>()); + let mut i = 0; + while i < METHODS.len() + MORE_METHODS.len() { + let (slot, method) = if i < METHODS.len() { + METHODS[i] + } else { + MORE_METHODS[i - METHODS.len()] + }; + f[if newer { newer_slot(slot) } else { slot }] = method; + i += 1; + } + let mut i = 0; + while newer && i < NEWER_METHODS.len() { + f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1; + i += 1; + } + f +} + +/// Every slot up to the limit exists and logs, for the methods newer +/// titles add. +static LIST_FUNCTIONS: Table<160> = Table(list_table(false)); +static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true)); + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + #[test] + fn every_inline_command_falls_back_to_the_table() { + 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; + let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list); + assert_eq!(hr, S_OK); + // What the title's inline draw checks: put < draw limit. + // SAFETY: the list is 0x560 bytes. + let (put, draw_limit, api_limit) = unsafe { + let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read(); + (at(0x18), at(0x28), at(0x30)) + }; + assert!(put >= draw_limit && put >= api_limit); + // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks. + let mut same = null; + assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK); + assert_eq!(same, list); + assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1); + assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0); + assert_eq!( + slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list), + S_OK + ); + // List-owned upload memory: aligned, writable, gone at reset. + let p = allocate_upload(list, 40, 0x100); + 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); + // SAFETY: the list is ours. + assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty()); + let release = |o: This| slot::<extern "system" fn(This) -> 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 000000000..c25636783 --- /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<Arc<Shadow>>, + /// Per host view heap (by address): the first slot of its run, and how + /// many copies have their view there. + heaps: HashMap<usize, (u32, u32)>, + /// 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<u64>, +} + +// SAFETY: the mappings are of buffers the struct owns; all access is under +// the mutex. +unsafe impl Send for Memory {} + +static MEMORY: Mutex<Option<Memory>> = 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<Memory> { + 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::<u32>(), 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<Shadow>| 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<Ready> { + 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/object.rs b/crates/victory-gpu/src/object.rs new file mode 100644 index 000000000..156c92ded --- /dev/null +++ b/crates/victory-gpu/src/object.rs @@ -0,0 +1,384 @@ +//! What every console graphics object starts with: a function table +//! pointer, bookkeeping bits and a reference count. Tables begin with +//! IUnknown's three slots. Our objects are static and never destroyed. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +pub type HRESULT = i32; +pub const S_OK: HRESULT = 0; +pub(crate) const S_FALSE: HRESULT = 1; +pub(crate) const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +pub(crate) const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +pub(crate) const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +pub(crate) const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; +pub(crate) const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// What D3D and DXGI return for a missing item (adapter, output, private +/// data). +pub(crate) const NOT_FOUND: HRESULT = 0x887A_0002_u32 as i32; +pub(crate) const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32; + +pub type Iid = [u8; 16]; + +/// An interface id from its text form's fields, in memory order. +pub const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> Iid { + let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes()); + [ + a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6], + d[7], + ] +} + +pub fn guid_text(g: &Iid) -> String { + let a = u32::from_le_bytes([g[0], g[1], g[2], g[3]]); + let b = u16::from_le_bytes([g[4], g[5]]); + let c = u16::from_le_bytes([g[6], g[7]]); + let d: String = g[8..].iter().map(|x| format!("{x:02x}")).collect(); + format!("{a:08x}-{b:04x}-{c:04x}-{}-{}", &d[..4], &d[4..]) +} + +#[repr(C)] +pub struct Object { + functions: *const *const (), + /// Device index (bits 0-2) and bookkeeping bits; all zero. + bits: u32, + refs: AtomicU32, +} +// SAFETY: the table is static and immutable; the count is atomic. +unsafe impl Sync for Object {} + +impl Object { + pub(crate) const fn new<const N: usize>(table: &'static Table<N>) -> Self { + Object { + functions: table.0.as_ptr(), + bits: 0, + refs: AtomicU32::new(0), + } + } +} + +pub(crate) type This = *const Object; + +#[repr(transparent)] +pub(crate) struct Table<const N: usize>(pub [*const (); N]); +// SAFETY: function addresses only. +unsafe impl<const N: usize> Sync for Table<N> {} + +pub(crate) extern "system" fn add_ref(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +pub(crate) extern "system" fn release(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + let refs = &unsafe { &*this }.refs; + let _ = refs.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1)); + refs.load(Ordering::Relaxed) +} + +/// Answers an interface query (or any call handing out an object): a new +/// reference to `found`, or null and `E_NOINTERFACE`. +pub(crate) fn answer(kind: usize, iid: *const Iid, found: Option<This>, out: *mut This) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + let hr = match found { + Some(object) => { + add_ref(object); + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(object) }; + return S_OK; + } + None => E_NOINTERFACE, + }; + // SAFETY: the title passes an interface id (null is tolerated). + let iid = unsafe { iid.as_ref() }.map(guid_text).unwrap_or_default(); + tracing::warn!(object = KINDS[kind], %iid, "unknown interface"); + // SAFETY: checked non-null. + unsafe { out.write(std::ptr::null()) }; + hr +} + +/// Whether `iid` is one of `known`. +pub(crate) fn is(iid: *const Iid, known: &[Iid]) -> bool { + // SAFETY: the title passes an interface id (null is tolerated). + unsafe { iid.as_ref() }.is_some_and(|i| known.contains(i)) +} + +/// Hands a new object to the title as one of `known`, or drops it. `T` +/// starts with its `Object`; its table's release slot is +/// [`release_boxed::<T>`]. +pub(crate) fn hand_out<T>( + kind: usize, + object: Box<T>, + iid: *const Iid, + known: &[Iid], + out: *mut This, +) -> HRESULT { + if !is(iid, known) { + return answer(kind, iid, None, out); + } + if out.is_null() { + // Asked only whether creation would succeed. + return S_FALSE; + } + answer(kind, iid, Some(Box::into_raw(object).cast()), out) +} + +/// Release for objects made by [`hand_out`]: the last reference frees it. +pub(crate) fn release_boxed<T>(this: This) -> u32 { + // SAFETY: `this` is the header of a boxed `T`. + let refs = &unsafe { &*this }.refs; + match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) { + Ok(1) => { + private_data().retain(|&(object, _), _| object != this as usize); + // SAFETY: that was the last reference to a `Box<T>`. + drop(unsafe { Box::from_raw(this.cast_mut().cast::<T>()) }); + 0 + } + Ok(n) => n - 1, + Err(_) => 0, + } +} + +/// Private data of every object, by object address and id. +static PRIVATE: Mutex<BTreeMap<(usize, Iid), Vec<u8>>> = Mutex::new(BTreeMap::new()); + +fn private_data() -> std::sync::MutexGuard<'static, BTreeMap<(usize, Iid), Vec<u8>>> { + PRIVATE.lock().unwrap_or_else(|e| e.into_inner()) +} + +extern "system" fn get_private_data( + this: This, + id: *const Iid, + size: *mut u32, + data: *mut u8, +) -> HRESULT { + // SAFETY: the title passes an id and its buffer size (null is tolerated). + let (Some(id), Some(size)) = (unsafe { (id.as_ref(), size.as_mut()) }) else { + return E_INVALIDARG; + }; + let map = private_data(); + let Some(value) = map.get(&(this as usize, *id)) else { + *size = 0; + return NOT_FOUND; + }; + let len = value.len() as u32; + let room = std::mem::replace(size, len); + if data.is_null() { + return S_OK; + } + if room < len { + return MORE_DATA; + } + // SAFETY: the buffer holds `room` >= `len` bytes. + unsafe { data.copy_from_nonoverlapping(value.as_ptr(), value.len()) }; + S_OK +} + +/// Null data removes the entry. +extern "system" fn set_private_data( + this: This, + id: *const Iid, + size: u32, + data: *const u8, +) -> HRESULT { + // SAFETY: the title passes an id (null is tolerated). + let Some(&id) = (unsafe { id.as_ref() }) else { + return E_INVALIDARG; + }; + let mut map = private_data(); + if data.is_null() { + map.remove(&(this as usize, id)); + } else { + // SAFETY: the title passes `size` bytes. + let value = unsafe { std::slice::from_raw_parts(data, size as usize) }; + map.insert((this as usize, id), value.to_vec()); + } + S_OK +} + +/// Fills a D3D12 table's object methods: private data and name (setting +/// an interface as private data stays unwritten). +pub(crate) const fn d3d12_object<const N: usize>(mut f: [*const (); N]) -> [*const (); N] { + f[3] = get_private_data as *const (); // 0x18 + f[4] = set_private_data as *const (); // 0x20 + f[6] = set_name as *const (); // 0x30 + f +} + +/// The object methods' name setter: names only reach our log. +pub(crate) extern "system" fn set_name(this: This, name: *const u16) -> HRESULT { + let name = if name.is_null() { + String::new() + } else { + // SAFETY: a non-null name is NUL-terminated UTF-16. + let len = (0..).take_while(|&i| unsafe { *name.add(i) } != 0).count(); + // SAFETY: `len` units were just read. + String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(name, len) }) + }; + tracing::debug!(object = ?this, %name, "named"); + S_OK +} + +/// The device-child method: the device that made the object, as any of +/// the interfaces the device itself answers to. +pub(crate) extern "system" fn parent_device(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + let device = crate::device::device(); + answer( + DEVICE, + iid, + crate::device::is_device(iid).then_some(device), + out, + ) +} + +pub(crate) const DEVICE: usize = 0; +pub(crate) const DXGI_DEVICE: usize = 1; +pub(crate) const ADAPTER: usize = 2; +pub(crate) const FACTORY: usize = 3; +pub(crate) const OUTPUT: usize = 4; +pub(crate) const HEAP: usize = 5; +pub(crate) const RESOURCE: usize = 6; +pub(crate) const FENCE: usize = 7; +pub(crate) const QUEUE: usize = 8; +pub(crate) const ALLOCATOR: usize = 9; +pub(crate) const LIST: usize = 10; +pub(crate) const DESCRIPTOR_HEAP: usize = 11; +pub(crate) const ROOT_SIGNATURE: usize = 12; +pub(crate) const QUERY_HEAP: usize = 13; +pub(crate) const COMMAND_SIGNATURE: usize = 14; +pub(crate) const PIPELINE: usize = 15; +const KINDS: [&str; 16] = [ + "device", + "DXGI device", + "adapter", + "factory", + "output", + "heap", + "resource", + "fence", + "command queue", + "command allocator", + "command list", + "descriptor heap", + "root signature", + "query heap", + "command signature", + "pipeline state", +]; + +const MAX_SLOTS: usize = 160; + +/// Which unwritten slots have been reported; each is logged once. +static REPORTED: [[AtomicBool; MAX_SLOTS]; KINDS.len()] = + [const { [const { AtomicBool::new(false) }; MAX_SLOTS] }; KINDS.len()]; + +/// Logged once per slot, with the caller's offset in its module (the title +/// image for title calls). Wrong for a slot that returns a value instead of +/// an `HRESULT`. +extern "system" fn missing<const KIND: usize, const SLOT: usize>() -> HRESULT { + if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) { + tracing::warn!( + object = KINDS[KIND], + slot = format_args!("{:#x}", SLOT * 8), + caller = caller(), + "method not implemented" + ); + } + E_NOTIMPL +} + +/// The return address of whoever called our caller, as `+offset` into its +/// module. +#[inline(never)] +fn caller() -> String { + #[cfg(windows)] + { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleHandleExW, + }; + let mut frame = std::ptr::null_mut(); + // SAFETY: room for one frame; skips this function and its caller. + if unsafe { RtlCaptureStackBackTrace(2, 1, &mut frame, std::ptr::null_mut()) } == 1 { + let mut module = std::ptr::null_mut(); + // SAFETY: looks up the module holding the address, no reference. + let found = unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS + | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + frame as *const u16, + &mut module, + ) + }; + if found != 0 { + return format!("+{:#x}", frame as usize - module as usize); + } + return format!("{frame:?}"); + } + } + String::new() +} + +/// Accepts and ignores (debug-only settings). +pub(crate) extern "system" fn ignore() -> HRESULT { + S_OK +} + +macro_rules! missing { + ($kind:ident; $($slot:literal)*) => { [$(missing::<$kind, $slot> as *const ()),*] }; +} + +/// A table of `N` slots that log and fail; callers fill in what they have. +/// Tables are made longer than the interfaces we know, so that a method a +/// newer title adds logs instead of jumping into whatever follows the table. +pub(crate) const fn missing_table<const KIND: usize, const N: usize>() -> [*const (); N] { + let all = missing!(KIND; + 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 150 151 152 153 154 155 156 157 + 158 159 + ); + assert!(N <= all.len()); + let mut table = [std::ptr::null(); N]; + let mut i = 0; + while i < N { + table[i] = all[i]; + i += 1; + } + table[1] = add_ref as *const (); + table[2] = release as *const (); + table +} + +#[cfg(test)] +pub(crate) fn slot<F: Copy>(object: This, offset: usize) -> F { + // SAFETY: `object` is ours and its table has the slot. + let f = unsafe { *(*object).functions.add(offset / 8) }; + // SAFETY: the caller names the slot's signature. + unsafe { std::mem::transmute_copy(&f) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn guids_round_trip_through_text() { + let g = guid( + 0x189819f1, + 0x1db6, + 0x4b57, + [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], + ); + assert_eq!(g[..4], [0xf1, 0x19, 0x98, 0x18]); + assert_eq!(guid_text(&g), "189819f1-1db6-4b57-be54-1821339b85f7"); + } +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs new file mode 100644 index 000000000..2510fd27d --- /dev/null +++ b/crates/victory-gpu/src/pipeline.rs @@ -0,0 +1,843 @@ +//! Pipeline states. Both descriptions start as on PC: the root signature, +//! then the shader stages (five for graphics, one for compute); streams +//! carry the rest of the graphics state as subobjects of the standard +//! 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 +//! 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). +//! +//! shortcut: only vertex plus pixel pipelines from streams and compute +//! pipelines get host pipelines; mesh, tessellation and geometry stages, +//! and the plain graphics description, keep their containers only. The 32-byte +//! packet after the header stays zero: titles only copy it inline, which +//! our null command-list limits keep from running. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::HashMap; +use std::mem::offset_of; +use std::sync::{Arc, Mutex, OnceLock}; + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const PIPELINE_IIDS: [Iid; 4] = [ + guid( + 0x765a30f3, + 0xf624, + 0x4c6f, + [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +pub(crate) struct Bytecode { + code: *const u8, + size: usize, +} + +#[repr(C)] +pub(crate) struct GraphicsHead { + root: This, + /// Vertex, pixel, domain, hull, geometry. + stages: [Bytecode; 5], +} + +#[repr(C)] +pub(crate) struct ComputeHead { + root: This, + stage: Bytecode, +} + +/// A shader container a title passed, shared by every pipeline with the +/// same bytes. +pub(crate) struct Shader { + pub(crate) stage: &'static str, + /// The first 8 bytes of its BLAKE3, as logged. + pub(crate) hash: String, + container: Vec<u8>, + #[cfg(windows)] + translated: OnceLock<Option<Translated>>, +} + +impl std::fmt::Debug for Shader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} {}", self.stage, self.hash) + } +} + +/// Every container seen, by full content hash. +static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = 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<Shader> { + let full = blake3::hash(bytes); + let mut shaders = SHADERS.lock().unwrap_or_else(|e| e.into_inner()); + shaders + .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(), + container: bytes.to_vec(), + #[cfg(windows)] + translated: OnceLock::new(), + }) + }) + .clone() +} + +/// A translated shader and the console resources its code reads. +#[cfg(windows)] +pub(crate) struct Translated { + pub(crate) host: victory_shader::emit::HostShader, + pub(crate) used: Vec<victory_shader::UsedResource>, + /// 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 { + /// 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); + // `VICTORY_SHADER_SAVE=<dir>`: 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, + hash = %self.hash, + user_data = t.host.user_data.len(), + samplers = t.host.samplers.len(), + "shader translated" + ), + Err(e) => tracing::warn!( + stage = self.stage, + hash = %self.hash, + error = %e, + "shader does not translate; its pipelines' draws are dropped" + ), + } + done.ok() + }) + .as_ref() + } +} + +#[cfg(windows)] +fn translate(container: &[u8]) -> Result<Translated, String> { + use victory_shader::{Container, FourCC, HwStage}; + // The translation depends on it (a view index past a capped heap). + crate::descriptor::host::probe_view_limit(); + let c = Container::parse(container).map_err(|e| e.to_string())?; + let programs = match c.part(FourCC::DXIL) { + Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?, + None => Vec::new(), + }; + let host = crate::shader_cache::host_shader(container)?; + let stores = programs.is_empty() || programs.iter().any(stores); + let used = programs + .into_iter() + .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<Arc<make::Pending>>, + /// Every one of `pipelines` has a host pipeline. + whole: bool, + /// One could not be made. + off: bool, +} + +#[cfg(windows)] +static BUILDER: Mutex<Builder> = 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<Shader>]) -> 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<bool> = 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<bool> = 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)] +struct Pipeline { + object: Object, + packet: [u32; 8], + /// Each used stage's container. + shaders: Vec<Arc<Shader>>, + /// Whether a list has bound it yet (its shaders are logged then). + bound: std::sync::atomic::AtomicBool, + /// What its host pipeline is made from, and the host pipeline once made + /// (by a worker: the title may release the pipeline meanwhile). + #[cfg(windows)] + host: Arc<make::Pending>, + /// One of the ray-tracing structure builder's ([`Builder`]). + #[cfg(windows)] + builder: bool, +} +const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); + +/// Stage names, in description order. +const GRAPHICS_STAGES: [&str; 5] = ["vertex", "pixel", "domain", "hull", "geometry"]; + +fn pipeline<'a>(this: This) -> &'a Pipeline { + // SAFETY: the title passes one of our pipelines. + unsafe { &*this.cast::<Pipeline>() } +} + +/// List method: logs each pipeline's shaders the first time a list binds +/// it, so a run lists the shaders its frames need first. +pub(crate) fn bound(this: This) { + if this.is_null() { + return; + } + let p = pipeline(this); + if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) { + return; + } + let frame = crate::frame::current(); + for shader in &p.shaders { + tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind"); + } +} + +/// The host pipeline of a title pipeline; `None` if one of its shaders does +/// not translate, the host refuses it, or it is still being made (its first +/// use starts that, see [`make`]). +#[cfg(windows)] +pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + make::ready(&pipeline(this).host) +} + +/// Host pipelines queued and not made yet. +#[cfg(windows)] +pub(crate) fn making() -> u64 { + make::waiting() +} + +/// Draws and dispatches dropped since the last [`take_drops`], by reason +/// (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +static DROPS: Mutex<Option<HashMap<String, u64>>> = Mutex::new(None); + +/// Shader hashes as printed in the pipeline diagnostics. +#[cfg(all(windows, feature = "diagnostics"))] +fn parse_skip_hashes(value: &str) -> Vec<String> { + value + .split(',') + .map(str::trim) + .filter(|hash| !hash.is_empty()) + .filter_map(|hash| { + if hash.len() == 16 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) { + Some(hash.to_ascii_lowercase()) + } else { + tracing::warn!( + hash, + "VICTORY_SKIP_PIPELINES expects 16-digit shader hashes" + ); + None + } + }) + .collect() +} + +#[cfg(all(windows, feature = "diagnostics"))] +fn skipped_shader(p: &Pipeline) -> Option<&str> { + static HASHES: OnceLock<Vec<String>> = OnceLock::new(); + let hashes = HASHES.get_or_init(|| { + let value = std::env::var("VICTORY_SKIP_PIPELINES").unwrap_or_default(); + parse_skip_hashes(&value) + }); + if hashes.is_empty() { + return None; + } + p.shaders + .iter() + .find(|shader| hashes.contains(&shader.hash)) + .map(|shader| shader.hash.as_str()) +} + +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn is_skipped(this: This) -> bool { + !this.is_null() && skipped_shader(pipeline(this)).is_some() +} + +/// Counts a draw or dispatch of `this` intentionally skipped or dropped +/// for want of a host pipeline (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn note_drop(this: This) { + let why = if this.is_null() { + Some("no pipeline set".to_owned()) + } else { + let p = pipeline(this); + skipped_shader(p) + .map(|hash| format!("skipped shader {hash}")) + .or_else(|| make::missing(&p.host)) + }; + if let Some(why) = why { + note_why(why); + } +} + +/// 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; +} + +/// The drops counted since the last call, most first (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn take_drops() -> Vec<(String, u64)> { + let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect(); + // Frame reports only show the first 40 reasons. Keep ties ordered so + // a HashMap iteration order change cannot change which reasons appear. + drops.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + drops +} + +/// The stage's container, if it has one. +fn copy(stage: &'static str, code: &Bytecode) -> Option<Arc<Shader>> { + if code.code.is_null() || code.size == 0 { + return None; + } + // SAFETY: the title passes `size` bytes of shader code. + Some(shader(stage, unsafe { + std::slice::from_raw_parts(code.code, code.size) + })) +} + +fn hand_out( + shaders: Vec<Arc<Shader>>, + #[cfg(windows)] graphics: Option<Box<host::GraphicsState>>, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + tracing::trace!(?shaders, "pipeline state"); + #[cfg(windows)] + 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), + }); + object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out) +} + +/// Device method. +pub(crate) extern "system" fn create_graphics( + _: This, + desc: *const GraphicsHead, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + let stages = GRAPHICS_STAGES.iter().zip(&desc.stages); + let shaders = stages.filter_map(|(s, c)| copy(s, c)).collect(); + hand_out( + shaders, + #[cfg(windows)] + None, + iid, + out, + ) +} + +/// Device method. +pub(crate) extern "system" fn create_compute( + _: This, + desc: *const ComputeHead, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + hand_out( + copy("compute", &desc.stage).into_iter().collect(), + #[cfg(windows)] + None, + iid, + out, + ) +} + +/// Device method 0x1f0: the plain compute description plus console +/// extensions `(desc, extension count, extensions, iid, out)`. +/// shortcut: the extensions (console shader settings) are ignored, as is +/// the rest of the description. +pub(crate) extern "system" fn create_compute_x( + this: This, + desc: *const ComputeHead, + _extensions: u32, + _extended: *const u8, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + create_compute(this, desc, iid, out) +} + +/// A pipeline described as a stream: its size and the subobjects, each a +/// type then its data, padded to 8 bytes. +#[repr(C)] +pub(crate) struct StreamDesc { + size: usize, + stream: *const u8, +} + +/// A subobject type's size (type included), and the stage it is if it is a +/// shader. The console numbers amplification and mesh shaders 23 and 24 +/// (PC: 24 and 25); its own types from 25 on are not sized yet. +fn subobject(kind: u32) -> Option<(usize, Option<&'static str>)> { + let stage = |name| Some((24, Some(name))); + match kind { + 1 => stage("vertex"), + 2 => stage("pixel"), + 3 => stage("domain"), + 4 => stage("hull"), + 5 => stage("geometry"), + 6 => stage("compute"), + 23 => stage("amplification"), + 24 => stage("mesh"), + 0 => Some((16, None)), + 12 | 19 => Some((24, None)), + 7 | 15 => Some((40, None)), + 8 => Some((336, None)), + 10 => Some((48, None)), + 11 => Some((56, None)), + 17 => Some((16, None)), + 21 => Some((64, None)), + 22 => Some((32, None)), + 9 | 13 | 14 | 16 | 18 | 20 => Some((8, None)), + _ => None, + } +} + +/// Device method: a pipeline from a stream; the shaders are kept, and the +/// graphics state for the host pipeline. +pub(crate) extern "system" fn create_stream( + _: This, + desc: *const StreamDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if desc.stream.is_null() { + return E_INVALIDARG; + } + let mut shaders = Vec::new(); + #[cfg(windows)] + let mut graphics = host::GraphicsState::default(); + let mut at = 0; + while at + 8 <= desc.size { + // SAFETY: inside the stream the title passes. + let kind = unsafe { desc.stream.add(at).cast::<u32>().read_unaligned() }; + let Some((size, stage)) = subobject(kind) else { + tracing::warn!( + kind, + at, + "pipeline subobject of unknown size; the rest is ignored" + ); + break; + }; + if let Some(stage) = stage { + // SAFETY: a shader subobject has its bytecode at +8. + let code = unsafe { &*desc.stream.add(at + 8).cast::<Bytecode>() }; + shaders.extend(copy(stage, code)); + } + #[cfg(windows)] + // SAFETY: a whole subobject of this kind lies at `at`. + unsafe { + graphics.read(kind, desc.stream.add(at)) + }; + at += size; + } + hand_out( + shaders, + #[cfg(windows)] + Some(Box::new(graphics)), + iid, + out, + ) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &PIPELINE_IIDS).then_some(this); + object::answer(PIPELINE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::<Pipeline>(this) +} + +/// IUnknown 3, object 4, device child 1, pipeline 3. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 24>()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; + +#[cfg(windows)] +pub(crate) mod host; +#[cfg(windows)] +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)] +pub fn use_pipeline_cache(dir: std::path::PathBuf) { + library::use_pipeline_cache(dir); +} + +/// Saves the pipeline cache now if anything was added (at the end of a run). +#[cfg(windows)] +pub fn save_pipeline_cache() { + library::save(true); +} + +#[cfg(test)] +mod tests { + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + fn skip_hashes_accepts_full_hashes_only() { + assert!(super::parse_skip_hashes(" , ").is_empty()); + assert_eq!( + super::parse_skip_hashes(" 0123456789ABCDEF, 0123456789abcde, xyz, 0011223344556677,"), + ["0123456789abcdef", "0011223344556677"] + ); + } + + use super::*; + use crate::object::{S_OK, slot}; + + fn shaders(p: This) -> Vec<(&'static str, Vec<u8>)> { + pipeline(p) + .shaders + .iter() + .map(|s| (s.stage, s.container.clone())) + .collect() + } + + #[test] + fn pipelines_keep_their_shaders() { + let (vs, ps) = ([1u8, 2, 3], [4u8; 5]); + let none = || Bytecode { + code: std::ptr::null(), + size: 0, + }; + let desc = GraphicsHead { + root: std::ptr::null(), + stages: [ + Bytecode { + code: vs.as_ptr(), + size: vs.len(), + }, + Bytecode { + code: ps.as_ptr(), + size: ps.len(), + }, + none(), + none(), + none(), + ], + }; + let mut p = std::ptr::null(); + assert_eq!( + create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p), + S_OK + ); + assert_eq!( + shaders(p), + [("vertex", vs.to_vec()), ("pixel", ps.to_vec())] + ); + // A second pipeline with the same pixel shader shares its container. + let mut q = std::ptr::null(); + create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut q); + assert!(Arc::ptr_eq( + &pipeline(p).shaders[1], + &pipeline(q).shaders[1] + )); + assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0); + } + + /// The stream layout Grand Theft Auto VI 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. + #[test] + fn streams_yield_their_shaders() { + let (ms, ps) = ([9u8; 7], [4u8; 5]); + let mut stream = vec![0u8; 0x2b0]; + let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes()); + for (at, kind) in [ + (0x10, 24), + (0x28, 2), + (0x40, 3), + (0x58, 4), + (0x70, 5), + (0x88, 8), + (0x1d8, 9), + (0x1e0, 10), + (0x210, 21), + (0x250, 17), + (0x260, 12), + (0x278, 14), + (0x280, 15), + (0x2a8, 16), + ] { + put(at, kind); + } + put(0x18, ms.as_ptr() as u64); + put(0x20, ms.len() as u64); + put(0x30, ps.as_ptr() as u64); + put(0x38, ps.len() as u64); + // Topology type 3 (triangles), one render target of format 28. + put(0x278, 14 | 3 << 32); + put(0x280, 15 | 28 << 32); + put(0x2a0, 1 << 32); + let desc = StreamDesc { + size: stream.len(), + stream: stream.as_ptr(), + }; + let mut p = std::ptr::null(); + let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p); + assert_eq!(hr, S_OK); + assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]); + #[cfg(windows)] + { + let g = pipeline(p).host.graphics.as_deref().unwrap(); + assert_eq!(g.topology.0, 3); + assert_eq!( + (g.targets.NumRenderTargets, g.targets.RTFormats[0].0), + (1, 28) + ); + } + } +} diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs new file mode 100644 index 000000000..e8d457985 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -0,0 +1,931 @@ +//! Host pipelines for title pipelines (decision 0007, step 3): the +//! title's graphics state with the translated shaders, under a root +//! signature of our own that the translated shaders' bindings define +//! (`victory_shader::emit`): per stage one block of root constants for the +//! user data, root views for the title's root views, static samplers for +//! the immediate samplers, and directly indexed heaps. + +use std::ffi::{CStr, CString}; +use std::sync::Arc; + +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::*; +use windows::core::PCSTR; + +use super::{Shader, Translated}; +use crate::host::host; + +/// A stream's graphics state, owned (the title's stream lives only for the +/// creation call). Subobjects the stream leaves out keep D3D12's defaults. +pub(crate) struct GraphicsState { + blend: D3D12_BLEND_DESC, + sample_mask: u32, + rasterizer: D3D12_RASTERIZER_DESC, + depth: D3D12_DEPTH_STENCIL_DESC, + /// Input elements, their names pointing into `names`. + inputs: Vec<D3D12_INPUT_ELEMENT_DESC>, + names: Vec<CString>, + strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE, + pub(crate) targets: D3D12_RT_FORMAT_ARRAY, + depth_format: DXGI_FORMAT, + samples: DXGI_SAMPLE_DESC, +} + +impl Default for GraphicsState { + fn default() -> Self { + let target = D3D12_RENDER_TARGET_BLEND_DESC { + SrcBlend: D3D12_BLEND_ONE, + DestBlend: D3D12_BLEND_ZERO, + BlendOp: D3D12_BLEND_OP_ADD, + SrcBlendAlpha: D3D12_BLEND_ONE, + DestBlendAlpha: D3D12_BLEND_ZERO, + BlendOpAlpha: D3D12_BLEND_OP_ADD, + LogicOp: D3D12_LOGIC_OP_NOOP, + RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8, + ..Default::default() + }; + let keep = D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D12_STENCIL_OP_KEEP, + StencilDepthFailOp: D3D12_STENCIL_OP_KEEP, + StencilPassOp: D3D12_STENCIL_OP_KEEP, + StencilFunc: D3D12_COMPARISON_FUNC_ALWAYS, + }; + GraphicsState { + blend: D3D12_BLEND_DESC { + RenderTarget: [target; 8], + ..Default::default() + }, + sample_mask: u32::MAX, + rasterizer: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_BACK, + DepthClipEnable: true.into(), + ..Default::default() + }, + depth: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_LESS, + StencilReadMask: 0xff, + StencilWriteMask: 0xff, + FrontFace: keep, + BackFace: keep, + ..Default::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(), + depth_format: DXGI_FORMAT_UNKNOWN, + samples: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + } + } +} + +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`. + 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 = data.cast::<D3D12_BLEND_DESC>().read_unaligned(), + 9 => self.sample_mask = data.cast::<u32>().read_unaligned(), + 10 => self.rasterizer = data.cast::<D3D12_RASTERIZER_DESC>().read_unaligned(), + 11 => self.depth = data.cast::<D3D12_DEPTH_STENCIL_DESC>().read_unaligned(), + 21 => { + // shortcut: the depth bounds test is dropped (the host + // pipeline uses the plain description); bring it back + // with a stream if a title enables it. + let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned(); + if d.DepthBoundsTestEnable.as_bool() { + static SEEN: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::warn!( + "a pipeline enables the depth bounds test, which its host pipeline leaves out: its draws pass at every depth" + ); + } + } + self.depth = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: d.DepthEnable, + DepthWriteMask: d.DepthWriteMask, + DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, + StencilReadMask: d.StencilReadMask, + StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, + BackFace: d.BackFace, + }; + } + 12 => { + let layout = at.add(8).cast::<D3D12_INPUT_LAYOUT_DESC>().read_unaligned(); + 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 = + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE(data.cast::<i32>().read_unaligned()) + } + 14 => { + self.topology = + D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::<i32>().read_unaligned()) + } + 15 => { + self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().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; + } + } + 16 => { + let f = data.cast::<u32>().read_unaligned(); + self.depth_format = DXGI_FORMAT(crate::resource::pc_format(f) as i32); + } + 17 => self.samples = data.cast::<DXGI_SAMPLE_DESC>().read_unaligned(), + _ => {} + } + } + } + + /// 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: Vec<String> = 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:?} {} {} {:?} {} {:?}", + self.blend, + self.sample_mask, + self.rasterizer, + self.depth, + self.strip_cut.0, + self.topology.0, + self.targets, + self.depth_format.0, + self.samples + ) + } + + /// The vertex buffer slots the input layout reads. + fn slots(&self) -> u32 { + 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) -> Vec<Input> { + let mut next = [0u32; 32]; + self.inputs + .iter() + .map(|e| { + let slot = e.InputSlot.min(31) as usize; + let format = e.Format.0 as u32; + let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { + next[slot] + } else { + e.AlignedByteOffset + }; + 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() + } +} + +/// One input element: vertex buffer slot, byte offset, format. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Input { + pub(crate) slot: u32, + pub(crate) offset: u32, + pub(crate) format: u32, + pub(crate) per_instance: bool, +} + +/// The console's own primitive topology types. +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<bool> = 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<Shader>, + /// The root parameter of its user data, and its size in dwords. + pub(crate) user_data: Option<(u32, u32)>, + /// Root parameters of its root views: (title root parameter, ours). + pub(crate) root_cbvs: Vec<(u8, u32)>, + pub(crate) root_srvs: Vec<(u8, u32)>, + /// Root UAVs: one-view tables like the SRVs (or root descriptors with + /// `VICTORY_ROOT_SRV_DIRECT=1`). + pub(crate) root_uavs: Vec<(u8, u32)>, +} + +impl Stage { + pub(crate) fn translated(&self) -> &Translated { + self.shader + .translated() + .expect("host pipelines are made from translated shaders") + } +} + +pub(crate) struct HostPipeline { + /// A compute pipeline (else graphics). + pub(crate) compute: bool, + /// A mesh pipeline (graphics without vertex input). + pub(crate) mesh: bool, + pub(crate) pso: ID3D12PipelineState, + pub(crate) root: ID3D12RootSignature, + /// Vertex, then pixel stage, or the compute stage. + pub(crate) stages: Vec<Stage>, + /// The vertex buffer slots it reads (bit per slot). + pub(crate) slots: u32, + pub(crate) inputs: Vec<Input>, + /// 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, + /// 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. +fn refuse(reason: &'static str, shaders: &[Arc<Shader>]) -> Option<HostPipeline> { + static SEEN: std::sync::Mutex<Vec<&str>> = std::sync::Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&reason) { + seen.push(reason); + tracing::warn!(?shaders, "no host pipeline: {reason} (logged once)"); + } + None +} + +impl HostPipeline { + /// A host pipeline for vertex and pixel shaders with the graphics + /// state `g`, or for one compute shader. + pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> { + // 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), + _ => None, + }; + if compute.is_none() + && shaders + .iter() + .any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh")) + { + return refuse( + "only vertex, mesh, pixel and compute stages are translated", + shaders, + ); + } + let mesh = find("mesh"); + let stages = if let Some(cs) = compute { + vec![(cs, D3D12_SHADER_VISIBILITY_ALL)] + } else { + let first = match (mesh, find("vertex")) { + (Some(ms), _) => (ms, D3D12_SHADER_VISIBILITY_MESH), + (None, Some(vs)) => (vs, D3D12_SHADER_VISIBILITY_VERTEX), + (None, None) => return refuse("no vertex or mesh shader", shaders), + }; + let mut stages = vec![first]; + stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); + stages + }; + 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()?; + } + let host = host()?; + + // The root signature the translated shaders' bindings define. + let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new(); + // The ranges table parameters point at, alive until the root + // signature is made. + let mut ranges: Vec<Box<D3D12_DESCRIPTOR_RANGE1>> = Vec::new(); + let mut samplers = Vec::new(); + let mut bound = Vec::new(); + for &(shader, visibility) in &stages { + let t = &shader.translated()?.host; + let mut stage = Stage { + shader: shader.clone(), + user_data: None, + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + }; + let dwords = t.user_data_dwords(); + if dwords > 0 { + stage.user_data = Some((params.len() as u32, dwords)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: dwords, + }, + }, + ShaderVisibility: visibility, + }); + } + for (slots, kind, out) in [ + ( + &t.root_cbvs, + D3D12_ROOT_PARAMETER_TYPE_CBV, + &mut stage.root_cbvs, + ), + ( + &t.root_srvs, + D3D12_ROOT_PARAMETER_TYPE_SRV, + &mut stage.root_srvs, + ), + ( + &t.root_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.root_uavs, + ), + ] { + for &slot in slots { + let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV; + // Ours, not the title's, stay root descriptors: the + // table of strides, the directory of title memory by + // address and its fault notes. + let ours = if uav { + slot == victory_shader::emit::SLOT_FAULTS + } else { + slot == victory_shader::emit::SLOT_STRIDES + || slot == victory_shader::emit::SLOT_MEMORY + }; + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { + // A one-view table: the view's size bounds the + // reads (and a root UAV's writes), which a root + // descriptor leaves unbounded. + // (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 (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 { + pShaderBytecode: t.host.dxil.as_ptr().cast(), + BytecodeLength: t.host.dxil.len(), + }, + ) + }; + if compute.is_some() { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the description never releases. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + CS: code(0), + ..Default::default() + }; + let name = super::library::name("compute", &root_blob, &[&code_bytes(&code(0))], ""); + let made = super::library::pipeline( + &name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadComputePipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateComputePipelineState(&desc) }, + ); + let pso = match made { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); + return Some(HostPipeline { + compute: true, + mesh: false, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: 0, + inputs: Vec::new(), + rects: false, + state: String::new(), + }); + } + let Some(g) = g else { + return refuse("graphics state not kept (plain description)", shaders); + }; + 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 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, &name) { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host mesh pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); + return Some(HostPipeline { + compute: false, + mesh: true, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: 0, + inputs: Vec::new(), + rects: false, + state: String::new(), + }); + } + + // 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), + 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: 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 + // the host (see `draw`). + PrimitiveTopologyType: match g.topology.0 { + RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + _ => g.topology, + }, + NumRenderTargets: g.targets.NumRenderTargets, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + // A pipeline with the geometry stage has a name of its own in the + // library; the others keep theirs. + let name = |gs: Option<&Vec<u8>>| 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| { + super::library::pipeline( + name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadGraphicsPipeline(name, desc) }, + // SAFETY: as above. + || 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) => { + tracing::warn!(error = %e, ?shaders, "host pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); + tracing::debug!( + ?shaders, + depth = ?g.depth, + dsv = g.depth_format.0, + targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize], + blend = ?g.blend.RenderTarget[0], + cull = g.rasterizer.CullMode.0, + "host graphics state" + ); + Some(HostPipeline { + compute: false, + mesh: false, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + 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 + ) + }; + format!( + "depth {} write {} func {}; 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 + ) + }, + }) + } +} + +/// 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, + ms: D3D12_SHADER_BYTECODE, + ps: D3D12_SHADER_BYTECODE, + g: &GraphicsState, + name: &str, +) -> windows::core::Result<ID3D12PipelineState> { + use windows::core::Interface; + /// A stream subobject: its type, then its description, pointer-aligned. + #[repr(C, align(8))] + struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub<D3D12_SHADER_BYTECODE>, + ps: Sub<D3D12_SHADER_BYTECODE>, + blend: Sub<D3D12_BLEND_DESC>, + mask: Sub<u32>, + raster: Sub<D3D12_RASTERIZER_DESC>, + depth: Sub<D3D12_DEPTH_STENCIL_DESC>, + targets: Sub<D3D12_RT_FORMAT_ARRAY>, + dsv: Sub<DXGI_FORMAT>, + samples: Sub<DXGI_SAMPLE_DESC>, + topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>, + } + 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_STENCIL, g.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, + ), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::<Stream>(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let device = device.cast::<ID3D12Device2>()?; + super::library::pipeline( + name, + // SAFETY: the stream holds whole subobjects pointing at live data. + |library, name| unsafe { library.LoadPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { device.CreatePipelineState(&desc) }, + ) +} + +/// The bytes of shader code (none for an absent stage). +fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec<u8> { + 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::<u8>(), code.BytecodeLength) }.to_vec() +} + +fn root_signature( + device: &ID3D12Device, + params: &[D3D12_ROOT_PARAMETER1], + samplers: &[D3D12_STATIC_SAMPLER_DESC], + compute: bool, +) -> windows::core::Result<(ID3D12RootSignature, Vec<u8>)> { + let input = if compute { + D3D12_ROOT_SIGNATURE_FLAG_NONE + } else { + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + }; + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: samplers.len() as u32, + pStaticSamplers: samplers.as_ptr(), + Flags: input + | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + // SAFETY: the description points at live arrays; the blob is read in + // full before it is released. + unsafe { + let mut blob: Option<ID3DBlob> = None; + let mut error: Option<ID3DBlob> = None; + if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) { + if let Some(error) = error { + let text = std::slice::from_raw_parts( + error.GetBufferPointer().cast::<u8>(), + error.GetBufferSize(), + ); + tracing::warn!("root signature: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) + } +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + use std::sync::atomic::Ordering; + + use super::*; + + /// 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<PathBuf> { + 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"), + }; + dxc.exists().then_some(dxc) + } + + fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec<u8> { + 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() + } + + 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 a_mesh_pipeline_loads_from_the_library() { + let Some(host) = host() else { + return; // no host GPU here + }; + if !host.mesh_shaders() { + eprintln!("no host mesh shader support; skipped"); + return; + } + let Some(dxc) = dxc() else { + eprintln!("no PC dxc.exe; skipped"); + return; + }; + 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, &name).expect("made"); + let loaded = super::super::library::LOADED.load(Ordering::Relaxed); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &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" + ); + } +} diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs new file mode 100644 index 000000000..7047331af --- /dev/null +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -0,0 +1,838 @@ +//! Compiled host pipelines kept on disk, and the title pipelines worth +//! starting early (decision 0007, "Pipeline cache"). +//! +//! 1. Every host pipeline goes into the host's pipeline library, named by +//! 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; 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. +//! +//! 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::HashSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::{HSTRING, Interface, PCWSTR}; + +static DIR: OnceLock<PathBuf> = OnceLock::new(); + +/// Keeps the pipeline library and the early list in `dir` from now on. +pub fn use_pipeline_cache(dir: PathBuf) { + let _ = DIR.set(dir); +} + +/// Host pipelines created, loaded from the library, and title pipelines +/// started at creation, since the start. +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<bool> = 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<bool> = 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<std::fs::File>, +} + +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<Mapped> { + 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> { + 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<Mapped> { + // 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<Mapped> { + 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<u8>), + /// 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<Vec<(u32, &'static str, String, u64)>> = Mutex::new(Vec::new()); + +thread_local! { + /// The pipeline this thread is making (its shaders), for [`CALLS`]. + static LABEL: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) }; +} + +/// 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() { + const QUIET_MS: u64 = 10_000; + static ON: OnceLock<bool> = OnceLock::new(); + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 + || TRIMMED.load(Ordering::Relaxed) + || crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + QUIET_MS + || !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0")) + || 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: Blob, + /// Pipelines stored since the last save. + 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 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 {} + +/// 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()) +} + +/// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before. +fn one_call() -> Option<MutexGuard<'static, ()>> { + static ON: OnceLock<bool> = 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())) +} + +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 library() -> Option<&'static Library> { + static LIBRARY: OnceLock<Option<Library>> = OnceLock::new(); + LIBRARY + .get_or_init(|| { + let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?; + 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"); + } + 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: Blob) -> Option<Library> { + let make = |bytes: &[u8]| -> windows::core::Result<ID3D12PipelineLibrary1> { + // SAFETY: the bytes outlive the library (kept beside it). + unsafe { + device.CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)?.cast() + } + }; + if !blob.bytes().is_empty() { + match make(blob.bytes()) { + Ok(library) => { + 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: AtomicU64::new(0), + saving: RwLock::new(()), + }); + } + 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: Blob::None, + added: AtomicU64::new(0), + saving: RwLock::new(()), + }) +} + +/// A pipeline's name in the library: the hash of what its host +/// 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()]) { + h.update(&(part.len() as u64).to_le_bytes()); + h.update(part); + } + h.finalize().to_hex()[..32].to_owned() +} + +/// The pipeline named `name`: loaded from the library by `load` if it is +/// there with the same description, else made by `create` and stored. +pub(crate) fn pipeline( + name: &str, + load: impl FnOnce(&ID3D12PipelineLibrary1, PCWSTR) -> windows::core::Result<ID3D12PipelineState>, + create: impl FnOnce() -> windows::core::Result<ID3D12PipelineState>, +) -> windows::core::Result<ID3D12PipelineState> { + let wide = HSTRING::from(name); + let Some(library) = library() else { + MADE.fetch_add(1, Ordering::Relaxed); + return create(); + }; + 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 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<Option<std::time::Instant>> = Mutex::new(None); + const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); + 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) { + return; + } + *last = Some(std::time::Instant::now()); + } + if let Err(e) = std::fs::create_dir_all(dir) { + tracing::warn!(error = %e, "host pipeline library not saved"); + return; + } + 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; + } + library.added.store(0, Ordering::Relaxed); + SAVED.store(size as u64, Ordering::Relaxed); + size + } + }; + let used: Vec<String> = 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" } + ) + }); + } + 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<()> { + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +/// Title pipeline keys requested by draws or dispatches (this run and the last). +static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None); +static USED_CHANGED: AtomicBool = AtomicBool::new(false); + +fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> { + let mut used = USED.lock().unwrap_or_else(|e| e.into_inner()); + if used.is_none() { + let listed = DIR + .get() + .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) + .unwrap_or_default(); + let set: HashSet<String> = 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); + } + used +} + +/// Whether the title pipeline with `key` was requested in this or an earlier run. +pub(crate) fn wanted_early(key: &str) -> bool { + used().as_ref().is_some_and(|s| s.contains(key)) +} + +/// A draw or dispatch requested the title pipeline with `key`. +pub(crate) fn note_used(key: &str) { + let mut used = used(); + let set = used.get_or_insert_with(HashSet::new); + if set.len() < EARLY_MAX && set.insert(key.to_owned()) { + USED_CHANGED.store(true, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_change_with_what_goes_into_the_pipeline() { + let a = name("graphics", b"root", &[b"vs", b"ps"], "state"); + assert_eq!(a, name("graphics", b"root", &[b"vs", b"ps"], "state")); + assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps2"], "state")); + assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps"], "state2")); + assert_ne!(a, name("graphics", b"root2", &[b"vs", b"ps"], "state")); + assert_ne!(a, name("mesh", b"root", &[b"vs", b"ps"], "state")); + // Parts do not run into each other. + assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state")); + } + + #[test] + fn a_rejected_blob_gives_an_empty_library() { + let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else { + return; // no host GPU here + }; + 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!(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<u8> = (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<u8> = (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 new file mode 100644 index 000000000..49c26c62f --- /dev/null +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -0,0 +1,399 @@ +//! 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 +//! 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 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. +//! +//! 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::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}; + +/// What a host pipeline is made from, and the host pipeline once made. +pub(crate) struct Pending { + shaders: Vec<Arc<Shader>>, + pub(crate) graphics: Option<Box<GraphicsState>>, + queue_state: AtomicU8, + made: OnceLock<Option<HostPipeline>>, + /// What identifies it across runs (shader containers and state), and + /// whether a draw or dispatch has requested it yet. + key: String, + used: AtomicBool, +} + +// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input +// elements point into its own names) is only read after creation. +unsafe impl Send for Pending {} +// SAFETY: as above. +unsafe impl Sync for Pending {} + +impl Pending { + pub(crate) fn new(shaders: Vec<Arc<Shader>>, graphics: Option<Box<GraphicsState>>) -> 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()); + Pending { + shaders, + graphics, + queue_state: AtomicU8::new(NOT_QUEUED), + made: OnceLock::new(), + key: key.finalize().to_hex()[..32].to_owned(), + used: AtomicBool::new(false), + } + } + + fn make(&self) { + self.made + .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); + let (lock, done) = &DONE; + let _held = lock.lock().unwrap_or_else(|e| e.into_inner()); + done.notify_all(); + } +} + +/// Why a pipeline has no host pipeline (diagnostics): its shaders that do +/// not translate, else "refused" or "being made"; `None` if it has one. +#[cfg(feature = "diagnostics")] +pub(crate) fn missing(p: &Pending) -> Option<String> { + match p.made.get() { + Some(Some(_)) => None, + None => Some("being made".into()), + Some(None) => { + let failed: Vec<String> = p + .shaders + .iter() + .filter(|s| matches!(s.translated.get(), Some(None))) + .map(|s| format!("{} {}", s.stage, s.hash)) + .collect(); + Some(if failed.is_empty() { + format!("refused {:?}", p.shaders) + } else { + failed.join(" + ") + }) + } + } +} + +/// Signalled whenever a worker has made a pipeline. +static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); + +/// Waiting allowed per title frame, over all threads. +fn wait_budget() -> Duration { + static BUDGET: OnceLock<Duration> = OnceLock::new(); + *BUDGET.get_or_init(|| { + let millis = std::env::var("VICTORY_PIPELINE_WAIT_MS") + .ok() + .and_then(|value| value.trim().parse::<u64>().ok()) + .unwrap_or(500); + tracing::info!(millis, "host pipeline wait budget per frame"); + Duration::from_millis(millis) + }) +} + +/// Pipelines queued and not made yet. +static WAITING: AtomicU64 = AtomicU64::new(0); + +/// Pipelines queued and not made yet (for the frame line). +pub(crate) fn waiting() -> u64 { + WAITING.load(Ordering::Relaxed) +} + +/// The host pipeline if it is made (or is made within the frame's budget); +/// queues it on first use. +pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> { + // 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. + if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) { + super::library::note_used(&p.key); + } + if p.made.get().is_none() { + start(p, REQUESTED); + wait(p, crate::frame::current()); + } + p.made.get()?.as_ref() +} + +/// 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<Pending>) -> 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 if an earlier +/// run drew with it (during loading, so the world's first frames find it). +pub(crate) fn early(p: &Arc<Pending>) { + if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { + super::library::EARLY.fetch_add(1, Ordering::Relaxed); + 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<bool> = 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) { + let budget = wait_budget(); + if budget.is_zero() { + return; + } + // 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; + } + let started = Instant::now(); + let (lock, done) = &DONE; + let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); + while p.made.get().is_none() { + let rest = left.saturating_sub(started.elapsed()); + if rest.is_zero() { + break; + } + 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; + } + } + } + #[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<Arc<Pending>>, + requested: VecDeque<Arc<Pending>>, +} + +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<Pending>, priority: u8) -> Option<bool> { + 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<Arc<Pending>> { + 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) + } +} + +static QUEUE: Mutex<Queue> = 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<Pending>, 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<Pending> { + 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<bool> = 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 spawned = std::thread::Builder::new() + .name(format!("victory-pipelines-{i}")) + .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 { + next().make(); + if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { + drained(); + } else { + super::library::save(false); + } + } + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "no pipeline worker"); + } else { + running = true; + } + } + running + }) +} + +/// The most pipelines waiting at once since the workers last ran out. +static PEAK: AtomicU64 = AtomicU64::new(0); + +/// The workers ran out of work: logged after a batch of 10 or more, and +/// the cache saved (at most every 20 s). +fn drained() { + use super::library::{EARLY, LOADED, MADE}; + if PEAK.swap(0, Ordering::Relaxed) >= 10 { + tracing::info!( + made = MADE.load(Ordering::Relaxed), + loaded = LOADED.load(Ordering::Relaxed), + started_early = EARLY.load(Ordering::Relaxed), + "host pipelines all made" + ); + } + super::library::save(false); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 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_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(); + } + assert!(matches!(p.made.get(), Some(None))); + } + + #[test] + fn pending_pipeline_is_recorded_for_the_next_launch() { + let mut p = Pending::new(Vec::new(), None); + p.key = "pending-pipeline-test".to_owned(); + // 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)); + assert!(ready(&p).is_none()); + assert!(p.made.get().is_none()); + assert!(super::super::library::wanted_early(&p.key)); + } + + #[test] + 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 new file mode 100644 index 000000000..91a23ee16 --- /dev/null +++ b/crates/victory-gpu/src/primitive.rs @@ -0,0 +1,237 @@ +//! Console primitive types the host lacks. A rectangle list gives three +//! corners per rectangle, the second the one between the other two, and +//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's +//! full-screen rectangles come as top left, bottom left, bottom right); on +//! the host each rectangle becomes two triangles, with the fourth vertex +//! made from the other three on the CPU. +//! +//! shortcut: the fourth vertex is computed from vertex inputs, not from +//! vertex shader outputs as the hardware does; that is the same for vertex +//! shaders linear in their inputs (blits, 2D quads). Inputs in formats +//! [`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)]) { + for (rect, out) in src + .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() { + out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i)); + } + let fourth = &mut out[5 * stride..]; + fourth.copy_from_slice(v(0)); + for &(offset, format) in elements { + let at = offset as usize; + let Some((n, kind)) = components(format) else { + continue; + }; + // Only the components inside the vertex: the rest belong to the + // next one. + let inside = stride.saturating_sub(at) / kind.bytes(); + for c in 0..n.min(inside) { + let get = |i: usize| kind.read(&v(i)[at..], c); + let value = get(0) + get(2) - get(1); + kind.write(&mut fourth[at..], c, value); + } + } + } +} + +#[derive(Clone, Copy)] +enum Kind { + F32, + F16, + Unorm8, + Unorm16, +} + +/// Component count and kind of the vertex formats rectangles use. +fn components(format: u32) -> Option<(usize, Kind)> { + Some(match format { + 2 => (4, Kind::F32), + 6 => (3, Kind::F32), + 16 => (2, Kind::F32), + 41 => (1, Kind::F32), + 10 => (4, Kind::F16), + 34 => (2, Kind::F16), + 54 => (1, Kind::F16), + 11 => (4, Kind::Unorm16), + 35 => (2, Kind::Unorm16), + 28 | 29 | 87 | 91 => (4, Kind::Unorm8), + _ => return None, + }) +} + +impl Kind { + fn bytes(self) -> usize { + match self { + Kind::F32 => 4, + Kind::F16 | Kind::Unorm16 => 2, + Kind::Unorm8 => 1, + } + } + + fn read(self, at: &[u8], c: usize) -> f32 { + let b = &at[c * self.bytes()..]; + match self { + Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]), + Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])), + Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0, + Kind::Unorm8 => f32::from(b[0]) / 255.0, + } + } + + fn write(self, at: &mut [u8], c: usize, v: f32) { + let n = self.bytes(); + let b = &mut at[c * n..(c + 1) * n]; + match self { + Kind::F32 => b.copy_from_slice(&v.to_le_bytes()), + Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()), + Kind::Unorm16 => { + b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes()) + } + Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8, + } + } +} + +fn half_to_f32(h: u16) -> f32 { + let sign = u32::from(h >> 15) << 31; + let exp = u32::from((h >> 10) & 0x1f); + let man = u32::from(h & 0x3ff); + let bits = match (exp, man) { + (0, 0) => sign, + // Subnormal: scale the mantissa. + (0, m) => { + let v = m as f32 * 2f32.powi(-24); + return if sign != 0 { -v } else { v }; + } + (31, m) => sign | 0x7f80_0000 | m << 13, + (e, m) => sign | (e + 112) << 23 | m << 13, + }; + f32::from_bits(bits) +} + +fn f32_to_half(v: f32) -> u16 { + let bits = v.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let man = bits & 0x7f_ffff; + if exp >= 31 { + return sign | 0x7c00; // too large: infinity + } + if exp <= 0 { + if exp < -10 { + return sign; // below half the smallest subnormal: zero + } + // Half subnormals are `m * 2^-24`. An f32 in this range is still + // normal (exponent field >= 1), so its significand has the implicit + // leading 1; shift it into the half mantissa, rounding to even. + let sig = (1u32 << 23) | man; + let shift = (14 - exp) as u32; + let halfway = 1u32 << (shift - 1); + let q = sig >> shift; + let r = sig & ((1u32 << shift) - 1); + let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); + return sign | m as u16; + } + // 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; + sign | (half + ((man + 0x1000) >> 13)) as u16 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A rectangle of float2 positions and RGBA8 colors, given as top + /// left, bottom left, bottom right: the fourth corner completes the + /// parallelogram at the top right. + #[test] + fn rectangles_get_their_fourth_corner() { + let vertex = |x: f32, y: f32, r: u8| { + let mut v = Vec::new(); + v.extend(x.to_le_bytes()); + v.extend(y.to_le_bytes()); + v.extend([r, 0, 0, 255]); + v + }; + let src: Vec<u8> = [ + vertex(-1.0, 1.0, 0), + vertex(-1.0, -1.0, 100), + vertex(1.0, -1.0, 150), + ] + .concat(); + let mut dst = vec![0u8; 6 * 12]; + expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]); + assert_eq!(dst[..36], src[..]); + assert_eq!(dst[36..48], src[..12]); + assert_eq!(dst[48..60], src[24..36]); + assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x3e00), 1.5); + assert_eq!(half_to_f32(0xc000), -2.0); + } + + /// A rounding that carries out of the mantissa raises the exponent + /// (the carry used to be or-ed into an odd exponent, halving the value). + #[test] + fn halves_round_up_into_the_next_power_of_two() { + assert_eq!(f32_to_half(2.0 - 2f32.powi(-12)), 0x4000); + assert_eq!(f32_to_half(0.5 - 2f32.powi(-13)), 0x3800); + assert_eq!(f32_to_half(65520.0), 0x7c00, "past the largest half"); + // An R16_FLOAT element at 1.0, 2^-12 and 1.0: the fourth corner is + // 2 - 2^-12, which rounds to 2.0. + let src: Vec<u8> = [0x3c00_u16, 0x0c00, 0x3c00] + .iter() + .flat_map(|h| h.to_le_bytes()) + .collect(); + let mut dst = vec![0u8; 6 * 2]; + expand_rects(&src, &mut dst, 2, &[(0, 54)]); + assert_eq!(dst[10..], 0x4000_u16.to_le_bytes()); + } + + /// 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 + /// code indexed past the vertex and panicked. + #[test] + fn elements_past_the_stride_are_left_alone() { + let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat(); + let src = [vertex(0.0, 2.0), vertex(1.0, 3.0), vertex(5.0, 7.0)].concat(); + let mut dst = vec![0u8; 6 * 8]; + expand_rects(&src, &mut dst, 8, &[(0, 16), (4, 2), (8, 28)]); + assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]); + assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); + } + + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be + /// able to write them back instead of flushing every one to zero. + #[test] + fn half_subnormals_convert_in_both_directions() { + assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001); + assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001); + assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002); + assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff); + // Ties go to an even mantissa: 0/1 and 1/2. + assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000); + assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002); + // Below half the smallest subnormal, and normal values, are unchanged. + assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + } +} diff --git a/crates/victory-gpu/src/query.rs b/crates/victory-gpu/src/query.rs new file mode 100644 index 000000000..f3eb6b040 --- /dev/null +++ b/crates/victory-gpu/src/query.rs @@ -0,0 +1,72 @@ +//! Query heaps. Nothing runs on a GPU yet, so no query ever produces a +//! result; the heap only remembers its description. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUERY_HEAP, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x0d9658ae, + 0xed45, + 0x469e, + [0xa6, 0x1d, 0x97, 0x0e, 0xc5, 0x83, 0xca, 0xb4], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct Desc { + kind: u32, + count: u32, + nodes: u32, +} + +#[repr(C)] +struct Heap { + object: Object, + desc: Desc, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + desc: *const Desc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "query heap"); + let heap = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc, + }); + object::hand_out(QUERY_HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + QUERY_HEAP, + iid, + object::is(iid, &HEAP_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::<Heap>(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 24>()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs new file mode 100644 index 000000000..13354018e --- /dev/null +++ b/crates/victory-gpu/src/queue.rs @@ -0,0 +1,1086 @@ +//! Command queues. Submitted lists run on the host GPU and are waited for, +//! so fence signals complete at once. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const QUEUE_IIDS: [Iid; 4] = [ + guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct QueueDesc { + kind: u32, + priority: i32, + flags: u32, + nodes: u32, +} + +/// The title reads the list type right after the header. +#[repr(C)] +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<Vec<Held>>, +} +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<crate::list::Detached>, Vec<usize>), + /// 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<Vec<usize>> = std::sync::Mutex::new(Vec::new()); + +#[cfg(windows)] +fn lock<T>(mutex: &std::sync::Mutex<T>) -> 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<bool> = 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<bool> = 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<bool> = 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<bool> = 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<String> = 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::<usize>(), + "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<String> = 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<Held> = 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<crate::list::ValueWait> = 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::<Queue>() } +} + +pub(crate) extern "system" fn create( + _: This, + desc: *const QueueDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "command queue"); + let queue = Box::new(Queue { + object: if crate::device::newer() { + Object::new(&NEWER_FUNCTIONS) + } else { + Object::new(&FUNCTIONS) + }, + kind: desc.kind, + desc, + #[cfg(windows)] + held: Default::default(), + }); + object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out) +} + +/// The console's queue description: an engine or pipe and a queue on it +/// in place of PC's priority and node mask. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct QueueDescX { + kind: u32, + flags: u32, + engine_or_pipe: u32, + queue: u32, +} + +/// Device method `CreateCommandQueueX`. The host picks engines itself, so +/// the queue is created as on PC. +pub(crate) extern "system" fn create_x( + this: This, + desc: *const QueueDescX, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&x) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(desc = ?x, "console command queue"); + let desc = QueueDesc { + kind: x.kind, + priority: 0, + flags: x.flags, + nodes: 1, + }; + create(this, &desc, iid, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + QUEUE, + iid, + object::is(iid, &QUEUE_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + let left = object::release_boxed::<Queue>(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). 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; + } + #[cfg(windows)] + 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<String> = 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(&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"); + } +} + +/// The start of a present plane: frame token, then the plane's resources. +#[repr(C)] +pub(crate) struct Plane { + token: u64, + count: u32, + resources: *const This, +} +/// Submission tagged with the frame it belongs to `(count, lists, frame +/// token, flags)`; frames are paced elsewhere, so it runs as a plain one. +extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) { + execute(this, count, lists); +} +/// Signal with sync settings for the top and bottom of the pipe; our +/// submissions are complete when they return, so it signals at once. +extern "system" fn signal2_x( + this: This, + fence: This, + value: u64, + _bottom: *const u8, + _top: *const u8, +) -> HRESULT { + signal(this, fence, value) +} +/// Markers and events only matter to profilers. +extern "system" fn marker(_: This) {} +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) +} +/// 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 { + if out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + unsafe { out.write(TIMESTAMP_FREQUENCY) }; + S_OK +} +const TIMESTAMP_FREQUENCY: u64 = 100_000_000; + +/// What a list's bottom-of-pipe write stores when the list has run. +#[derive(Debug, Clone, Copy)] +pub(crate) enum Written { + Value(u64), + /// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the + /// process started (our GPU work is done on the CPU's timeline). + GpuTimestamp, + /// The CPU's performance counter. + SystemTimestamp, +} + +impl Written { + /// Stores the low `bytes` (4 or 8) of the value at `at`. + pub(crate) fn write(self, at: *mut u8, bytes: usize) { + let value = match self { + Written::Value(v) => v, + Written::GpuTimestamp => { + static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let elapsed = START.get_or_init(std::time::Instant::now).elapsed(); + (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64 + } + Written::SystemTimestamp => system_timestamp(), + }; + // SAFETY: the title names writable GPU memory (unified with ours). + unsafe { + if bytes == 4 { + at.cast::<u32>().write_unaligned(value as u32); + } else { + at.cast::<u64>().write_unaligned(value); + } + } + } +} + +fn system_timestamp() -> u64 { + #[cfg(windows)] + { + let mut count = 0; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) }; + count as u64 + } + #[cfg(not(windows))] + 0 +} + +/// Frames presented so far. +static FRAMES: AtomicU64 = AtomicU64::new(0); + +#[cfg(feature = "diagnostics")] +pub(crate) fn presented() -> u64 { + FRAMES.load(Ordering::Relaxed) +} + +/// Shows the first plane's first resource in our window. +/// +/// shortcut: one plane, no scaling or placement, the source expected in +/// the common state. +extern "system" fn present( + _: This, + planes: u32, + 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(); + #[cfg(windows)] + let (drawn, dispatched) = { + static DRAWN: AtomicU64 = AtomicU64::new(0); + static DISPATCHED: AtomicU64 = AtomicU64::new(0); + let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed); + ( + since(&DRAWN, crate::draw::drawn()), + since(&DISPATCHED, crate::draw::dispatched()), + ) + }; + #[cfg(not(windows))] + let (drawn, dispatched) = (0, 0); + tracing::info!( + frame, + draws, + drawn, + dispatches, + dispatched, + "frame presented (since the last line: draws and dispatches, and those run on the host)" + ); + #[cfg(windows)] + if frame >= 256 { + let (hits, misses) = crate::shader_cache::counts(); + tracing::info!(hits, misses, "shaders from the cache and translated so far"); + } + } + #[cfg(all(windows, feature = "diagnostics"))] + { + crate::capture::frame_drew(frame, crate::draw::drawn()); + if crate::capture::listed(frame) { + crate::capture::dump_targets(frame); + } + } + #[cfg(windows)] + if planes > 0 + // SAFETY: the title passes `planes` plane descriptions. + && let Some(plane) = unsafe { plane_parameters.as_ref() } + && plane.count > 0 + && !plane.resources.is_null() + // SAFETY: the plane lists `count` resources. + && let resource = unsafe { *plane.resources } + && let Some(texture) = crate::resource::host_resource(resource) + && let Some(host) = crate::host::host() + { + const COPY_SOURCE: u32 = 0x800; + let state = crate::resource::host_transition(resource, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); + let shown = host.present(texture, state, frame); + crate::resource::host_transition(resource, state); + #[cfg(feature = "diagnostics")] + blinks(frame, resource, state, shown); + #[cfg(not(feature = "diagnostics"))] + let _ = shown; + } + #[cfg(not(windows))] + let _ = (planes, plane_parameters); + S_OK +} +/// Diagnostics: logs a presented frame that is black after one that was +/// not, with what was presented and how many draws ran since. +#[cfg(all(windows, feature = "diagnostics"))] +fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) { + static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0)); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let drawn = crate::draw::drawn(); + let black = shown.unwrap_or(false); + let draws = crate::draw::take_frame(); + if black && !last.0 { + last.2 += 1; + tracing::warn!( + frame, + resource = ?resource, + state = format_args!("{state:#x}"), + draws = drawn - last.1, + copied = shown.is_some(), + black_frames = last.2, + levels = ?crate::capture::recent_levels(), + "a black frame after a frame that was not" + ); + for d in draws { + tracing::warn!("black frame {frame}: {d}"); + } + AFTER.store(frame + 6, Ordering::Relaxed); + } + // Six frames on: the levels around it (a fade or a single drop). + static AFTER: AtomicU64 = AtomicU64::new(0); + if AFTER.load(Ordering::Relaxed) == frame { + tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame"); + } + *last = (black, drawn, last.2); +} + +/// A run of destination pages: how they are mapped (0 pool pages from +/// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are) +/// and how many. +#[repr(C)] +pub(crate) struct PageRange { + kind: u32, + start: u32, + count: u32, +} + +/// The ranges mapped from a destination address on. +#[repr(C)] +pub(crate) struct PageBatch { + destination: u64, + count: u32, + ranges: *const PageRange, +} + +/// Bytes per mapped page. +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 +/// 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. +extern "system" fn copy_page_mappings( + _: This, + count: u32, + batches: *const PageBatch, + pool: u64, + pool_pages: u32, + _flags: u32, +) -> HRESULT { + let Some(map) = crate::resource::page_mapper() else { + return E_INVALIDARG; + }; + if batches.is_null() && count > 0 { + return E_INVALIDARG; + } + let batches = (count > 0).then(|| { + // SAFETY: the title passes `count` batches. + unsafe { std::slice::from_raw_parts(batches, count as usize) } + }); + let mut ok = true; + for b in batches.into_iter().flatten() { + if b.ranges.is_null() { + continue; + } + // SAFETY: each batch holds `count` ranges. + let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) }; + let mut at = b.destination; + for r in ranges { + let len = u64::from(r.count) * PAGE; + let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages); + let source = pool + u64::from(r.start) * PAGE; + ok &= match r.kind { + 0 if inside(r.count) => map(at, source, len), + 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)), + 2 => map(at, 0, len), + 3 => true, + _ => false, + }; + at += len; + } + } + 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")); + } + S_OK +} + +extern "system" fn desc(this: This, out: *mut QueueDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(queue(this).desc) }; + } +} + +/// The queue methods by their slot in older titles' queues (the 2020-era +/// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, +/// then console ones). +const METHODS: [(usize, *const ()); 15] = [ + (0, query as *const ()), + (2, release as *const ()), + (7, object::parent_device as *const ()), // 0x38 + (10, execute as *const ()), // 0x50 + (11, marker as *const ()), // 0x58 set marker + (12, marker as *const ()), // 0x60 begin event + (13, marker as *const ()), // 0x68 end event + (14, signal as *const ()), // 0x70 + (15, wait as *const ()), // 0x78 + (16, timestamp_frequency as *const ()), // 0x80 + (26, desc as *const ()), // 0xd0 + (29, copy_page_mappings as *const ()), // 0xe8 page mapping batch + (30, present as *const ()), // 0xf0 + (33, execute_x as *const ()), // 0x108 + (32, signal2_x as *const ()), // 0x100 +]; + +/// 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, +/// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume +/// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count, +/// lists, token, flags)` (title+0x24821dd). +const fn newer_slot(slot: usize) -> usize { + if slot >= 14 { slot + 2 } else { slot } +} + +const fn queue_table(newer: bool) -> [*const (); 36] { + let mut f = object::d3d12_object(object::missing_table::<QUEUE, 36>()); + let mut i = 0; + while i < METHODS.len() { + let (slot, method) = METHODS[i]; + f[if newer { newer_slot(slot) } else { slot }] = method; + i += 1; + } + f +} + +static FUNCTIONS: Table<36> = Table(queue_table(false)); +static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true)); + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + /// Where a queue's signal is: newer layouts have it two slots later. + /// Another test may switch layouts while this one runs, so the queue's + /// own table decides. + fn signal_slot(q: This) -> usize { + // SAFETY: one of our queues; its first field is the table. + let table = unsafe { *q.cast::<*const *const ()>() }; + if table == NEWER_FUNCTIONS.0.as_ptr() { + 0x80 + } else { + 0x70 + } + } + + #[test] + fn queue_signals_complete_at_once() { + let null = std::ptr::null(); + let desc = QueueDesc { + kind: 0, + priority: 0, + flags: 0, + nodes: 0, + }; + let mut q = null; + assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + // SAFETY: the title reads the type at +0x10. + assert_eq!(unsafe { q.cast::<u8>().add(0x10).cast::<u32>().read() }, 0); + let mut fence = null; + let fence_iid = &crate::fence::FENCE_IIDS[0]; + assert_eq!( + crate::fence::create(null, 0, 0, fence_iid, &mut fence), + S_OK + ); + let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, signal_slot(q)); + assert_eq!(signal(q, fence, 7), S_OK); + assert_eq!( + slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence), + 7 + ); + assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0); + } + + /// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. + #[test] + fn console_queues_are_created_as_on_pc() { + let null = std::ptr::null(); + let desc = QueueDescX { + kind: 2, + flags: 0, + engine_or_pipe: 1, + queue: 0, + }; + let mut q = null; + assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + assert_eq!(queue(q).desc.kind, 2); + let none = std::ptr::null(); + assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG); + } + + #[test] + fn newer_queues_have_their_methods_two_slots_later() { + let (old, new) = (queue_table(false), queue_table(true)); + assert_eq!(old[10], new[10]); // submission stays at 0x50 + assert_eq!(old[14], new[16]); // signal 0x70 → 0x80 + assert_eq!(old[30], new[32]); // present 0xf0 → 0x100 + assert_eq!(new[35], execute_x as *const ()); // 0x118 + } + + #[test] + fn timestamps_and_values_are_written() { + let mut at = [0u64; 2]; + Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4); + assert_eq!(at[0], 2); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); + let first = at[1]; + std::thread::sleep(std::time::Duration::from_millis(2)); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); + assert!(at[1] > first); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs new file mode 100644 index 000000000..3782a0d70 --- /dev/null +++ b/crates/victory-gpu/src/resource.rs @@ -0,0 +1,3410 @@ +//! Heaps, committed and placed resources, and resource sizes. +//! +//! Heaps and resources are host memory and a resource's GPU address is its +//! CPU address, as on the console; textures also get a host copy, and +//! buffers a host copy when a draw reads them (`shadow`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::{Layout, alloc_zeroed, dealloc}; +use std::ffi::c_void; +use std::ptr::NonNull; + +use victory_formats::texture; + +use crate::object::{ + self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This, + guid, +}; + +/// The interfaces every device child also answers for. +pub(crate) const PAGEABLE_IIDS: [Iid; 3] = [ + guid( + 0x63ee58fb, + 0x1268, + 0x4835, + [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6], + ), + guid( + 0x905db94b, + 0xa00c, + 0x4140, + [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57], + ), + guid( + 0xc4fec28f, + 0x7966, + 0x4e95, + [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8], + ), +]; +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x6b3b2502, + 0x6e51, + 0x45b3, + [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; +const RESOURCE_IIDS: [Iid; 4] = [ + guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +const KIB_64: u64 = 64 << 10; +const MIB_4: u64 = 4 << 20; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapProperties { + kind: u32, + cpu_pages: u32, + pool: u32, + creation_nodes: u32, + visible_nodes: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapDesc { + size: u64, + properties: HeapProperties, + alignment: u64, + flags: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct ResourceDesc { + dimension: u32, + alignment: u64, + width: u64, + height: u32, + depth_or_array_size: u16, + mip_levels: u16, + format: u32, + sample_count: u32, + sample_quality: u32, + layout: u32, + flags: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct AllocationInfo { + size: u64, + alignment: u64, +} + +const _: () = assert!(size_of::<HeapProperties>() == 20); +const _: () = assert!(size_of::<HeapDesc>() == 48); +const _: () = assert!(size_of::<ResourceDesc>() == 56); + +const BUFFER: u32 = 1; +const TEXTURE_3D: u32 = 4; + +/// Bytes per element and the element's width in texels (4 for block +/// compression), by DXGI format number. `None` for 1-bit and video +/// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit +/// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed +/// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color). +pub(crate) fn element(format: u32) -> Option<(u64, u64)> { + Some(match format { + 1..=4 => (16, 1), + 5..=8 => (12, 1), + 9..=22 => (8, 1), + 23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1), + 118..=120 => (3, 1), + 48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1), + 60..=65 | 190 => (1, 1), + 70..=72 | 79..=81 => (8, 4), + 73..=78 | 82..=84 | 94..=99 => (16, 4), + _ => return None, + }) +} + +/// A texture's layout in console memory, as the console's layout library +/// gives it (`victory-hle`'s `xg` serves the same): the description's +/// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick. +pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option<texture::Texture> { + use texture::{Dimension, Swizzle, TextureDesc}; + const TEXTURE_1D: u32 = 2; + const TEXTURE_2D: u32 = 3; + const RENDER_TARGET: u32 = 1; + const DEPTH: u32 = 2; + let dimension = match desc.dimension { + TEXTURE_1D => Dimension::Tex1d, + TEXTURE_2D => Dimension::Tex2d, + TEXTURE_3D => Dimension::Tex3d, + _ => return None, + }; + let swizzle = match desc.layout { + 0 if dimension == Dimension::Tex1d => Swizzle::LINEAR, + 0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X, + 0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X, + 0 => Swizzle::SW_4KB_S, + 1 => Swizzle::LINEAR, + l if l & !0xff == 0x100 => Swizzle(l & 0xff), + _ => return None, + }; + texture::Texture::new(&TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array_size), + mips: u32::from(desc.mip_levels), + format: desc.format, + samples: desc.sample_count.max(1), + swizzle, + }) + .ok() +} + +/// Bytes and alignment a resource takes: buffers their width (64 KiB +/// aligned), textures their console layout (formats it does not know: +/// every mip of every array slice and sample, packed, 64 KiB aligned), +/// rounded up to the alignment. +fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> { + if desc.dimension != BUFFER + && 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 + // asserts when they disagree with the streamed layout. + let alignment = desc.alignment.max(t.alignment); + if !alignment.is_power_of_two() { + return None; + } + return Some(AllocationInfo { + size: t.size.checked_next_multiple_of(alignment)?, + alignment, + }); + } + let bytes = if desc.dimension == BUFFER { + desc.width + } else { + let (element, block) = element(desc.format)?; + let (depth, slices) = if desc.dimension == TEXTURE_3D { + (u64::from(desc.depth_or_array_size), 1) + } else { + (1, u64::from(desc.depth_or_array_size)) + }; + let height = u64::from(desc.height); + let mips = mip_count(desc); + let mut chain = 0u64; + for mip in 0..mips.min(64) { + let w = (desc.width >> mip).max(1).div_ceil(block); + let h = (height >> mip).max(1).div_ceil(block); + let d = (depth >> mip).max(1); + chain = chain.checked_add(w.checked_mul(h)?.checked_mul(d)?.checked_mul(element)?)?; + } + chain + .checked_mul(slices)? + .checked_mul(u64::from(desc.sample_count.max(1)))? + }; + if bytes == 0 { + return None; + } + let minimum = if desc.sample_count > 1 { MIB_4 } else { KIB_64 }; + let alignment = desc.alignment.max(minimum); + if !alignment.is_power_of_two() { + return None; + } + Some(AllocationInfo { + size: bytes.checked_next_multiple_of(KIB_64)?, + alignment, + }) +} + +/// 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. +pub(crate) fn pc_format(format: u32) -> u32 { + match format { + 118 => 45, + 119 => 46, + 120 => 47, + other => other, + } +} + +/// 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 Grand Theft +/// Auto VI 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 (Grand +/// Theft Auto VI'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<HostTexture>, + /// 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<windows::Win32::Graphics::Direct3D12::ID3D12Resource>, + /// 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<std::sync::Arc<HostTexture>>, +} + +#[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<std::sync::Arc<Twin>> { + 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<std::sync::Arc<Twin>> { + 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<bool> = 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<bool> = 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<ID3D12Resource> = 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<bool> = 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<ID3D12Resource> = 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), + (5, 8), + (9, 14), + (15, 18), + (19, 22), + (23, 25), + (27, 32), + (33, 38), + (39, 43), + (44, 47), + (48, 52), + (53, 59), + (60, 65), + (70, 72), + (73, 75), + (76, 78), + (79, 81), + (82, 84), + (90, 91), + (92, 93), + (94, 96), + (97, 99), + ]; + match format { + 87 => 90, + 88 => 92, + f => FAMILIES + .iter() + .find(|&&(first, last)| (first..=last).contains(&f)) + .map_or(f, |&(first, _)| first), + } +} + +/// sRGB formats and their linear twins. +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. +pub(crate) fn view_format(this: This) -> Option<u32> { + // 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; + // 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. +pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)]; + +/// Mip levels, the full chain for 0. +fn mip_count(desc: &ResourceDesc) -> u32 { + let depth = if desc.dimension == TEXTURE_3D { + u64::from(desc.depth_or_array_size) + } else { + 1 + }; + match desc.mip_levels { + 0 => { + 64 - desc + .width + .max(u64::from(desc.height)) + .max(depth) + .max(1) + .leading_zeros() + } + n => u32::from(n), + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct PlacedFootprint { + pub(crate) offset: u64, + format: u32, + width: u32, + height: u32, + depth: u32, + row_pitch: u32, +} + +impl PlacedFootprint { + /// The bytes it spans in a buffer: every row pitched but the last. + pub(crate) fn bytes(&self) -> Option<u64> { + 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::<PlacedFootprint>() == 32); + +const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint { + offset: u64::MAX, + format: 0, + width: 0, + height: 0, + depth: 0, + row_pitch: 0, +}; + +/// One subresource's size in an upload buffer: footprint (offset 0), rows +/// and bytes per row. Planes of depth-stencil formats are not told apart. +fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> { + const PITCH: u64 = 256; + if desc.dimension == BUFFER { + let footprint = PlacedFootprint { + offset: 0, + format: 0, + width: u32::try_from(desc.width).ok()?, + height: 1, + depth: 1, + row_pitch: u32::try_from(desc.width.next_multiple_of(PITCH)).ok()?, + }; + return (index == 0).then_some((footprint, 1, desc.width)); + } + let mips = mip_count(desc); + let slices = if desc.dimension == TEXTURE_3D { + 1 + } else { + u32::from(desc.depth_or_array_size).max(1) + }; + let (mip, slice) = (index % mips, index / mips); + if slice >= slices { + return None; + } + let (element, block) = element(desc.format)?; + let width = (desc.width >> mip).max(1).next_multiple_of(block); + let height = (u64::from(desc.height) >> mip) + .max(1) + .next_multiple_of(block); + let depth = if desc.dimension == TEXTURE_3D { + (u32::from(desc.depth_or_array_size) >> mip).max(1) + } else { + 1 + }; + let row_size = width / block * element; + let footprint = PlacedFootprint { + offset: 0, + format: desc.format, + width: u32::try_from(width).ok()?, + height: u32::try_from(height).ok()?, + depth, + row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?, + }; + Some((footprint, u32::try_from(height / block).ok()?, row_size)) +} + +/// Device method: where each subresource goes in an upload buffer, rows +/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give +/// the documented all-ones values. +pub(crate) extern "system" fn copyable_footprints( + _: This, + desc: *const ResourceDesc, + first: u32, + count: u32, + base: u64, + layouts: *mut PlacedFootprint, + rows: *mut u32, + row_sizes: *mut u64, + total: *mut u64, +) { + const PLACEMENT: u64 = 512; + // SAFETY: the title passes a description (null is tolerated). + let desc = unsafe { desc.as_ref() }; + let mut end = base; + let mut known = desc.is_some(); + for i in 0..count { + let one = desc.and_then(|d| subresource(d, first + i)); + let (layout, row_count, row_size) = match one { + Some((mut footprint, row_count, row_size)) => { + footprint.offset = end.next_multiple_of(PLACEMENT); + let pitch = u64::from(footprint.row_pitch); + let lines = u64::from(row_count) * u64::from(footprint.depth); + end = footprint.offset + pitch * lines.saturating_sub(1) + row_size; + (footprint, row_count, row_size) + } + None => { + known = false; + (NO_FOOTPRINT, u32::MAX, u64::MAX) + } + }; + let i = i as usize; + // SAFETY: each output is null or holds `count` entries. + unsafe { + if !layouts.is_null() { + layouts.add(i).write(layout); + } + if !rows.is_null() { + rows.add(i).write(row_count); + } + if !row_sizes.is_null() { + row_sizes.add(i).write(row_size); + } + } + } + if !known { + tracing::warn!(?desc, "no footprint for this resource"); + } + if !total.is_null() { + // SAFETY: checked non-null. + unsafe { total.write(if known { end - base } else { u64::MAX }) }; + } +} + +/// Device method: the footprint of resources placed one after another. +/// Returns a 16-byte value, through a hidden first argument. Invalid input +/// gives the documented size `u64::MAX`. +pub(crate) extern "system" fn allocation_info( + out: *mut AllocationInfo, + _: This, + _visible: u32, + count: u32, + descs: *const ResourceDesc, +) -> *mut AllocationInfo { + let descs = if descs.is_null() { + &[][..] + } else { + // SAFETY: the title passes `count` descriptions. + unsafe { std::slice::from_raw_parts(descs, count as usize) } + }; + // SAFETY: the caller passes room for the value. + unsafe { out.write(place(descs.iter(), |_, _| ())) }; + out +} + +/// The newer description: the plain one, then a sampler feedback mip +/// region (width, height, depth). +#[repr(C)] +pub(crate) struct ResourceDesc1 { + desc: ResourceDesc, + mip_region: [u32; 3], +} +const _: () = assert!(size_of::<ResourceDesc1>() == 72); + +/// Where one resource goes in [`allocation_info2`]'s placement. +#[repr(C)] +pub(crate) struct AllocationInfo1 { + offset: u64, + alignment: u64, + size: u64, +} + +/// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer +/// descriptions, also telling where each resource goes. +pub(crate) extern "system" fn allocation_info2( + out: *mut AllocationInfo, + _: This, + _visible: u32, + count: u32, + descs: *const ResourceDesc1, + each: *mut AllocationInfo1, +) -> *mut AllocationInfo { + let descs = if descs.is_null() { + &[][..] + } else { + // SAFETY: the title passes `count` descriptions. + unsafe { std::slice::from_raw_parts(descs, count as usize) } + }; + let total = place(descs.iter().map(|d| &d.desc), |i, info| { + if !each.is_null() { + // SAFETY: the title passes room for `count` entries. + unsafe { each.add(i).write(info) }; + } + }); + // SAFETY: the caller passes room for the value. + unsafe { out.write(total) }; + out +} + +/// Resources placed one after another: the whole footprint, telling `each` +/// where every resource goes. Unknown sizes give the documented `u64::MAX`. +fn place<'a>( + descs: impl Iterator<Item = &'a ResourceDesc>, + mut each: impl FnMut(usize, AllocationInfo1), +) -> AllocationInfo { + let mut total = AllocationInfo { + size: 0, + alignment: KIB_64, + }; + for (i, desc) in descs.enumerate() { + let Some(one) = footprint(desc) else { + tracing::warn!(?desc, "no size for this resource"); + each( + i, + AllocationInfo1 { + offset: u64::MAX, + alignment: 0, + size: u64::MAX, + }, + ); + return AllocationInfo { + size: u64::MAX, + alignment: 0, + }; + }; + tracing::debug!(?desc, ?one, "allocation info"); + let offset = total.size.next_multiple_of(one.alignment); + each( + i, + AllocationInfo1 { + offset, + alignment: one.alignment, + size: one.size, + }, + ); + total.size = offset + one.size; + total.alignment = total.alignment.max(one.alignment); + } + total +} + +/// Zeroed host memory standing in for GPU memory. +pub(crate) struct Memory { + ptr: NonNull<u8>, + layout: Layout, + /// Set when the memory came from the title's allocator, with these + /// allocation attributes (it goes back there). + attributes: Option<u64>, +} + +pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; +pub type FreeRoutine = extern "system" fn(*mut c_void, u64); +static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new(); + +/// 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 +/// 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) { + let _ = ALLOCATOR.set((alloc, free)); +} + +/// Maps the physical pages behind one range of title memory at another, +/// `(to, from, len)` (`from` 0 unmaps); false on failure. +pub type PageMapper = fn(u64, u64, u64) -> bool; +static PAGE_MAPPER: std::sync::OnceLock<PageMapper> = std::sync::OnceLock::new(); + +/// The runtime's page mapper, for the queues' page-mapping copies (memory +/// is the runtime's, as on the console). +pub fn use_page_mapper(mapper: PageMapper) { + let _ = PAGE_MAPPER.set(mapper); +} + +pub(crate) fn page_mapper() -> Option<PageMapper> { + PAGE_MAPPER.get().copied() +} + +/// Allocation attributes for resource memory: allocator id, page size +/// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2 +/// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only +/// heaps, cacheable for the CPU-visible ones). +/// shortcut: the console runtime's own choice of page size and memory type +/// is not known; this is the plausible one. +fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 { + const GRAPHICS_ALLOCATOR: u64 = 128 << 16; + const DEFAULT_HEAP: u32 = 1; + let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 }; + let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 }; + let alignment = u64::from(info.alignment.max(1).trailing_zeros()); + GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29 +} + +impl Memory { + /// A committed resource's memory: from the title's allocator if the + /// runtime named one, else our own; zeroed either way. + fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result<Memory, HRESULT> { + let Some(&(alloc, _)) = ALLOCATOR.get() else { + return Memory::new(info); + }; + let layout = Layout::from_size_align(info.size as usize, info.alignment as usize) + .map_err(|_| E_INVALIDARG)?; + let attributes = resource_attributes(info, heap_kind); + let ptr = + NonNull::new(alloc(layout.size(), attributes).cast::<u8>()).ok_or(E_OUTOFMEMORY)?; + // SAFETY: the allocator handed out `size` bytes. + unsafe { ptr.as_ptr().write_bytes(0, layout.size()) }; + Ok(Memory { + ptr, + layout, + attributes: Some(attributes), + }) + } + + /// `size` zeroed bytes aligned to `alignment` (a power of two). + pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> { + Memory::new(AllocationInfo { size, alignment }) + } + + pub(crate) fn address(&self) -> u64 { + self.ptr.as_ptr() as u64 + } + + fn new(info: AllocationInfo) -> Result<Memory, HRESULT> { + let layout = usize::try_from(info.size) + .ok() + .zip(usize::try_from(info.alignment).ok()) + .filter(|&(size, _)| size > 0) + .and_then(|(size, align)| Layout::from_size_align(size, align).ok()) + .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, + attributes: None, + }) + } +} + +impl Drop for Memory { + fn drop(&mut self) { + match (self.attributes, ALLOCATOR.get()) { + (Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes), + // SAFETY: allocated in `new` with this layout. + _ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) }, + } + } +} + +#[repr(C)] +struct Heap { + object: Object, + desc: HeapDesc, + memory: Memory, +} + +pub(crate) extern "system" fn create_heap( + _: This, + desc: *const HeapDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!( + size = desc.size, + kind = desc.properties.kind, + flags = format_args!("{:#x}", desc.flags), + "heap" + ); + if desc.alignment != 0 && !desc.alignment.is_power_of_two() { + return E_INVALIDARG; + } + let info = AllocationInfo { + size: desc.size, + alignment: desc.alignment.max(KIB_64), + }; + let memory = match Memory::new(info) { + Ok(memory) => memory, + Err(hr) => return hr, + }; + let heap = Box::new(Heap { + object: Object::new(&HEAP_FUNCTIONS), + desc, + memory, + }); + object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn heap_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer(HEAP, iid, object::is(iid, &HEAP_IIDS).then_some(this), out) +} +extern "system" fn heap_release(this: This) -> u32 { + object::release_boxed::<Heap>(this) +} +extern "system" fn heap_desc(this: This, out: *mut HeapDesc) { + if !out.is_null() { + // SAFETY: `this` is a heap; the title passes room for a description. + unsafe { out.write((*this.cast::<Heap>()).desc) }; + } +} + +/// A resource's memory: its own, or a range of a heap it holds a reference +/// to. +enum Backing { + Committed(Memory), + Placed { + heap: This, + offset: u64, + }, + /// Memory the title mapped itself, at this address. + Address(*mut u8), +} + +impl Drop for Backing { + fn drop(&mut self) { + if let Backing::Placed { heap, .. } = *self { + heap_release(heap); + } + } +} + +#[repr(C)] +struct Resource { + object: Object, + desc: ResourceDesc, + heap: HeapProperties, + heap_flags: u32, + backing: Backing, + /// Textures also live on the host GPU (decision 0007); buffers do not + /// yet. With, for a depth texture the title also writes as unordered + /// access, the colour texture shaders write instead ([`Twin`]). + #[cfg(windows)] + host: Hosted, +} + +/// A title texture's host copy and the state it is in. The title's barriers +/// name console states (looser than the host's), so we transition from this +/// one. Lists that use the texture hold it until they are reset: the title +/// may release a resource whose commands it recorded but not yet submitted +/// (console memory outlives the object; a host texture must outlive the +/// lists that name it). +#[cfg(windows)] +pub(crate) struct HostTexture { + pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + pub(crate) state: std::sync::atomic::AtomicU32, + /// 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)] +type Made = (std::sync::Arc<HostTexture>, Option<std::sync::Arc<Twin>>); + +/// A title texture's host side. The host copy is made when something first +/// uses the texture, not when the title creates it: Grand Theft Auto VI +/// 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<Option<Made>>, + /// 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]; + +/// 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::collections::BTreeSet<usize>> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +#[cfg(windows)] +fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet<usize>> { + TEXTURES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// 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)] +static TARGETS_AT: std::sync::Mutex<std::collections::BTreeMap<u64, usize>> = + 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 +/// (Grand Theft Auto VI 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<This> { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock<bool> = 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; + } + static WHOLE: std::sync::OnceLock<bool> = 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; + } + // 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<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_TEXTURES").is_none_or(|v| v != "0")) +} + +/// 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)] +fn fills(desc: &ResourceDesc) -> bool { + const TARGET_DEPTH_UNORDERED: u32 = 0x7; + desc.dimension != BUFFER && desc.flags & TARGET_DEPTH_UNORDERED == 0 +} + +/// 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) +} + +/// 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)] +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() +} + +/// 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 hosted(this: This, make: bool) -> Option<Made> { + 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::<c_void>()); + 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) }) +} + +/// 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 +/// (`VICTORY_TEXTURE_BUDGET_MB` sets a limit on those copies' bytes +/// instead). Past the budget the system moves the card's memory into the +/// PC's, which ended runs 20 and 24. +#[cfg(windows)] +pub(crate) fn room() -> bool { + use std::sync::atomic::Ordering::Relaxed; + const FLOOR: u64 = 2 << 30; + const WITHOUT_BUDGET: u64 = 4 << 30; + static LIMIT: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?; + mb.trim().parse::<u64>().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 / 10 * 9, + None => filled < WITHOUT_BUDGET, + } +} + +/// 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_MS: u64 = 5_000; + const IDLE_FRAMES: u64 = 4; + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return; + } + // 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 + } + }; + 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); + } + } + } + count +} + +/// Host textures alive (the title's and the twins) and the bytes the host +/// gives them, for the memory line. +#[cfg(windows)] +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 + } +} + +#[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, + } + } +} + +#[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); + } + } +} + +/// 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 +/// resource and the state it leaves, if that is a change. +#[cfg(windows)] +pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { + use windows::core::Interface; + 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: 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, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + 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. +#[cfg(windows)] +pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> { + if this.is_null() { + return None; + } + hosted(this, true).map(|made| made.0) +} + +/// A host texture like the title's: same description, in GPU memory, +/// without the console's layout and flags. +#[cfg(windows)] +fn host_texture( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, +) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + use windows::Win32::Graphics::Direct3D12::*; + const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access + if desc.dimension == BUFFER { + return None; + } + let host = crate::host::host()?; + let mut d = *desc; + d.layout = 0; + 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). + // 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) + { + d.format = typeless; + } + // The host has no sRGB unordered access: such textures are typeless, + // their unordered access views plain UNORM. + if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { + d.format = family(d.format); + } + // The clear value names the format too: format, then color or depth + // 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 heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option<ID3D12Resource> = 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, "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) + }); + } + texture +} + +/// A texture's console memory and description; `None` for buffers. +pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) +} + +/// A buffer's host memory and size; `None` for textures. +pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width)) +} + +impl Resource { + fn data(&self) -> *mut u8 { + match self.backing { + Backing::Committed(ref memory) => memory.ptr.as_ptr(), + // SAFETY: placement checked the range lies inside the heap. + Backing::Placed { heap, offset } => unsafe { + (*heap.cast::<Heap>()) + .memory + .ptr + .as_ptr() + .add(offset as usize) + }, + Backing::Address(at) => at, + } + } +} + +fn resource<'a>(this: This) -> &'a Resource { + // SAFETY: called from resource methods only. + unsafe { &*this.cast::<Resource>() } +} + +// The creation methods' own arguments, passed on. +#[allow(clippy::too_many_arguments)] +fn hand_out_resource( + desc: ResourceDesc, + heap: HeapProperties, + heap_flags: u32, + backing: Backing, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + #[cfg(not(windows))] + let _ = (state, clear); + let resource = Box::new(Resource { + object: Object::new(&RESOURCE_FUNCTIONS), + desc, + heap, + heap_flags, + backing, + #[cfg(windows)] + 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>(&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>(&resource) as usize; + crate::shadow::register(at, resource.data() as u64, desc.width); + } + object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out) +} + +#[cfg(windows)] +impl Drop for Resource { + fn drop(&mut 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::<Resource>(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::<Resource>(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) + { + // Before lists held their textures, this freed a texture that + // lists not yet run still named (a GPU page fault). + static OUTLIVED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = OUTLIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + desc = ?self.desc, + "a title texture was released while a list not yet reset names its host copy" + ); + } + } + // 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::<Resource>(self) as usize); + crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize); + if self.desc.dimension == BUFFER { + crate::shadow::unregister( + std::ptr::from_ref::<Resource>(self) as usize, + self.data() as u64, + ); + } + } +} + +pub(crate) extern "system" fn create_committed( + _: This, + heap: *const HeapProperties, + heap_flags: u32, + desc: *const ResourceDesc, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes both descriptions (null is tolerated). + let (Some(&heap), Some(&desc)) = (unsafe { (heap.as_ref(), desc.as_ref()) }) else { + return E_INVALIDARG; + }; + let Some(info) = footprint(&desc) else { + tracing::warn!(?desc, "no size for this resource"); + return E_INVALIDARG; + }; + tracing::debug!( + dimension = desc.dimension, + size = info.size, + heap = heap.kind, + "committed resource" + ); + let memory = match Memory::for_resource(info, heap.kind) { + Ok(memory) => memory, + Err(hr) => return hr, + }; + hand_out_resource( + desc, + heap, + heap_flags, + Backing::Committed(memory), + state, + clear, + iid, + out, + ) +} + +/// Device method 0x3f8, inferred from Grand Theft Auto VI'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 +/// session, castable format count, castable formats, iid, out)`. The host +/// copy starts in the common state, as layouts are not tracked. +#[allow(clippy::too_many_arguments)] // the method's own arguments +pub(crate) extern "system" fn create_committed3( + this: This, + heap: *const HeapProperties, + heap_flags: u32, + desc: *const ResourceDesc, + _layout: u32, + clear: *const c_void, + _protected: This, + _castable_count: u32, + _castable: *const u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + const COMMON: u32 = 0; + create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out) +} + +/// Registered page pools (64 KiB pages the title maps into tiled +/// resources by page index): first address and page count; a handle is an +/// index plus one, a removed pool leaves `None`. +static PAGE_POOLS: std::sync::Mutex<Vec<Option<(u64, u32)>>> = std::sync::Mutex::new(Vec::new()); + +fn page_pools() -> std::sync::MutexGuard<'static, Vec<Option<(u64, u32)>>> { + PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Device method 0x250: `(address, page count, handle out)`. +pub(crate) extern "system" fn register_page_pool( + _: This, + address: u64, + pages: u32, + out: *mut usize, +) -> HRESULT { + if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) { + return E_INVALIDARG; + } + tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool"); + let mut pools = page_pools(); + pools.push(Some((address, pages))); + // SAFETY: checked non-null; the title passes room for a handle. + unsafe { out.write(pools.len()) }; + S_OK +} + +/// Device method 0x258. +pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT { + match page_pools().get_mut(handle.wrapping_sub(1)) { + Some(pool @ Some(_)) => { + *pool = None; + S_OK + } + _ => E_INVALIDARG, + } +} + +/// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11` +/// additions. From Grand Theft Auto VI'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 +/// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain +/// description; its sampler feedback region is not needed. +pub(crate) extern "system" fn create_at_address( + _: This, + address: u64, + desc: *const ResourceDesc, + layout: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if address == 0 { + return E_INVALIDARG; + } + tracing::debug!( + address = format_args!("{address:#x}"), + dimension = desc.dimension, + width = desc.width, + layout, + "resource at an address" + ); + const COMMON: u32 = 0; + const DEFAULT: HeapProperties = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 1, + visible_nodes: 1, + }; + hand_out_resource( + desc, + DEFAULT, + 0, + Backing::Address(address as *mut u8), + COMMON, + clear, + iid, + out, + ) +} + +/// Textures the title placed in its own memory and views without a +/// resource object (device 0x230, Grand Theft Auto VI's streamed and +/// interface textures), by address and description: a resource at that +/// address, made the first time a draw reads one. +/// 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::collections::BTreeMap<(u64, [u32; 14]), usize>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// 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<u64> { + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + footprint(&d).map(|f| f.size) +} + +/// 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<This> { + let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&r) = map.get(&(address, *desc)) { + return Some(r as This); + } + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + let mut out = std::ptr::null(); + let made = create_at_address( + std::ptr::null(), + address, + &d, + 0, + std::ptr::null(), + &RESOURCE_IIDS[0], + &mut out, + ); + if made != S_OK { + return None; + } + map.insert((address, *desc), out as usize); + resource(out) + .host + .placed + .store(true, std::sync::atomic::Ordering::Relaxed); + Some(out) +} + +pub(crate) extern "system" fn create_placed( + _: This, + heap: This, + offset: u64, + desc: *const ResourceDesc, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if heap.is_null() { + return E_INVALIDARG; + } + // SAFETY: the title passes one of our heaps. + let h = unsafe { &*heap.cast::<Heap>() }; + let fits = footprint(&desc).is_some_and(|info| { + offset.is_multiple_of(info.alignment) + && offset + .checked_add(info.size) + .is_some_and(|end| end <= h.desc.size) + }); + if !fits { + tracing::warn!( + ?desc, + offset, + heap = h.desc.size, + "placed resource does not fit" + ); + return E_INVALIDARG; + } + object::add_ref(heap); + let backing = Backing::Placed { heap, offset }; + hand_out_resource( + desc, + h.desc.properties, + h.desc.flags, + backing, + state, + clear, + iid, + out, + ) +} + +extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + RESOURCE, + iid, + object::is(iid, &RESOURCE_IIDS).then_some(this), + out, + ) +} +extern "system" fn resource_release(this: This) -> u32 { + object::release_boxed::<Resource>(this) +} +/// Memory is always mapped (subresources are not told apart yet); a null +/// `out` only asks for residency. +extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *mut u8) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(resource(this).data()) }; + } + S_OK +} +extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {} +extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(resource(this).desc) }; + } +} +/// Device method `GetCustomHeapProperties`, returning its struct through a +/// hidden first argument: what a standard heap type is as a custom heap. +/// Memory is unified and cache-coherent (as the architecture query says), +/// so every type is in pool L0, default heaps are not CPU-visible and the +/// others are write-back. +pub(crate) extern "system" fn custom_heap_properties( + out: *mut HeapProperties, + _: This, + nodes: u32, + kind: u32, +) -> *mut HeapProperties { + const CUSTOM: u32 = 4; + const NOT_AVAILABLE: u32 = 1; + const WRITE_BACK: u32 = 3; + const L0: u32 = 1; + let nodes = nodes.max(1); + let cpu_pages = match kind { + 1 => NOT_AVAILABLE, + 2 | 3 => WRITE_BACK, + _ => 0, + }; + let properties = HeapProperties { + kind: CUSTOM, + cpu_pages, + pool: if cpu_pages == 0 { 0 } else { L0 }, + creation_nodes: nodes, + visible_nodes: nodes, + }; + // SAFETY: the title passes room for the result (null is tolerated). + if let Some(out) = unsafe { out.as_mut() } { + *out = properties; + } + out +} + +extern "system" fn gpu_address(this: This) -> u64 { + let r = resource(this); + let at = r.data() as u64; + // The console's GPU addresses fit in 40 bits; its ray-tracing builder + // refuses others (diagnostics: which memory breaks that). + #[cfg(feature = "diagnostics")] + if at >> 40 != 0 { + static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()]; + let backing = match r.backing { + Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes), + Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"), + Backing::Address(_) => "at a title address".into(), + }; + ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| { + tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits") + }); + } + at +} +extern "system" fn heap_properties( + this: This, + properties: *mut HeapProperties, + flags: *mut u32, +) -> HRESULT { + let r = resource(this); + // SAFETY: either pointer may be null; otherwise the title passes room. + unsafe { + if let Some(p) = properties.as_mut() { + *p = r.heap; + } + if let Some(f) = flags.as_mut() { + *f = r.heap_flags; + } + } + S_OK +} + +/// IUnknown 3, object 4, device child 1, heap 1. +static HEAP_FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<HEAP, 24>()); + f[0] = heap_query as *const (); + f[2] = heap_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = heap_desc as *const (); // 0x40 + Table(f) +}; + +/// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3 +/// console ones). +static RESOURCE_FUNCTIONS: Table<32> = { + let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 32>()); + f[0] = resource_query as *const (); + f[2] = resource_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = map as *const (); // 0x40 + f[9] = unmap as *const (); // 0x48 + f[10] = resource_desc as *const (); // 0x50 + f[11] = gpu_address as *const (); // 0x58 + f[14] = heap_properties as *const (); // 0x70 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + type Release = extern "system" fn(This) -> u32; + type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT; + type Address = extern "system" fn(This) -> u64; + + const PROPERTIES: HeapProperties = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 0, + visible_nodes: 0, + }; + + fn buffer(width: u64) -> ResourceDesc { + ResourceDesc { + dimension: BUFFER, + alignment: 0, + width, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format: 0, + sample_count: 1, + sample_quality: 0, + layout: 1, + flags: 0, + } + } + + fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc { + ResourceDesc { + dimension: 3, + width, + height, + format, + mip_levels: mips, + layout: 0, + ..buffer(0) + } + } + + fn heap(size: u64) -> This { + let desc = HeapDesc { + size, + properties: PROPERTIES, + alignment: 0, + flags: 0, + }; + let mut heap = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &desc, &HEAP_IIDS[0], &mut heap), + S_OK + ); + heap + } + + #[test] + fn heaps_are_zeroed_aligned_memory() { + let heap = heap(1 << 20); + // SAFETY: a heap we just made. + let memory = unsafe { &(*heap.cast::<Heap>()).memory }; + assert_eq!(memory.ptr.as_ptr() as u64 % KIB_64, 0); + let mut back = std::mem::MaybeUninit::<HeapDesc>::uninit(); + slot::<extern "system" fn(This, *mut HeapDesc)>(heap, 0x40)(heap, back.as_mut_ptr()); + // SAFETY: written above. + assert_eq!(unsafe { back.assume_init() }.size, 1 << 20); + assert_eq!(slot::<Release>(heap, 0x10)(heap), 0); + + let bad = HeapDesc { + size: 1 << 20, + properties: PROPERTIES, + alignment: 3, + flags: 0, + }; + let mut out = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &bad, &HEAP_IIDS[0], &mut out), + E_INVALIDARG + ); + } + + #[test] + fn device_setup_heap_properties_and_resources_at_addresses() { + let device = crate::device::device(); + // GetCustomHeapProperties (0xd0): the struct comes back through the + // hidden first argument, which is also returned. + type Custom = + extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties; + let mut p = PROPERTIES; + let back = slot::<Custom>(device, 0xd0)(&mut p, device, 1, 2); + assert_eq!(back, &raw mut p); + assert_eq!( + ( + p.kind, + p.cpu_pages, + p.pool, + p.creation_nodes, + p.visible_nodes + ), + (4, 3, 1, 1, 1), + "upload: custom, write-back, L0" + ); + slot::<Custom>(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. + type At = extern "system" fn( + This, + u64, + *const ResourceDesc, + u32, + *const c_void, + *const Iid, + *mut This, + ) -> HRESULT; + let memory = vec![0u8; 0x1_0000]; + let address = memory.as_ptr() as u64; + let mut r = std::ptr::null(); + let create = slot::<At>(device, 0x428); + let desc = buffer(0x1_0000); + let null = std::ptr::null(); + assert_eq!( + create( + device, + address, + &desc, + u32::MAX, + null, + &RESOURCE_IIDS[0], + &mut r + ), + 0 + ); + assert_eq!(slot::<Address>(r, 0x58)(r), address); + assert_eq!(slot::<Release>(r, 0x10)(r), 0); + // The title's memory is still there after the release. + assert_eq!(memory[0xffff], 0); + assert_ne!( + create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r), + 0 + ); + } + + #[test] + fn sizes_cover_every_mip() { + let size = |d: &ResourceDesc| footprint(d).map(|i| i.size); + assert_eq!(size(&buffer(256)), Some(KIB_64)); + // Textures take their console layout and its alignment (4 KiB + // standard swizzle when the description leaves it to the library): + // 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on + // the console. + let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size; + let rgba = texture(256, 256, 28, 0); + assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096))); + let bc7 = footprint(&texture(512, 512, 98, 10)); + let console = AllocationInfo { + size: 0x56000, + alignment: 0x1000, + }; + assert_eq!(bc7, Some(console)); + assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip"); + // BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB. + assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10)); + assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format"); + // Linear layout (1) and an explicit mode (64 KiB display, 0x10a). + let linear = ResourceDesc { + layout: 1, + ..texture(100, 60, 28, 1) + }; + assert_eq!( + texture_layout(&linear).unwrap().planes[0] + .layout + .desc + .swizzle + .0, + 0 + ); + let display = ResourceDesc { + layout: 0x10a, + ..texture(100, 60, 28, 1) + }; + assert_eq!( + texture_layout(&display).unwrap().planes[0] + .layout + .desc + .swizzle + .0, + 10 + ); + + let mut info = AllocationInfo { + size: 0, + alignment: 0, + }; + let descs = [buffer(100), texture(256, 256, 28, 0)]; + allocation_info(&mut info, std::ptr::null(), 0, 2, descs.as_ptr()); + assert_eq!( + info, + AllocationInfo { + size: KIB_64 + size(&descs[1]).unwrap(), + alignment: KIB_64 + } + ); + allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1)); + assert_eq!(info.size, u64::MAX); + } + + #[test] + fn upload_footprints_follow_the_pc_rules() { + let null = std::ptr::null(); + let mut layouts = [NO_FOOTPRINT; 2]; + let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0); + let mut footprints = |desc: &ResourceDesc, first, count| { + let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr()); + copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total); + (layouts, rows, sizes, total) + }; + // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512. + let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2); + assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400)); + // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one + // packed row, rounded up to 512. + assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512)); + assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30)); + assert_eq!(t, l[1].offset + 256 * 29 + 200); + // BC1: rows of 4x4 blocks, 8 bytes each. + let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1); + assert_eq!((r[0], s[0]), (16, 128)); + let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1); + assert_eq!(t, u64::MAX, "no second subresource"); + } + + /// A 4x4 texture filled from a title buffer through our list and queue, + /// then read back from the host GPU. + #[cfg(windows)] + #[test] + fn buffer_data_reaches_the_host_texture() { + use windows::Win32::Graphics::Direct3D12::*; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source) = (null, null); + let rgba = texture(4, 4, 28, 1); + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &rgba, + COPY_DEST, + null.cast(), + iid, + &mut image + ), + S_OK + ); + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &buffer(1024), + 0, + null.cast(), + iid, + &mut source + ), + S_OK + ); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + + let queue_iid = guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], + ); + let allocator_iid = guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ); + let list_iid = guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ); + let (mut queue, mut allocator, mut list) = (null, null, null); + let queue_desc = [0u32; 4]; + assert_eq!( + crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue), + S_OK + ); + assert_eq!( + crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), + S_OK + ); + assert_eq!( + crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list), + S_OK + ); + + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { + offset: 0, + format: 28, + width: 4, + height: 4, + depth: 1, + row_pitch: 256, + }; + let to = Location { + resource: image, + kind: 0, + footprint: PlacedFootprint { offset: 0, ..rows }, + }; + let from = Location { + resource: source, + kind: 1, + footprint: rows, + }; + type Copy = + extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + slot::<Copy>(list, 0x80)(list, &to, 0, 0, 0, &from, null.cast()); + slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list); + slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list); + + // Read the host texture back into a readback buffer. + 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: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option<ID3D12Resource> = 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(); + let host_image = host_resource(image).unwrap(); + let back = host.new_list().unwrap(); + let (_, before) = host_transition(image, 0x800).unwrap(); + // The upload list holds the texture until it is reset. + assert!(std::sync::Arc::strong_count(&host_copy(image).unwrap()) > 2); + use windows::core::Interface; + let out_to = Location { + resource: readback.as_raw().cast_const().cast(), + kind: 1, + footprint: rows, + }; + let out_from = Location { + resource: host_image.as_raw().cast_const().cast(), + kind: 0, + footprint: to.footprint, + }; + // SAFETY: an open list, live resources, locations in the host layout. + unsafe { + back.list.ResourceBarrier(&[crate::host::transition( + host_image, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + back.list.CopyTextureRegion( + (&raw const out_to).cast(), + 0, + 0, + 0, + (&raw const out_from).cast(), + 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::<u8>(), 1024) + }; + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}"); + } + } + + /// 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<ID3D12Resource> = 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::<u8>(), 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<ID3D12Resource> = 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::<u8>(), 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<ID3D12Resource> = 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<ID3D12Resource> = 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::<u8>(), 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(); + let mut committed = null; + let hr = create_committed( + null, + &PROPERTIES, + 0, + &buffer(256), + 0, + null.cast(), + &RESOURCE_IIDS[0], + &mut committed, + ); + assert_eq!(hr, S_OK); + let mut data = std::ptr::null_mut(); + assert_eq!( + slot::<Map>(committed, 0x40)(committed, 0, null.cast(), &mut data), + S_OK + ); + assert_eq!(slot::<Address>(committed, 0x58)(committed), data as u64); + // SAFETY: the buffer is at least 256 zeroed bytes. + assert_eq!(unsafe { *data.add(255) }, 0); + assert_eq!(slot::<Release>(committed, 0x10)(committed), 0); + + let heap = heap(4 * KIB_64); + let place = |offset, desc: &ResourceDesc, out: &mut This| { + create_placed( + null, + heap, + offset, + desc, + 0, + null.cast(), + &RESOURCE_IIDS[0], + out, + ) + }; + let mut placed = null; + assert_eq!(place(KIB_64, &buffer(KIB_64), &mut placed), S_OK); + // SAFETY: a heap we made. + let base = unsafe { (*heap.cast::<Heap>()).memory.ptr.as_ptr() } as u64; + assert_eq!(slot::<Address>(placed, 0x58)(placed), base + KIB_64); + let mut other = null; + assert_eq!( + place(4 * KIB_64, &buffer(1), &mut other), + E_INVALIDARG, + "past the end" + ); + assert_eq!( + place(100, &buffer(1), &mut other), + E_INVALIDARG, + "misaligned" + ); + // The resource keeps the heap alive. + assert_eq!(slot::<Release>(heap, 0x10)(heap), 1); + assert_eq!(slot::<Release>(placed, 0x10)(placed), 0); + } +} diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs new file mode 100644 index 000000000..10368e9a9 --- /dev/null +++ b/crates/victory-gpu/src/root.rs @@ -0,0 +1,324 @@ +//! Root signatures. +//! +//! Serializing goes to the host's `D3D12SerializeRootSignature` (or its +//! versioned form): the description is laid out as on PC, and the blob it +//! returns works as the console's, whose two methods sit in the same slots. +//! The console's own flags (bit 24 and up) are dropped first. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_void}; +use std::sync::OnceLock; + +use crate::object::{ + self, E_INVALIDARG, E_NOTIMPL, HRESULT, Iid, Object, ROOT_SIGNATURE, Table, This, guid, +}; +use crate::resource::PAGEABLE_IIDS; + +const ROOT_SIGNATURE_IIDS: [Iid; 3] = [ + guid( + 0xc54a6b66, + 0x72df, + 0x4ee8, + [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14], + ), + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +const CONSOLE_FLAGS: u32 = 0xff00_0000; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Desc { + parameter_count: u32, + parameters: *const c_void, + sampler_count: u32, + samplers: *const c_void, + flags: u32, +} + +/// Every version's description starts with the fields of [`Desc`]. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct VersionedDesc { + version: u32, + desc: Desc, +} + +type Serialize = + unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT; +type SerializeVersioned = + unsafe extern "system" fn(*const VersionedDesc, *mut *mut c_void, *mut *mut c_void) -> HRESULT; + +/// An export of the host's `d3d12.dll` in System32, looked up once. +fn host_export(cache: &OnceLock<Option<usize>>, name: &CStr) -> Option<usize> { + *cache.get_or_init(|| { + #[cfg(windows)] + { + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }; + let dll: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect(); + // SAFETY: a NUL-terminated name; System32 only. + let module = unsafe { + LoadLibraryExW( + dll.as_ptr(), + std::ptr::null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + }; + if module.is_null() { + return None; + } + // SAFETY: a loaded module and a NUL-terminated name. + unsafe { GetProcAddress(module, name.as_ptr().cast()) }.map(|f| f as usize) + } + #[cfg(not(windows))] + None + }) +} + +fn without_console_flags(desc: Desc) -> Desc { + if desc.flags & CONSOLE_FLAGS != 0 { + tracing::debug!( + flags = format_args!("{:#x}", desc.flags), + "console root signature flags dropped" + ); + } + Desc { + flags: desc.flags & !CONSOLE_FLAGS, + ..desc + } +} + +/// `d3d12_xs!D3D12SerializeRootSignature`. +pub extern "system" fn serialize( + desc: *const Desc, + version: u32, + blob: *mut *mut c_void, + error: *mut *mut c_void, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + static FUNCTION: OnceLock<Option<usize>> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12SerializeRootSignature") else { + tracing::warn!("no host d3d12.dll to serialize root signatures"); + return E_NOTIMPL; + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { + std::mem::transmute::<usize, Serialize>(address)( + &without_console_flags(desc), + version, + blob, + error, + ) + } +} + +/// `d3d12_xs!D3D12SerializeVersionedRootSignature`. +pub extern "system" fn serialize_versioned( + desc: *const VersionedDesc, + blob: *mut *mut c_void, + error: *mut *mut c_void, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + static FUNCTION: OnceLock<Option<usize>> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12SerializeVersionedRootSignature") else { + tracing::warn!("no host d3d12.dll to serialize root signatures"); + return E_NOTIMPL; + }; + let desc = VersionedDesc { + desc: without_console_flags(desc.desc), + ..desc + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { std::mem::transmute::<usize, SerializeVersioned>(address)(&desc, blob, error) } +} + +type Deserialize = + unsafe extern "system" fn(*const u8, usize, *const Iid, *mut *mut c_void) -> HRESULT; + +/// `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. +pub extern "system" fn create_deserializer( + blob: *const u8, + size: usize, + iid: *const Iid, + out: *mut *mut c_void, +) -> HRESULT { + if blob.is_null() || out.is_null() { + return E_INVALIDARG; + } + static FUNCTION: OnceLock<Option<usize>> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12CreateRootSignatureDeserializer") else { + tracing::warn!("no host d3d12.dll to deserialize root signatures"); + return E_NOTIMPL; + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { std::mem::transmute::<usize, Deserialize>(address)(blob, size, iid, out) } +} + +#[repr(C)] +struct RootSignature { + object: Object, + /// The serialized form, kept for translating pipelines later. + blob: Vec<u8>, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + _nodes: u32, + blob: *const u8, + size: usize, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if blob.is_null() || size == 0 { + return E_INVALIDARG; + } + // SAFETY: the title passes `size` bytes. + let blob = unsafe { std::slice::from_raw_parts(blob, size) }.to_vec(); + tracing::debug!(size, "root signature"); + let root = Box::new(RootSignature { + object: Object::new(&FUNCTIONS), + blob, + }); + object::hand_out(ROOT_SIGNATURE, root, iid, &ROOT_SIGNATURE_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &ROOT_SIGNATURE_IIDS).then_some(this); + object::answer(ROOT_SIGNATURE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::<RootSignature>(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 24>()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + + /// One 32-bit constant at b0, serialized by the host, then created. + #[cfg(windows)] + #[test] + fn host_serialized_blobs_create_root_signatures() { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_ROOT_CONSTANTS, D3D12_ROOT_PARAMETER, D3D12_ROOT_PARAMETER_0, + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_SHADER_VISIBILITY_ALL, + }; + let parameter = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 1, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let desc = Desc { + parameter_count: 1, + parameters: (&raw const parameter).cast(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 0x0100_0001, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize(&desc, 1, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::<Object>(); + let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob); + let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob); + assert!(size > 0); + let null = std::ptr::null(); + let mut root = null; + assert_eq!( + create(null, 0, data, size, &ROOT_SIGNATURE_IIDS[0], &mut root), + S_OK + ); + assert_eq!(slot::<extern "system" fn(This) -> u32>(root, 0x10)(root), 0); + slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob); + } + + /// The host's deserializer reads our blobs back (the upscaler's call). + #[cfg(windows)] + #[test] + fn our_blobs_deserialize_on_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::<Object>(); + let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob); + let size = slot::<extern "system" fn(This) -> 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, &iid, &mut out), S_OK); + // SAFETY: the host handed out this interface. + let deserializer = unsafe { ID3D12RootSignatureDeserializer::from_raw(out) }; + // SAFETY: valid while the deserializer lives. + let read = unsafe { &*deserializer.GetRootSignatureDesc() }; + assert_eq!((read.NumParameters, read.Flags.0), (0, 1)); + slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob); + } + + /// Version 1.0 through the versioned entry point, with a console flag. + #[cfg(windows)] + #[test] + fn versioned_descriptions_serialize_on_the_host() { + let desc = VersionedDesc { + version: 1, + desc: Desc { + parameter_count: 0, + parameters: std::ptr::null(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 0x0200_0001, + }, + }; + 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::<Object>(); + assert!(slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob) > 0); + slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob); + assert_eq!( + serialize_versioned(std::ptr::null(), &mut blob.cast_mut().cast(), &mut error), + E_INVALIDARG + ); + } +} diff --git a/crates/victory-gpu/src/sampler.rs b/crates/victory-gpu/src/sampler.rs new file mode 100644 index 000000000..ee95da3fd --- /dev/null +++ b/crates/victory-gpu/src/sampler.rs @@ -0,0 +1,119 @@ +//! Samplers as the host describes them, from the console's sampler +//! description (`CreateSamplerX`), which names the hardware's sampler +//! fields. (Immediate samplers in shader code come decoded with the +//! translation.) + +use windows::Win32::Graphics::Direct3D12::*; + +/// The fields both forms share. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Fields { + /// Point 0, bilinear 1, anisotropic point 2, anisotropic bilinear 3. + mag: u32, + min: u32, + /// None 0, point 1, linear 2. + mip: u32, + /// Plain 0, minimum 1, maximum 2. + mode: u32, + /// Host address modes. + address: [u32; 3], + anisotropy: u32, + /// Host comparison function. + compare: u32, + min_lod: f32, + max_lod: f32, + bias: f32, + border: [f32; 4], +} + +impl Fields { + fn host(&self) -> D3D12_SAMPLER_DESC { + let linear = |f: u32| u32::from(f == 1 || f == 3); + let aniso = self.mag >= 2 || self.min >= 2; + // The console compares when the instruction says so, with the + // sampler's function; the host needs a comparison sampler for that. + // A sampler given a real test (less ... greater-or-equal) is one; + // never, always and none are plain samplers. + const LESS: u32 = 2; + const GREATER_EQUAL: u32 = 7; + let compares = (LESS..=GREATER_EQUAL).contains(&self.compare); + let reduction = match self.mode { + 1 => 2, + 2 => 3, + _ => u32::from(compares), + }; + let filter = if aniso { + 0x55 + } else { + linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2) + }; + D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER((reduction << 7 | filter) as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32), + MipLODBias: self.bias, + MaxAnisotropy: if aniso { + self.anisotropy.clamp(1, 16) + } else { + 1 + }, + ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32), + BorderColor: self.border, + MinLOD: self.min_lod, + // Without a mip filter the console samples mip 0 only. + MaxLOD: if self.mip == 0 { + self.min_lod + } else { + self.max_lod + }, + } + } +} + +/// The console's sampler description (27 words): flags, magnification, +/// minification, mip and depth filters, filter mode, three address modes, +/// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias +/// and threshold, comparison, border color, then tuning words. +pub(crate) fn console(words: &[u32; 27]) -> D3D12_SAMPLER_DESC { + let f = |i: usize| f32::from_bits(words[i]); + Fields { + mag: words[1], + min: words[2], + mip: words[3], + mode: words[5], + address: [words[6], words[7], words[8]], + min_lod: f(9), + max_lod: f(10), + bias: f(11), + anisotropy: words[13], + compare: words[16], + border: [f(17), f(18), f(19), f(20)], + } + .host() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn console_descriptions_decode() { + let mut w = [0u32; 27]; + w[1] = 1; // bilinear magnification + w[2] = 0; // point minification + w[3] = 2; // linear mips + w[6..9].copy_from_slice(&[3, 3, 3]); + w[10] = 1000.0f32.to_bits(); + let d = console(&w); + assert_eq!(d.Filter.0, 0x5, "min point, mag and mip linear"); + assert_eq!(d.AddressW, D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + assert_eq!(d.MaxLOD, 1000.0); + // A less-or-equal test makes a comparison sampler; never does not. + w[16] = 4; + assert_eq!(console(&w).Filter.0, 0x85); + assert_eq!(console(&w).ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL); + w[16] = 1; + assert_eq!(console(&w).Filter.0, 0x5); + } +} diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs new file mode 100644 index 000000000..eabd0f3fa --- /dev/null +++ b/crates/victory-gpu/src/shader_cache.rs @@ -0,0 +1,415 @@ +//! Translated shaders kept on disk (decision 0003): under the configured +//! cache folder, keyed by the container's content and by the VIctory build +//! that translated it (the BLAKE3 of our executable), so a rebuilt +//! translator never serves an old translation. Entries go through +//! `victory-pipeline`'s content-addressed cache, which writes them +//! 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 +//! are ignored anyway). + +use std::path::PathBuf; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use victory_pipeline::{Cache, Converter}; +use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::resource::RootIndexedView; +use victory_shader::{HwStage, RootType}; + +static CACHE: OnceLock<Cache> = OnceLock::new(); +static HITS: AtomicU64 = AtomicU64::new(0); +static MISSES: AtomicU64 = AtomicU64::new(0); + +/// Keeps translated shaders in `dir` from now on. +pub fn use_shader_cache(dir: PathBuf) { + match Cache::open(dir) { + Ok(cache) => { + let _ = CACHE.set(cache); + } + Err(e) => tracing::warn!(error = %e, "no shader cache"), + } +} + +/// Shaders found in the cache and translated since the start. +pub(crate) fn counts() -> (u64, u64) { + (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) +} + +/// What identifies this build: the BLAKE3 of our executable file and of +/// the translation settings it runs with (the loop limit, which a +/// diagnostics build can change at run time). +fn build() -> &'static [u8; 32] { + static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); + BUILD.get_or_init(|| { + let exe = std::env::current_exe().and_then(std::fs::read); + let limit = victory_shader::emit::loop_limit(); + if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { + tracing::warn!( + limit, + "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" + ); + } + match exe { + Ok(mut bytes) => { + bytes.extend_from_slice(&limit.to_le_bytes()); + // Which group barriers wait is part of the translation too. + bytes.push(victory_shader::emit::group_sync()); + // So are the switches that pick the form of a wave64 program: + // without them here a run with `VICTORY_WAVE_WIDE=0` was + // served the translations an earlier run of the same + // executable had cached with the switch unset. + for name in [ + "VICTORY_WAVE_WIDE", + "VICTORY_WAVE_DEEP_SKIPS", + "VICTORY_WAVE_OWN_BITS", + "VICTORY_F16_NEAREST", + ] { + bytes.extend_from_slice(name.as_bytes()); + bytes.push(b'='); + if let Some(value) = std::env::var_os(name) { + bytes.extend_from_slice(value.as_encoded_bytes()); + } + bytes.push(0); + } + // And which clean-up passes ran over the translated code. + bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); + *blake3::hash(&bytes).as_bytes() + } + Err(e) => { + // Without it no entry can be trusted: a fresh key per run. + tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + *blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes() + } + } + }) +} + +/// The translation of a console shader container, from the cache when +/// there is one. +pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> { + let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); + match CACHE.get() { + Some(cache) => cached(cache, build(), container, translate), + None => translate(container), + } +} + +/// The cache entry's converter: the build and the container in, the +/// encoded translation out. `ran` tells a miss from a hit. +struct Translate<F> { + translate: F, + ran: AtomicBool, +} + +impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> { + fn id(&self) -> &'static str { + "shader.dxil" + } + fn version(&self) -> u32 { + // The build fingerprint in the input does the versioning. + 1 + } + fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> { + 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; 32], + container: &[u8], + translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync, +) -> Result<HostShader, String> { + let input = [&build[..], container].concat(); + let converter = Translate { + translate, + ran: AtomicBool::new(false), + }; + for _ in 0..2 { + 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.ran.load(Ordering::Relaxed) { + (&MISSES, "translated and cached") + } else { + (&HITS, "from the cache") + }; + counter.fetch_add(1, Ordering::Relaxed); + tracing::debug!(path = %path.display(), "shader {what}"); + return Ok(shader); + } + tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again"); + let _ = std::fs::remove_file(&path); + } + MISSES.fetch_add(1, Ordering::Relaxed); + (converter.translate)(container) +} + +const MAGIC: &[u8; 4] = b"VSH1"; +const STAGES: [HwStage; 8] = [ + HwStage::Ls, + HwStage::Hs, + HwStage::Es, + HwStage::Gs, + HwStage::Vs, + HwStage::Ps, + HwStage::Ms, + HwStage::Cs, +]; + +fn root_code(r: RootType) -> u32 { + match r { + RootType::Constants => 0, + RootType::Descriptor => 1, + RootType::Table => 2, + RootType::ImmediateSampler => 3, + RootType::ResourceHeap => 4, + RootType::SamplerHeap => 5, + RootType::Other(x) => 6 + x, + } +} + +fn root_type(code: u32) -> RootType { + match code { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 2 => RootType::Table, + 3 => RootType::ImmediateSampler, + 4 => RootType::ResourceHeap, + 5 => RootType::SamplerHeap, + x => RootType::Other(x - 6), + } +} + +/// Little-endian words and length-prefixed lists. +fn encode(s: &HostShader) -> Vec<u8> { + let mut out = MAGIC.to_vec(); + let word = |out: &mut Vec<u8>, v: u32| out.extend(v.to_le_bytes()); + let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u32; + word(&mut out, stage); + word(&mut out, s.dxil.len() as u32); + out.extend(&s.dxil); + word(&mut out, s.user_data.len() as u32); + for u in &s.user_data { + for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] { + word(&mut out, v); + } + } + word(&mut out, s.samplers.len() as u32); + for sampler in &s.samplers { + for &v in sampler { + word(&mut out, v); + } + } + word(&mut out, s.static_samplers.len() as u32); + for t in &s.static_samplers { + let [u, v, w] = t.address; + let words = [ + t.filter, + u, + v, + w, + t.mip_lod_bias.to_bits(), + t.max_anisotropy, + t.comparison, + t.border, + t.min_lod.to_bits(), + t.max_lod.to_bits(), + ]; + for v in words { + word(&mut out, v); + } + } + for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] { + word(&mut out, slots.len() as u32); + out.extend(slots); + } + word(&mut out, s.root_indexed_views.len() as u32); + for view in &s.root_indexed_views { + for value in [ + u32::from(view.table_slot), + u32::from(view.constant_slot), + view.constant_dword, + view.byte_offset, + u32::from(view.shift), + ] { + word(&mut out, value); + } + } + out +} + +fn decode(bytes: &[u8]) -> Option<HostShader> { + struct Reader<'a>(&'a [u8]); + impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let (head, rest) = self.0.split_at_checked(n)?; + self.0 = rest; + Some(head) + } + fn word(&mut self) -> Option<u32> { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } + fn list(&mut self) -> Option<Vec<u8>> { + let n = self.word()? as usize; + Some(self.take(n)?.to_vec()) + } + } + let mut r = Reader(bytes); + if r.take(4)? != MAGIC { + return None; + } + let stage = *STAGES.get(r.word()? as usize)?; + let dxil = r.list()?; + let n = r.word()? as usize; + let mut user_data = Vec::with_capacity(n.min(256)); + for _ in 0..n { + user_data.push(UserData { + index: r.word()?, + slot: u8::try_from(r.word()?).ok()?, + root: root_type(r.word()?), + dword: r.word()?, + }); + } + let n = r.word()? as usize; + let mut samplers = Vec::with_capacity(n.min(256)); + for _ in 0..n { + samplers.push([r.word()?, r.word()?, r.word()?, r.word()?]); + } + let n = r.word()? as usize; + let mut static_samplers = Vec::with_capacity(n.min(256)); + for _ in 0..n { + static_samplers.push(StaticSampler { + filter: r.word()?, + address: [r.word()?, r.word()?, r.word()?], + mip_lod_bias: f32::from_bits(r.word()?), + max_anisotropy: r.word()?, + comparison: r.word()?, + border: r.word()?, + min_lod: f32::from_bits(r.word()?), + max_lod: f32::from_bits(r.word()?), + }); + } + let root_cbvs = r.list()?; + let root_srvs = r.list()?; + let root_uavs = r.list()?; + let n = r.word()? as usize; + let mut root_indexed_views = Vec::with_capacity(n.min(256)); + for _ in 0..n { + root_indexed_views.push(RootIndexedView { + table_slot: u8::try_from(r.word()?).ok()?, + constant_slot: u8::try_from(r.word()?).ok()?, + constant_dword: r.word()?, + byte_offset: r.word()?, + shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, + }); + } + r.0.is_empty().then_some(HostShader { + stage, + dxil, + user_data, + samplers, + static_samplers, + root_cbvs, + root_srvs, + root_uavs, + root_indexed_views, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shader() -> HostShader { + HostShader { + stage: HwStage::Ps, + dxil: b"DXBC and the rest".to_vec(), + user_data: vec![UserData { + index: 8, + slot: 1, + root: RootType::Table, + dword: 0, + }], + samplers: vec![[0x400, 0xc0_0000, 0x18f0_0000, 0]], + static_samplers: vec![StaticSampler::from_words([ + 0x400, + 0xc0_0000, + 0x18f0_0000, + 0, + ])], + root_cbvs: vec![2], + root_srvs: vec![0, 3], + root_uavs: vec![1], + root_indexed_views: vec![RootIndexedView { + table_slot: 1, + constant_slot: 2, + constant_dword: 3, + byte_offset: 32, + shift: 5, + }], + } + } + + #[test] + fn translations_come_back_from_the_cache() { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let build = [7u8; 32]; + let container = b"a console container".as_slice(); + let runs = AtomicU64::new(0); + let translate = |_: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + Ok(shader()) + }; + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); + + // Another build translates again. + 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"VSH1 broken").unwrap(); + } + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 3); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 3); + + // Failures are not stored. + let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned()); + assert!(cached(&cache, &build, b"other", fail).is_err()); + } + + fn walk(dir: &std::path::Path) -> Vec<PathBuf> { + let mut files = Vec::new(); + for e in std::fs::read_dir(dir).unwrap().flatten() { + if e.path().is_dir() { + files.extend(walk(&e.path())); + } else { + files.push(e.path()); + } + } + files + } + + #[test] + fn entries_round_trip_and_reject_damage() { + let bytes = encode(&shader()); + assert_eq!(decode(&bytes), Some(shader())); + assert_eq!(decode(&bytes[..bytes.len() - 1]), None); + assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); + assert_eq!(decode(b"VSH0"), None); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs new file mode 100644 index 000000000..d17007512 --- /dev/null +++ b/crates/victory-gpu/src/shadow.rs @@ -0,0 +1,3186 @@ +//! Host copies of title buffers (decision 0007, step 3 and "Copies of title +//! memory"). Title buffers are title memory, which the host GPU cannot +//! read, so a buffer a draw uses gets a persistent host buffer of its size +//! on first use (system memory shaders may also write), and the ranges each +//! submission reads (vertex, index and constant data, buffer views) are +//! brought up to date from title memory before it runs: the 64 KiB pages +//! the title wrote since they were last copied ([`crate::watch`]: write +//! watching, or read-only guards on physical-page views), all of it where +//! neither works. A title GPU address inside the buffer is the same offset +//! in its copy. Ranges shaders write go back to title memory after the +//! submission ([`Shadow::gpu_writes`]). +//! +//! shortcut: only the ranges draws are known to read are brought up to +//! date (vertex and index buffer views, constant buffers in tables, root +//! descriptors, buffer views in tables); buffers read through directly +//! indexed heaps keep what their first use copied. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use windows::Win32::Graphics::Direct3D12::ID3D12Resource; + +use crate::host::{HostList, host}; +use crate::watch::PAGE; + +/// A title buffer's host copy. +pub(crate) struct Shadow { + pub(crate) buffer: ID3D12Resource, + data: *mut u8, + gpu: u64, + /// Where the title buffer starts and how long it is. + start: u64, + len: u64, + /// Per page of title memory from `start`'s on: the write-watch asking + /// after which it was last copied (0: never). + copied: Mutex<Vec<u64>>, + /// Whether the memory is write-watched: unknown, yes, no. + watched: AtomicU8, + /// Ranges shaders of a submission not yet copied back may be writing: + /// title memory there is older than the copy. + pending: Mutex<Vec<(usize, usize)>>, + /// With [`relay`]: how many submissions not yet copied back declared + /// each range of `pending` ([`Flights`]). Locked inside `pending`'s + /// lock. + flights: Mutex<Flights>, + /// 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<Option<Vec<u8>>>, + /// 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>, 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<Card>, + /// 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<Option<ID3D12Resource>>, + /// Offsets of the copy whose bytes changed on the CPU's side and have + /// not gone to the card's side yet. + dirty: Mutex<Vec<(usize, usize)>>, + /// 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<Vec<(usize, usize, u64)>>, + /// 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<bool> = 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::<u64>().ok()).unwrap_or(default) << 20 + }; + (mb("VICTORY_CARD_BUFFERS_MIN_MB", 16).max(1 << 20), mb("VICTORY_CARD_BUFFERS_MB", 512)) + }) +} + +/// 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<Vec<std::sync::Weak<Shadow>>> = 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<ID3D12Resource> { + 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<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::<u64>().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<ID3D12Resource> { + 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<Shadow>, 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<CardSpan>) -> Vec<CardSpan> { + runs.sort_unstable_by_key(|r| r.first); + let mut out: Vec<CardSpan> = 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<u32> = 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<u32> = 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::<Vec<_>>(), [(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<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_RELAY").is_ok_and(|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<u8> = (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<u8> = (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<u8> = (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<Vec<Vec<u8>>> = Mutex::new(Vec::new()); + +/// 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<u8> { + 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 && v.capacity() <= most) + .min_by_key(|(_, v)| v.capacity()) + .map(|(i, _)| i); + let mut v = match fit { + Some(i) => pool.swap_remove(i), + None => Vec::with_capacity(n), + }; + v.clear(); + v +} + +/// 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<u8>) { + const KEPT: usize = 512 << 20; + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + pool.push(v); + 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<usize> { + 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<usize> { + 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<u8> = (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<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_some_and(|v| v == "1")) +} + +type Job = Box<dyn FnOnce() + Send>; + +/// Threads kept for [`wide`]: what they are to do, and the word that there +/// is something. +struct Workers { + jobs: Mutex<std::collections::VecDeque<Job>>, + more: std::sync::Condvar, +} + +fn workers() -> &'static Workers { + static WORKERS: std::sync::OnceLock<Workers> = 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<Job>) { + 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<Box<dyn FnOnce() + Send>>) { + 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<Vec<(usize, usize, usize)>> = 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<Job> { + let mut jobs: Vec<Job> = 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<Job>| { + 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<Shadow>, usize, usize)]) -> Vec<Vec<(usize, usize)>> { + 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<Vec<(usize, usize)>> { + // 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<Mutex<Found>> = Arc::default(); + let mut jobs: Vec<Job> = Vec::new(); + let mut group: Vec<Part> = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec<Part>, jobs: &mut Vec<Job>| { + 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<f64> = 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<Job> = (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<u8> = (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<u8> = (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<u8> = (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<bool> = 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<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::<u64>().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<usize> { + 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_MS: u64 = 10_000; + const IDLE_FRAMES: u64 = 4; + let gone: Vec<Arc<Shadow>> = { + // 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()); + 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::<u64>()); + 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::<u64>()) + }; + [ + 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 {} +// SAFETY: as above. +unsafe impl Sync for Shadow {} + +impl Shadow { + /// The host GPU address of a title address inside the buffer. + pub(crate) fn gpu(&self, address: u64) -> u64 { + 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<u64> { + 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 + self.place.as_ref().map_or(0, |place| place.1) + } + + /// 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, + /// and keeps the copy alive until the list is reset. + pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) { + let len = len.min(self.start + self.len - address); + list.defer_refresh(self, address as usize, len as usize); + } + + 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, + data, + gpu, + start, + len, + 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<Self>, 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<Vec<(usize, usize)>>) -> 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<u8>, title: &mut Vec<u8>) -> 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); + } + } + + /// 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<usize> { + pieces_of(self.start as usize, from, to) + } + + /// 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) + } + + /// 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()) + .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 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, + }) + } + + /// 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<usize> = { + 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]; + // 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; + } + *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); + } + } 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); + } + } + 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; + } + } + } + } + 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 { + return 0; + } + let mut busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .copied() + .filter(|&(a, e)| a < to && e > from) + .collect(); + if !busy.is_empty() { + // Around ranges shaders are writing: the gaps, each as below + // (in the world most submissions have such ranges; copying the + // gaps whole cost ~1 s per frame). + busy.sort_unstable(); + let (mut at, mut bytes) = (from, 0); + for (a, e) in busy { + if a > at { + bytes += self.update_free(at, a); + } + at = at.max(e); + } + if at < to { + bytes += self.update_free(at, to); + } + return bytes; + } + self.update_free(from, to) + } + + /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no + /// shader writes. + fn update_free(&self, from: usize, to: usize) -> usize { + if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { + 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); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from).saturating_sub(copied) as u64); + } + return copied; + } + self.watched.store(NOT_WATCHED, Ordering::Relaxed); + } + #[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 + } + + /// 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. + fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { + let base = self.start as usize / PAGE; + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let mut writes = written.iter().peekable(); + let (mut bytes, mut run) = (0, None); + let last = (to - 1) / PAGE; + for page in from / PAGE..=last { + let write = match writes.peek() { + Some(&&(p, w)) if p == page => { + writes.next(); + w + } + _ => 0, + }; + let at = &mut copied[page - base]; + if *at == 0 || write > *at { + // A page only partly in the range is copied in part: it + // stays stale for the rest. + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { + *at = now; + } + run.get_or_insert(page); + } else if let Some(first) = run.take() { + 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((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + } + bytes + } + + /// 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::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<ID3D12Resource>, 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<ID3D12Resource>) -> 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<CardSpan> { + 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) + } + + /// 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<u8>) -> 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<u8>) -> 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 { + end: u64, + shadow: Option<Arc<Shadow>>, +} + +/// Title buffers by (start address, resource), with their copy once made. +static BUFFERS: Mutex<BTreeMap<(u64, usize), Entry>> = Mutex::new(BTreeMap::new()); + +fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A title buffer exists at `start` (`len` bytes). +pub(crate) fn register(resource: usize, start: u64, len: u64) { + buffers().insert( + (start, resource), + Entry { + end: start + len, + shadow: None, + }, + ); +} + +/// The title released it; lists that still hold its copy keep it alive. +pub(crate) fn unregister(resource: usize, start: u64) { + buffers().remove(&(start, resource)); +} + +/// 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<Arc<Shadow>> = 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. 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<Arc<Shadow>> { + 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<Arc<Shadow>> { + // 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<Arc<Shadow>> { + let end = address.checked_add(len.max(1))?; + let mut map = buffers(); + let key = map + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end >= end) + .map(|(k, _)| *k); + let Some(key) = key else { + drop(map); + 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 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!( + start = format_args!("{:#x}", key.0), + len, + "large buffer copied to the host" + ); + } else { + tracing::debug!( + start = format_args!("{:#x}", key.0), + len, + "buffer copied to the host" + ); + } + 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 +/// gets copies of the aligned windows it touches. +/// 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; + +/// 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<u64> = std::sync::OnceLock::new(); + *GRID.get_or_init(|| { + let kb = std::env::var("VICTORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::<u64>().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>) -> 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<bool> = 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<Item = (u64, u64)>, 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))) +} + +/// 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 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<Item = (u64, u64)>) -> 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<Item = (u64, u64)>, 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() +} + +/// Copies of title memory outside buffers, by (start, length). +static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new()); + +fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Shadow>> { + 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()); + } + // 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!( + 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) +} + +#[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 +/// starts closest below host GPU address `va`, and where `va` is in it. +pub(crate) fn near(va: u64) -> String { + let mut all: Vec<(u64, u64, u64)> = buffers() + .values() + .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len))) + .collect(); + all.extend( + LOOSE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .map(|s| (s.gpu, s.start, s.len)), + ); + let below = all.iter().filter(|c| c.0 <= va).max(); + let above = all.iter().filter(|c| c.0 > va).min(); + let mut text = match below { + Some(&(gpu, start, len)) => format!( + "; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}", + va - gpu + ), + None => "; no title memory copy below it".into(), + }; + if let Some(&(gpu, start, len)) = above { + text.push_str(&format!( + "; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)", + all.len() + )); + } + text +} diff --git a/crates/victory-gpu/src/signature.rs b/crates/victory-gpu/src/signature.rs new file mode 100644 index 000000000..3c7b5d53d --- /dev/null +++ b/crates/victory-gpu/src/signature.rs @@ -0,0 +1,94 @@ +//! Command signatures: the record layout of indirect execution. Kept for +//! translating it later. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{ + self, COMMAND_SIGNATURE, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid, +}; +use crate::resource::PAGEABLE_IIDS; + +const SIGNATURE_IIDS: [Iid; 4] = [ + guid( + 0xc36a797c, + 0xec80, + 0x4f0a, + [0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +pub(crate) struct Desc { + stride: u32, + count: u32, + /// Each a type and up to three 32-bit fields. + arguments: *const [u32; 4], + nodes: u32, +} + +#[repr(C)] +struct Signature { + object: Object, + stride: u32, + arguments: Vec<[u32; 4]>, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + desc: *const Desc, + _root: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if desc.arguments.is_null() && desc.count > 0 { + return E_INVALIDARG; + } + let arguments = if desc.count == 0 { + Vec::new() + } else { + // SAFETY: the title passes `count` argument descriptions. + unsafe { std::slice::from_raw_parts(desc.arguments, desc.count as usize) }.to_vec() + }; + tracing::debug!(stride = desc.stride, ?arguments, "command signature"); + let signature = Box::new(Signature { + object: Object::new(&FUNCTIONS), + stride: desc.stride, + arguments, + }); + object::hand_out(COMMAND_SIGNATURE, signature, iid, &SIGNATURE_IIDS, out) +} + +/// A signature's record stride and arguments (type, then up to three +/// fields each). +pub(crate) fn layout<'a>(this: This) -> Option<(u32, &'a [[u32; 4]])> { + if this.is_null() { + return None; + } + // SAFETY: the title passes one of our signatures. + let s = unsafe { &*this.cast::<Signature>() }; + Some((s.stride, &s.arguments)) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &SIGNATURE_IIDS).then_some(this); + object::answer(COMMAND_SIGNATURE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::<Signature>(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 24>()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs new file mode 100644 index 000000000..f81539369 --- /dev/null +++ b/crates/victory-gpu/src/texture.rs @@ -0,0 +1,1167 @@ +//! Texture contents the title writes itself (decision 0007, "Texture +//! memory"): streamed pages, layout-library copies, movie frames, glyph +//! atlases. Such a texture lives in console memory in its tiled layout; +//! before a submission samples its host copy, the memory is detiled into a +//! staging buffer when its content changed, and the staging buffer is +//! copied into the host texture. +//! +//! "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 the whole memory at every +//! submission that samples it. +//! +//! 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::sync::{Arc, Mutex}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::host::{HostList, host}; +use crate::object::This; + +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +/// A texture's upload state: the staging buffer laid out as the host +/// texture's subresources, and what was last detiled. +pub(crate) struct Staging { + buffer: ID3D12Resource, + /// Its bytes. + #[cfg(feature = "diagnostics")] + size: u64, + data: *mut u8, + footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, + rows: Vec<u32>, + layout: victory_formats::texture::Layout, + /// Mips per array slice. + mips: u32, + /// The staging buffer's bytes (counted in `STAGED` while it lives). + bytes: u64, + memory: *const u8, + last: Mutex<Last>, + /// 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. +#[derive(Default)] +struct Last { + hash: Option<blake3::Hash>, + asked: u64, + /// The frame a partly mapped texture was last read in. + partial: Option<u64>, +} + +// SAFETY: the staging mapping is written only at submission, under +// `last`'s lock; the title memory is only read. +unsafe impl Send for Staging {} +// SAFETY: as above. +unsafe impl Sync for Staging {} + +static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None); + +/// 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, + )>, +} + +/// The most levels times layers [`alias`] copies (a cube of nine levels). +const ALIAS_PARTS: u32 = 54; + +// SAFETY: a device-local buffer only lists record copies with. +unsafe impl Send for Through {} +// SAFETY: as above. +unsafe impl Sync for Through {} + +/// The copy buffers of [`alias`], by the placed view's texture. +static THROUGH: Mutex<Option<HashMap<usize, Arc<Through>>>> = 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 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 + } + } + }; + 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)]); + } + 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); + } + true +} + +/// 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<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_some_and(|v| v == "1")) +} + +/// 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<T>(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 +} + +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<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Calls `f` with `size` bytes of this thread's read buffer (their +/// contents are whatever the last texture left). +fn with_read<R>(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { + READ.with(|read| { + let mut read = read.borrow_mut(); + if read.len() < size { + read.resize(size, 0); + } + f(&mut read[..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<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_COPY").is_some_and(|v| v == "1")) +} + +/// 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<R>(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) + }) +} + +/// 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]; + +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); + } +} + +/// 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] +} + +/// 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)] +} + +/// 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_MS: u64 = 10_000; + 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; + }; + // 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; + } + 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<Option<std::collections::HashSet<usize>>> = Mutex::new(None); + +/// A host copy or resolve writes `resource`. +pub(crate) fn host_written(resource: This) { + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + set.get_or_insert_with(Default::default) + .insert(resource as usize); +} + +/// 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); + } + let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(through) = through.as_mut() { + through.remove(&resource); + } +} + +/// 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 +/// its host copy, and the detiling that refreshes the staging buffer at +/// submission if the memory changed. Leaves the texture in the copy +/// destination state. +pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { + 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; + }; + 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; + } + #[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) { + use std::sync::atomic::Ordering::Relaxed; + let started = std::time::Instant::now(); + let read = self.refresh_now(); + let preparing = &crate::host::PREPARING; + preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); + preparing[3].fetch_add(read as u64, Relaxed); + } + + /// Returns the bytes of title memory read. + fn refresh_now(&self) -> usize { + let whole = std::time::Instant::now(); + let read = self.refresh_timed(); + REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + read + } + + fn refresh_timed(&self) -> usize { + let size = self.layout.size as usize; + let start = self.memory as usize; + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); + let last = &mut *last; + 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. + 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, 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<bool> = 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")] + 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; + } + 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 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 + } + + /// 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!( + memory = ?self.memory, + desc = ?self.layout.desc, + "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" + ); + } + 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; + } + } + } +} + +/// 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)); + } +} + +/// Whether a title texture has a staging buffer: a list recorded its +/// upload, and the lists that sample it check it at submission. +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<bool> = 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::<PSAPI_WORKING_SET_EX_INFORMATION>()) 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 end = p + len; + 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)) }; + if n == 0 || info.State != MEM_COMMIT { + return false; + } + p = info.BaseAddress as usize + info.RegionSize; + } + true +} + +/// 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<bool> = 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. +fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + if let Some(s) = map.get(&(resource as usize)) { + return Some(s.clone()); + } + let (memory, desc) = crate::resource::texture_memory(resource)?; + let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone()) + else { + once!( + ?desc, + "texture contents without a console layout not uploaded" + ); + return None; + }; + if layout.desc.swizzle.xor() { + once!(?desc, "texture contents in an XOR mode not uploaded"); + return None; + } + let host = host()?; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + 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 total = 0; + // SAFETY: outputs for `count` subresources. + unsafe { + host.device.GetCopyableFootprints( + &d, + 0, + count, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + None, + Some(&mut total), + ); + } + let (buffer, data) = host.upload_buffer(total)?; + crate::host::name(&buffer, || { + format!( + "staging of {resource:?} {}x{}x{} f{}", + d.Width, d.Height, d.DepthOrArraySize, d.Format.0 + ) + }); + tracing::debug!(?desc, total, "texture contents uploaded from title memory"); + 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, + #[cfg(feature = "diagnostics")] + size: total, + data, + footprints, + rows, + layout, + mips: u32::from(d.MipLevels), + 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)] +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 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::<u8>(); + 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); + } + } + + /// 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 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::<u8>(); + 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); + } + } + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs new file mode 100644 index 000000000..60089a7e8 --- /dev/null +++ b/crates/victory-gpu/src/watch.rs @@ -0,0 +1,1108 @@ +//! Which title memory the title wrote since a host copy took it (decision +//! 0007, "Copies of title memory"). The runtime reserves title GPU memory +//! with write watching (`victory-hle` xmem), so the kernel keeps a dirty bit +//! per 4 KiB page; asking for a range's written pages also clears them. Host +//! copies of the same memory can overlap (nested buffers, textures in +//! buffers), so what one asks is kept here for the others: a journal of +//! each page's last write, numbered by the asking. +//! +//! Physical-page views (xmem's sections) cannot be write-watched. There a +//! 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. 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 +//! the guarded addresses; they go to the texture pool, whose textures are +//! hashed, not guarded. A system call writing into a guarded block fails +//! (none is known to). + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Mutex; + +/// The unit tracked and copied: 64 KiB, the console's page (the kernel's +/// 4 KiB pages fold into it). Finer units made the checks of the world's +/// big buffers cost more than the copies they saved. +pub(crate) const PAGE: usize = 64 << 10; +/// The kernel's page, the unit of its answers. +const KERNEL_PAGE: usize = 4096; + +struct Journal { + /// Numbers the askings; 0 is "never". + asked: u64, + /// Page number → the asking that last found it written. + written: BTreeMap<usize, u64>, + /// Room for the kernel's answer. + found: Vec<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<Journal> = Mutex::new(Journal { + asked: 0, + written: BTreeMap::new(), + found: Vec::new(), + ahead: Vec::new(), + ahead_asked: 0, + kept: false, +}); + +/// 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; + } + ask_run(j, &pieces[i..k]); + i = k; + } +} + +/// 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); +} + +/// [`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(); + } +} + +/// 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<bool> = 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; + } + 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)); + } + } + 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(); + } +} + +/// 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; + } + j.asked += 1; + let now = j.asked; + for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { + j.written.insert(page, now); + } +} + +/// One kernel asking for `pieces` (page ranges in order); by halves if it +/// fails, as a run across two reservations or into memory that is not +/// write-watched does. A piece alone is left to [`writes`]. +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); +} + +/// 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 +/// written since tracking began: `(page number, asking)` in page order, and +/// this asking's number, which is higher than any in the list but those the +/// kernel just reported. `None` if the memory is not write-watched (nor, +/// with `guarded`, view memory, which is then guarded). +pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + 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; + // 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.ahead_asked, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )); + } + 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; + let guarded = if failed { + count = 0; + if !guarded { + 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 { + Vec::new() + }; + #[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); + } + j.asked += 1; + let now = j.asked; + let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded); + for page in pages.collect::<Vec<_>>() { + j.written.insert(page, now); + } + Some(( + now, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )) +} + +/// Guarded blocks of view memory. +const BLOCK: usize = PAGE; + +struct Guards { + /// Blocks we made read-only. + protected: BTreeSet<usize>, + /// Of those, the ones not written since a copy took them. + clean: BTreeSet<usize>, + /// 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<usize>, +} + +static GUARDS: Mutex<Guards> = Mutex::new(Guards { + protected: BTreeSet::new(), + clean: BTreeSet::new(), + absent: BTreeSet::new(), +}); + +fn guards() -> std::sync::MutexGuard<'static, Guards> { + GUARDS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// 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) -> Option<Vec<usize>> { + // 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<bool> = 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<usize> = 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<usize> = 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 { + 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) { + // Written through the runtime, still read-only. + g.clean.insert(block); + } else { + run.get_or_insert(block); + continue; + } + } + if let Some(from) = run.take() { + protect(&mut g, from, block); + } + } + 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<bool> = 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, 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| { + let mut old = 0; + // SAFETY: title view memory; only its protection changes. + unsafe { + VirtualProtect( + (from * BLOCK) as *const _, + (to - from) * BLOCK, + PAGE_READONLY, + &mut old, + ) != 0 + } + }; + let note = |g: &mut Guards, from: usize, to: usize| { + g.protected.extend(from..to); + g.clean.extend(from..to); + }; + if set(from, to) { + note(g, from, to); + return; + } + for block in from..to { + 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 { + use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + let blocks: Vec<usize> = g + .protected + .range(start / BLOCK..end.div_ceil(BLOCK)) + .copied() + .collect(); + for &block in &blocks { + 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() +} + +/// Before our own write into title memory `[at, at + len)` through the +/// kernel (which does not fault into our handler): opens its guarded blocks. +/// The runtime calls it (as `kernel_will_write`) before the title's kernel +/// reads into its own memory. +pub fn writing(at: usize, len: usize) { + // 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<Reading> { + 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 (nor known +/// unmapped). +pub fn title_memory_remapped(at: usize, len: usize) { + // 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 range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); + let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect(); + for block in absent { + g.absent.remove(&block); + } + let blocks: Vec<usize> = g.protected.range(range).copied().collect(); + for block in blocks { + g.protected.remove(&block); + g.clean.remove(&block); + } +} + +/// Registers the handler that takes writes to guarded blocks, once, ahead +/// of the crash reporter's. +fn install() { + use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; + use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, + EXCEPTION_POINTERS, + }; + unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched. + let r = unsafe { &*(*info).ExceptionRecord }; + const WRITE: usize = 1; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS + || r.NumberParameters < 2 + || r.ExceptionInformation[0] != WRITE + { + return EXCEPTION_CONTINUE_SEARCH; + } + let at = r.ExceptionInformation[1]; + // Held across both checks: another thread may have opened the block + // since this one faulted, and a copy may have guarded it again since + // (then it is ours again, not read-only for some other reason). + let mut g = guards(); + if open(&mut g, at, at + 1) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::GuardFaults, 1); + return EXCEPTION_CONTINUE_EXECUTION; + } + if writable(at) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } + } + static ONCE: std::sync::Once = std::sync::Once::new(); + // SAFETY: the handler only touches our guard state and protections. + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(on_write)); + }); +} + +/// Whether `at` is committed read-write memory now. +fn writable(at: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, 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(at as *const _, &mut info, size_of_val(&info)) }; + n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + #[test] + fn written_pages_are_reported_to_every_asker() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc( + std::ptr::null(), + 4 * PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(p, 0); + let (start, end) = (p, p + 4 * PAGE); + 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) }; + 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. + let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); + assert!(later > now); + assert_eq!(again, [(p / PAGE + 1, now)]); + let mut plain = vec![0u8; PAGE]; + assert!( + writes( + plain.as_mut_ptr() as usize, + plain.as_ptr() as usize + PAGE, + true + ) + .is_none() + ); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + + /// A kernel read into a guarded view block fails; opened first, it + /// lands and the block counts as written. + #[test] + fn kernel_reads_into_guarded_blocks_after_opening() { + use std::io::{Read, Seek, Write}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write. + let view = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize + }; + assert_ne!(view, 0); + 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. + let read = |file: &mut std::fs::File| { + file.rewind().unwrap(); + // SAFETY: 13 bytes of our view, nothing else refers to them. + let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) }; + file.read(into).is_ok_and(|n| n == 13) + }; + assert!( + !read(&mut file), + "the kernel does not fault into our handler" + ); + 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!( + guard(view, view + 2 * BLOCK), + Some((view / PAGE..view / PAGE + 1).collect()) + ); + // SAFETY: our view. + unsafe { + UnmapViewOfFile( + windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }, + ) + }; + title_memory_remapped(view, 2 * BLOCK); + } + + #[test] + 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_range_that_begins_in_an_unmapped_block_is_guarded() { + 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 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<usize> = (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); + } + 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, + (2 * 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 first = map(0); + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec<usize> = (0..3).flat_map(pages).collect(); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!( + guard(p, p + 3 * BLOCK), + Some(Vec::new()), + "nothing written since" + ); + let second = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), 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 new file mode 100644 index 000000000..e8d6bafc0 --- /dev/null +++ b/crates/victory-hle/Cargo.toml @@ -0,0 +1,55 @@ +[package] +name = "victory-hle" +description = "Our implementation of the Xbox system API surface the title imports." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-gpu.workspace = true +victory-loader.workspace = true +victory-pe.workspace = true +victory-formats.workspace = true +opus-pure.workspace = true +miniz_oxide.workspace = true +tracing.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Globalization", + "Win32_Media", + "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_Diagnostics_Debug", + "Win32_System_LibraryLoader", + "Win32_System_Memory", + "Win32_System_Power", + "Win32_System_ProcessStatus", + "Win32_System_Threading", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Input_XboxController", + "Win32_UI_WindowsAndMessaging", +] } +# Diagnostics only: recording our own audio (`modules::audio::capture`). +windows = { workspace = true, optional = true, features = [ + "Win32_Media_Audio", + "Win32_System_Com", + "Win32_System_Com_StructuredStorage", + "Win32_System_Threading", + "Win32_System_Variant", +] } +# `#[implement]` names it. +windows-core = { workspace = true, optional = true } + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Debugging switches (scripted keys and the like). +diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"] + +[lints] +workspace = true diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs new file mode 100644 index 000000000..8a2a8750c --- /dev/null +++ b/crates/victory-hle/src/host.rs @@ -0,0 +1,148 @@ +//! Pass-through to the host's own implementation of shared APIs. + +use victory_pe::ImportSymbol; + +/// Which DLLs may be satisfied by the host's own implementation. +/// +/// Console titles link mostly against Windows API sets that behave the same +/// on PC. Passing those through lets bring-up focus on what really differs. +/// Anything whose semantics differ on console (memory, files, threads) is +/// overridden in `modules`, which always wins over the host. +#[derive(Debug, Clone)] +pub struct HostPolicy { + /// Lower-case patterns; a trailing `*` matches a prefix. + pub allow: Vec<String>, +} + +impl Default for HostPolicy { + fn default() -> Self { + let allow = [ + "api-ms-win-core-*", + "api-ms-win-eventing-*", + "api-ms-win-security-*", + "api-ms-win-crt-*", + "kernel32.dll", + "kernelbase.dll", + "ntdll.dll", + "ucrtbase.dll", + "vcruntime140*", + "msvcp140*", + // Off-machine traffic is refused in `modules::net`. + "ws2_32.dll", + "bcrypt.dll", + "crypt32.dll", + "ncrypt.dll", + "winhttp.dll", + "sspicli.dll", + "cabinet.dll", + "avrt.dll", + // Window, message and shell APIs: the host's desktop window + // stands in for the console's single core window. + "ext-ms-win-rtcore-ntuser-*", + "api-ms-win-shcore-*", + "msvcp_win.dll", + "ole32.dll", + "advapi32.dll", + "iphlpapi.dll", + // The title's crash handler writes minidumps with it (loaded by name). + "dbghelp.dll", + // Same APIs as the console's (XAudio2 ordinal 1 is XAudio2Create + // on both); Media Foundation reads local media files. + "xaudio2_9.dll", + "mfplat.dll", + "mfreadwrite.dll", + ]; + HostPolicy { + allow: allow.iter().map(|s| s.to_string()).collect(), + } + } +} + +impl HostPolicy { + /// No pass-through at all: shows the full surface a title needs. + pub fn none() -> Self { + HostPolicy { allow: Vec::new() } + } + + pub fn allows(&self, dll: &str) -> bool { + let dll = dll.to_ascii_lowercase(); + self.allow + .iter() + .any(|pattern| match pattern.strip_suffix('*') { + Some(prefix) => dll.starts_with(prefix), + None => dll == *pattern, + }) + } + + pub(crate) fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Option<usize> { + if !self.allows(dll) { + return None; + } + imp::resolve(dll, symbol) + } +} + +/// 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. +pub(crate) fn function(dll: &str, name: &str) -> Option<usize> { + let name = ImportSymbol::Name { + hint: 0, + name: name.into(), + }; + imp::resolve(dll, &name) +} + +#[cfg(windows)] +mod imp { + use std::collections::HashMap; + use std::ffi::CString; + use std::sync::{LazyLock, Mutex}; + + use victory_pe::ImportSymbol; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA, + }; + + /// Module handles by lower-case DLL name (stored as usize: Send + Sync). + static MODULES: LazyLock<Mutex<HashMap<String, usize>>> = LazyLock::new(Default::default); + + pub(super) fn resolve(dll: &str, symbol: &ImportSymbol) -> Option<usize> { + let module = module(dll)?; + let proc = match symbol { + ImportSymbol::Name { name, .. } => { + let name = CString::new(name.as_str()).ok()?; + // SAFETY: valid module handle, NUL-terminated name. + unsafe { GetProcAddress(module as _, name.as_ptr().cast()) } + } + // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module. + ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(module as _, *o as usize as _) }, + }; + proc.map(|f| f as *const () as usize) + } + + fn module(dll: &str) -> Option<usize> { + let key = dll.to_ascii_lowercase(); + let mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&m) = cache.get(&key) { + return Some(m); + } + let name = CString::new(key.as_str()).ok()?; + // System32 only: never pick up a same-named DLL from the current folder or PATH. + // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here. + let handle = unsafe { + LoadLibraryExA( + name.as_ptr().cast(), + std::ptr::null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } as usize; + (handle != 0).then(|| *cache.entry(key).or_insert(handle)) + } +} + +#[cfg(not(windows))] +mod imp { + pub(super) fn resolve(_dll: &str, _symbol: &victory_pe::ImportSymbol) -> Option<usize> { + None + } +} diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs new file mode 100644 index 000000000..ed5b6321b --- /dev/null +++ b/crates/victory-hle/src/lib.rs @@ -0,0 +1,123 @@ +//! Our implementation of the Xbox system API surface. +//! +//! A title imports from three kinds of DLLs, and each gets its own policy: +//! +//! | kind | examples | handled by | +//! |------|----------|------------| +//! | Windows API sets the console shares with PC | `api-ms-win-core-synch-*`, `ws2_32.dll` | host pass-through, overridden here where console behaviour differs (paths, memory) | +//! | console-only system APIs | `xgameruntime.dll`, `xmem.dll`, `d3d12_xs.dll` | implemented here, in [`modules`] | +//! | anything else | | an unimplemented-import stub from the loader | +//! +//! Resolution order for every import: an implementation in [`modules`], +//! then the host if [`HostPolicy`] allows that DLL, then `Missing`. + +mod host; +pub mod modules; +mod registry; +pub mod runtime; + +pub use host::HostPolicy; +pub use registry::{HleExport, HleModule, registry}; +pub use victory_gpu::console; + +use victory_loader::{ImportResolver, Provenance, Resolution}; +use victory_pe::ImportSymbol; + +/// Resolves a title's imports against our runtime and the host. +#[derive(Debug, Default)] +pub struct HleResolver { + pub host: HostPolicy, +} + +impl HleResolver { + pub fn new(host: HostPolicy) -> Self { + HleResolver { host } + } + + /// Where an import would come from, without binding anything. + pub fn classify(&self, dll: &str, symbol: &ImportSymbol) -> Option<Provenance> { + match self.resolve(dll, symbol) { + Resolution::Found { provenance, .. } => Some(provenance), + Resolution::Missing => None, + } + } +} + +impl ImportResolver for HleResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + // Ordinal imports look up `#n`. + if let Some(address) = registry::lookup(dll, &symbol.to_string()) { + return Resolution::Found { + address, + provenance: Provenance::Hle, + }; + } + match self.host.resolve(dll, symbol) { + Some(address) => Resolution::Found { + address, + provenance: Provenance::Host, + }, + None => Resolution::Missing, + } + } +} + +// The registry is code-only, so the "Missing" outcome can be checked on any +// host; host pass-through itself needs Windows. +#[cfg(test)] +mod tests { + use super::*; + + fn name(n: &str) -> ImportSymbol { + ImportSymbol::Name { + hint: 0, + name: n.into(), + } + } + + #[test] + fn console_api_resolves_to_hle() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("XGameRuntime.dll", &name("XGameRuntimeInitialize")), + Some(Provenance::Hle) + ); + } + + #[test] + fn strict_policy_reports_missing() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("api-ms-win-core-synch-l1-1-0.dll", &name("Sleep")), + None + ); + } + + #[cfg(windows)] + #[test] + fn shared_api_sets_pass_through_to_host() { + let r = HleResolver::default(); + assert_eq!( + r.classify("api-ms-win-core-synch-l1-2-0.dll", &name("Sleep")), + Some(Provenance::Host) + ); + // Console-only DLLs never pass through. + assert_eq!( + r.classify("xmem.dll", &name("XMemSetAllocationHooks")), + None + ); + } + + #[cfg(windows)] + #[test] + fn overrides_win_over_host() { + let r = HleResolver::default(); + assert_eq!( + r.classify( + "api-ms-win-core-libraryloader-l1-2-0.dll", + &name("GetModuleHandleW") + ), + Some(Provenance::Hle) + ); + } +} diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs new file mode 100644 index 000000000..0668f0dea --- /dev/null +++ b/crates/victory-hle/src/modules/apu.rs @@ -0,0 +1,524 @@ +//! The console's audio decoder (`xapu.dll`): Opus packets in, float PCM out. +//! +//! A title connects once for one kind of processing, gets a block of memory +//! for its packets and output, and then queues per-stream commands +//! (activate, process, reset, deactivate) and dequeues one result per +//! command. We decode each command when it is queued, so its result is ready +//! at once; the order of results is the order of commands. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::Layout; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::sync::Mutex; + +use opus_pure::OpusDecoder; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; +use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent}; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32; +/// No result yet, which titles poll for. +pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; +const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32; +const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32; +const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32; +const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32; + +/// Processing kinds; only plain decoding is implemented. +const DECODE_OPUS: u32 = 1; + +const ACTIVATE: u32 = 1; +const DEACTIVATE: u32 = 2; +const PROCESS: u32 = 3; +const NOTIFY: u32 = 4; +const RESET: u32 = 5; + +/// Command option: signal the connection's event when the result is ready. +const SIGNAL: u32 = 1; +/// Connect options. +const DEINTERLEAVED_OUTPUT: u32 = 4; +const RESULT_EVENT: u32 = 8; + +/// The longest Opus packet duration at 48 kHz (120 ms). +const MAX_FRAMES: usize = 5760; + +#[repr(C)] +pub struct ConnectInput { + process: u32, + streams: u32, + commands_per_stream: u32, + memory: u32, + frames_per_output: u32, + options: u32, +} + +#[repr(C)] +pub struct ConnectOutput { + memory: *mut c_void, + result_event: HANDLE, +} + +/// What every command starts with, and what its result echoes. +#[repr(C, packed)] +#[derive(Clone, Copy)] +pub struct CommandId { + kind: u32, + stream: u32, + sequence: u32, + options: u32, + context: u64, +} + +#[repr(C, packed)] +struct Activate { + id: CommandId, + channels: u32, + init_length: u32, + init: *const c_void, + start_pitch: f32, + processing_length: u32, + processing: *mut c_void, +} + +#[repr(C, packed)] +#[derive(Clone, Copy)] +struct Process { + id: CommandId, + pitch_ramp: f32, + target_pitch: f32, + first_frame: u32, + frame_count: u32, + input_length: u32, + input: *const u8, + output_length: u32, + output: *mut u8, +} + +#[repr(C, packed)] +#[derive(Clone, Copy)] +pub struct ApuResult { + id: CommandId, + state: u32, + state_data: u64, + usec: u64, + error: HRESULT, + frames: u32, + output_length: u32, + output: *mut u8, + pitch: f32, + input_length: u32, + input: *const u8, +} + +// SAFETY: the raw pointers are title addresses carried through, never +// dereferenced after the result is made. +unsafe impl Send for ApuResult {} + +pub struct Connection { + memory: *mut u8, + layout: Layout, + event: HANDLE, + options: u32, + per_stream: u32, + state: Mutex<State>, +} + +struct State { + streams: Vec<Option<OpusDecoder>>, + /// Results not yet dequeued, per stream. + queued: Vec<u32>, + results: VecDeque<ApuResult>, + commands: u32, + dequeued: u32, +} + +fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> { + c.state.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub extern "system" fn XApuConnect( + input: *const ConnectInput, + output: *mut ConnectOutput, + handle: *mut *mut Connection, +) -> HRESULT { + if input.is_null() || output.is_null() || handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + let input = unsafe { &*input }; + if !(1..=500).contains(&input.streams) + || !(1..=16).contains(&input.commands_per_stream) + || input.memory == 0 + { + return E_INVALIDARG; + } + if input.process != DECODE_OPUS { + // shortcut: rate conversion (decode-convert, PCM convert) is not + // implemented; add a resampler if a title connects for it. + tracing::warn!( + process = input.process, + "audio decoder: processing kind not implemented" + ); + return E_NOTIMPL; + } + if input.frames_per_output != 0 { + return E_INVALIDARG; + } + let Ok(layout) = Layout::from_size_align(input.memory as usize, 16) else { + return E_INVALIDARG; + }; + // SAFETY: non-zero size. + let memory = unsafe { std::alloc::alloc_zeroed(layout) }; + if memory.is_null() { + return E_OUTOFMEMORY; + } + let event = if input.options & RESULT_EVENT != 0 { + // SAFETY: plain auto-reset event, no name. + unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) } + } else { + std::ptr::null_mut() + }; + let streams = input.streams as usize; + tracing::info!( + streams, + memory = input.memory, + options = input.options, + "audio decoder connected" + ); + let connection = Box::new(Connection { + memory, + layout, + event, + options: input.options, + per_stream: input.commands_per_stream, + state: Mutex::new(State { + streams: (0..streams).map(|_| None).collect(), + queued: vec![0; streams], + results: VecDeque::new(), + commands: 0, + dequeued: 0, + }), + }); + // SAFETY: checked non-null. + unsafe { + output.write(ConnectOutput { + memory: memory.cast(), + result_event: event, + }); + handle.write(Box::into_raw(connection)); + } + S_OK +} + +pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT { + if handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XApuConnect`; disconnected once. + let connection = unsafe { Box::from_raw(handle) }; + if !connection.event.is_null() { + // SAFETY: our event. + unsafe { CloseHandle(connection.event) }; + } + // SAFETY: allocated in `XApuConnect` with this layout. + unsafe { std::alloc::dealloc(connection.memory, connection.layout) }; + S_OK +} + +pub extern "system" fn XApuEnqueueCommand( + handle: *mut Connection, + command: *const CommandId, + total: *mut u32, +) -> HRESULT { + if handle.is_null() || command.is_null() { + return E_INVALIDARG; + } + // SAFETY: a connection from `XApuConnect`; every command starts with an id. + let (connection, id) = unsafe { (&*handle, command.read_unaligned()) }; + let mut state = lock(connection); + let stream = id.stream as usize; + if stream >= state.streams.len() { + return INVALID_STREAM; + } + if state.queued[stream] >= connection.per_stream { + return QUEUE_FULL; + } + let mut result = ApuResult { + id, + state: 0, + state_data: 0, + usec: 0, + error: S_OK, + frames: 0, + output_length: 0, + output: std::ptr::null_mut(), + pitch: 1.0, + input_length: 0, + input: std::ptr::null(), + }; + let decoder = &mut state.streams[stream]; + match id.kind { + ACTIVATE => { + // SAFETY: an activate command is this struct. + let channels = unsafe { command.cast::<Activate>().read_unaligned() }.channels; + tracing::debug!(stream, channels, "Opus stream activated"); + result.error = if decoder.is_some() { + ALREADY_ACTIVE + } else { + match OpusDecoder::new(48_000, channels as usize) { + Ok(d) if (1..=2).contains(&channels) => { + *decoder = Some(d); + S_OK + } + _ => E_INVALIDARG, + } + }; + } + DEACTIVATE => *decoder = None, + RESET => { + if let Some(d) = decoder { + let _ = d.reset_state(); + } + } + NOTIFY => {} + PROCESS => { + // SAFETY: a process command is this struct. + let command = unsafe { command.cast::<Process>().read_unaligned() }; + match decoder { + Some(d) => process(d, connection.options, &command, &mut result), + None => result.error = INVALID_STREAM, + } + } + _ => return INVALID_COMMAND, + } + state.queued[stream] += 1; + state.commands = state.commands.wrapping_add(1); + state.results.push_back(result); + if !total.is_null() { + // SAFETY: optional out parameter. + unsafe { total.write(state.commands) }; + } + if id.options & SIGNAL != 0 && !connection.event.is_null() { + // SAFETY: our event. + unsafe { SetEvent(connection.event) }; + } + S_OK +} + +/// Decodes one packet into the command's output buffer, keeping the frames +/// from `first_frame` on, at most `frame_count` of them. +fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) { + let channels = decoder.channels(); + let (input, input_length) = (command.input, command.input_length); + let (output, output_length) = (command.output, command.output_length); + result.input = input; + result.input_length = input_length; + result.output = output; + if input.is_null() || output.is_null() || input_length == 0 { + result.error = E_INVALIDARG; + return; + } + // SAFETY: the title's packet in its connection memory. + let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) }; + let mut pcm = vec![0f32; MAX_FRAMES * channels]; + let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) { + Ok(n) => n, + Err(_) => { + result.error = BAD_PACKET; + return; + } + }; + let first = (command.first_frame as usize).min(decoded); + let frames = (decoded - first) + .min(command.frame_count as usize) + .min(output_length as usize / (4 * channels)); + let kept = &pcm[first * channels..(first + frames) * channels]; + // SAFETY: the title's output buffer holds `output_length` bytes. + let out = unsafe { std::slice::from_raw_parts_mut(output.cast::<f32>(), 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 = (frames * channels * 4) as u32; +} + +pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT { + if handle.is_null() || out.is_null() { + return E_INVALIDARG; + } + // SAFETY: a connection from `XApuConnect`. + let mut state = lock(unsafe { &*handle }); + let Some(result) = state.results.pop_front() else { + return PENDING_RESULTS; + }; + let stream = result.id.stream as usize; + state.queued[stream] -= 1; + state.dequeued = state.dequeued.wrapping_add(1); + // SAFETY: the title passes room for one result. + unsafe { out.write_unaligned(result) }; + S_OK +} + +pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 { + if handle.is_null() { + return 0; + } + // SAFETY: a connection from `XApuConnect`. + let state = lock(unsafe { &*handle }); + if !total.is_null() { + // SAFETY: optional out parameter. + unsafe { total.write(state.dequeued) }; + } + state.results.len() as u32 +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "apu", + dlls: &["xapu.dll"], + exports: vec![ + hle_export!(XApuConnect), + hle_export!(XApuDisconnect), + hle_export!(XApuEnqueueCommand), + hle_export!(XApuDequeueResult), + hle_export!(XApuGetResultCount), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opus_pure::{Application, OpusEncoder}; + + fn id(kind: u32, stream: u32) -> CommandId { + CommandId { + kind, + stream, + sequence: 7, + options: 0, + context: 0x1234, + } + } + + #[test] + fn decodes_opus_as_the_title_drives_it() { + assert_eq!(size_of::<ApuResult>(), 0x50); + // 256 mono/stereo streams, two commands each, as the title connects. + let input = ConnectInput { + process: DECODE_OPUS, + streams: 256, + commands_per_stream: 2, + memory: 0x10_4000, + frames_per_output: 0, + options: 1, + }; + 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::<u8>(); + + let activate = Activate { + id: id(ACTIVATE, 3), + 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 + ); + + // A 20 ms stereo packet of a 440 Hz tone. + let tone: Vec<f32> = (0..960 * 2) + .map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5) + .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(); + // SAFETY: inside the connection memory. + unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; + let process = Process { + id: id(PROCESS, 3), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count: 960, + input_length: n as u32, + input: base, + output_length: 0xf00 * 2, + output: base.wrapping_add(0x14000), + }; + let mut total = 0; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total), + S_OK + ); + assert_eq!(total, 2); + // Two results queued for stream 3: its queue is full. + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total), + QUEUE_FULL + ); + assert_eq!(XApuGetResultCount(handle, std::ptr::null_mut()), 2); + + let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed(); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let first = unsafe { result.assume_init() }; + let (kind, error, context) = (first.id.kind, first.error, first.id.context); + assert_eq!((kind, error, context), (ACTIVATE, S_OK, 0x1234)); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let decoded = unsafe { result.assume_init() }; + let (kind, error, frames, length) = ( + decoded.id.kind, + decoded.error, + decoded.frames, + decoded.output_length, + ); + assert_eq!((kind, error, frames, length), (PROCESS, S_OK, 960, 960 * 8)); + // SAFETY: the decoder wrote 960 stereo frames there. + let pcm = + unsafe { std::slice::from_raw_parts(base.wrapping_add(0x14000).cast::<f32>(), 1920) }; + let energy: f32 = pcm.iter().map(|s| s * s).sum::<f32>() / 1920.0; + assert!(energy > 0.01, "decoded a tone, energy {energy}"); + assert_eq!( + XApuDequeueResult(handle, result.as_mut_ptr()), + PENDING_RESULTS + ); + let mut dequeued = 0; + assert_eq!(XApuGetResultCount(handle, &mut dequeued), 0); + assert_eq!(dequeued, 2); + + // A process on a stream that was never activated fails in its result. + let mut stray = process; + stray.id.stream = 4; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const stray).cast(), &mut total), + S_OK + ); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let error = unsafe { result.assume_init() }.error; + assert_eq!(error, INVALID_STREAM); + assert_eq!(XApuDisconnect(handle), S_OK); + } +} diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs new file mode 100644 index 000000000..ac34d4c01 --- /dev/null +++ b/crates/victory-hle/src/modules/audio.rs @@ -0,0 +1,1172 @@ +//! The console's audio hardware (`AcpHal.dll`): +//! +//! * the APU heap: host memory with 32-bit device addresses; +//! * SHAPE context arrays allocated from it; +//! * the audio coprocessor's command and message queues, where every +//! command completes at once and is acknowledged as the hardware would; +//! * the XMA decoder: enabled XMA contexts are decoded on a thread of ours +//! into their output rings, like the hardware does. +//! +//! SHAPE's other units (rate conversion, EQ, filters, mixing through +//! flowgraphs) are not emulated, so voices that need them stay silent. +//! 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. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::Layout; +use std::collections::{BTreeMap, VecDeque}; +use std::ffi::c_void; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard}; +use std::time::Instant; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +#[cfg(all(windows, feature = "diagnostics"))] +pub mod capture; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; + +fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +// The APU heap. + +struct Block { + size: usize, + apu: u32, + layout: Layout, +} + +struct Heap { + /// By host address. + blocks: BTreeMap<usize, Block>, + /// Host address by device address. + by_apu: BTreeMap<u32, usize>, + /// Free device address ranges, start to end, merged with neighbours. + free: BTreeMap<u32, u32>, + /// Set by `ApuCreateHeap` or the first allocation: the heap exists. + created: bool, +} + +static HEAP: Mutex<Heap> = Mutex::new(Heap { + blocks: BTreeMap::new(), + by_apu: BTreeMap::new(), + free: BTreeMap::new(), + created: false, +}); + +/// Device addresses start above 0, which means "none" to titles. +const APU_BASE: u32 = 0x0001_0000; + +impl Heap { + /// First fit in the free ranges. + fn take(&mut self, size: u32, align: u32) -> Option<u32> { + if self.free.is_empty() && !self.created { + self.free.insert(APU_BASE, u32::MAX); + } + self.created = true; + let (start, end, apu) = self.free.iter().find_map(|(&start, &end)| { + let apu = start.checked_next_multiple_of(align)?; + (apu.checked_add(size)? <= end).then_some((start, end, apu)) + })?; + self.free.remove(&start); + if start < apu { + self.free.insert(start, apu); + } + if apu + size < end { + self.free.insert(apu + size, end); + } + Some(apu) + } + + fn give_back(&mut self, mut start: u32, mut end: u32) { + if let Some((&before, &before_end)) = self.free.range(..start).next_back() + && before_end == start + { + self.free.remove(&before); + start = before; + } + if let Some(after_end) = self.free.remove(&end) { + end = after_end; + } + self.free.insert(start, end); + } +} + +/// Zeroed host memory and its device address. +fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> { + let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?; + let mut heap = lock(&HEAP); + let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?; + // SAFETY: non-zero size. + let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; + if ptr.is_null() { + heap.give_back(apu, apu + layout.size() as u32); + return None; + } + 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)) +} + +fn heap_free(ptr: *mut u8) { + let mut heap = lock(&HEAP); + let Some(block) = heap.blocks.remove(&(ptr as usize)) else { + return; + }; + heap.by_apu.remove(&block.apu); + heap.give_back(block.apu, block.apu + block.layout.size() as u32); + drop(heap); + // SAFETY: allocated by `heap_alloc` with this layout. + unsafe { std::alloc::dealloc(ptr, block.layout) }; +} + +/// Sizes the heap once, before anything is allocated from it. The console +/// reserves both parts up front; we allocate per block, so the sizes only +/// decide whether the call is valid. +// shortcut: the cached and non-cached sizes are not enforced as limits; +// enforce them if a title relies on running out. +pub extern "system" fn ApuCreateHeap(cached: u32, _non_cached: u32) -> HRESULT { + const ALREADY_ALLOCATED: HRESULT = 0x8ACA_0001_u32 as i32; + if cached == 0 { + return E_INVALIDARG; + } + let mut heap = lock(&HEAP); + if heap.created { + return ALREADY_ALLOCATED; + } + heap.created = true; + heap.free.insert(APU_BASE, u32::MAX); + S_OK +} + +/// The host address of a device address, null outside the heap. +pub extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void { + heap_unmap(apu).map_or(std::ptr::null_mut(), |p| p.cast()) +} + +/// The device address of any byte of a heap block, 0 elsewhere. +fn heap_map(ptr: usize) -> u32 { + let heap = lock(&HEAP); + match heap.blocks.range(..=ptr).next_back() { + Some((&start, block)) if ptr < start + block.size.max(1) => { + block.apu + (ptr - start) as u32 + } + _ => 0, + } +} + +/// The host address of a device address, if a heap block holds it. +fn heap_unmap(apu: u32) -> Option<*mut u8> { + let heap = lock(&HEAP); + let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; + let block = &heap.blocks[&host]; + (apu < start.saturating_add(block.size.max(1) as u32)) + .then(|| (host + (apu - start) as usize) as *mut u8) +} + +/// `len` bytes of title memory at a device address, if one heap block holds +/// them all. +fn heap_bytes<'a>(apu: u32, len: usize) -> Option<&'a mut [u8]> { + let heap = lock(&HEAP); + let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; + let offset = (apu - start) as usize; + (offset + len <= heap.blocks[&host].size) + // SAFETY: inside a live heap block, which the title and the audio + // hardware share like on the console. + .then(|| unsafe { std::slice::from_raw_parts_mut((host + offset) as *mut u8, len) }) +} + +pub extern "system" fn ApuAlloc( + out: *mut *mut c_void, + apu: *mut u32, + size: u32, + align: u32, + _flags: u32, +) -> HRESULT { + if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() { + return E_INVALIDARG; + } + let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else { + return E_OUTOFMEMORY; + }; + // SAFETY: checked non-null; optional out parameter checked below. + unsafe { + out.write(ptr.cast()); + if !apu.is_null() { + apu.write(address); + } + } + S_OK +} + +pub extern "system" fn ApuFree(ptr: *mut c_void) { + heap_free(ptr.cast()); +} + +pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 { + heap_map(ptr as usize) +} + +pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool { + let apu = heap_map(ptr as usize); + apu != 0 && (align == 0 || apu.is_multiple_of(align)) +} + +// SHAPE context arrays. + +/// Six counts (rate conversion, EQ/compression, filter/volume, DMA, XMA, +/// PCM), then the six arrays and their device addresses. +#[repr(C, packed)] +pub struct ShapeContexts { + counts: [u32; 6], + arrays: [*mut c_void; 6], + apu: [u32; 6], +} + +/// Bytes per context: rate conversion, DMA and XMA as fmod clears them; +/// the others (not seen yet) get a generous upper bound. +const CONTEXT_BYTES: [usize; 6] = [32, 256, 256, 16, 64, 256]; + +static CONTEXTS: Mutex<Option<[usize; 6]>> = Mutex::new(None); + +pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) -> HRESULT { + if contexts.is_null() { + return E_INVALIDARG; + } + let mut allocated = lock(&CONTEXTS); + if allocated.is_some() { + return E_FAIL; + } + // SAFETY: the title passes its request; packed fields are copied out. + let counts = unsafe { std::ptr::addr_of!((*contexts).counts).read_unaligned() }; + let mut arrays: [*mut c_void; 6] = [std::ptr::null_mut(); 6]; + let mut addresses = [0u32; 6]; + for i in 0..6 { + if counts[i] == 0 { + continue; + } + let Some((ptr, apu)) = heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) else { + arrays.iter().for_each(|&p| heap_free(p.cast())); + return E_OUTOFMEMORY; + }; + (arrays[i], addresses[i]) = (ptr.cast(), apu); + } + // SAFETY: as above. + unsafe { + std::ptr::addr_of_mut!((*contexts).arrays).write_unaligned(arrays); + std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses); + } + *allocated = Some(arrays.map(|p| p as usize)); + let mut xma = XMA.write().unwrap_or_else(|e| e.into_inner()); + xma.array = arrays[4] as usize; + xma.voices = (0..counts[4]).map(|_| Mutex::new(None)).collect(); + S_OK +} + +pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT { + match lock(&CONTEXTS).take() { + Some(arrays) => { + *XMA.write().unwrap_or_else(|e| e.into_inner()) = Xma::EMPTY; + arrays.iter().for_each(|&p| heap_free(p as *mut u8)); + S_OK + } + None => E_FAIL, + } +} + +// The XMA decoder. +// +// An XMA context (16 words in the shared context array) names up to two +// input buffers of 2 KiB packets, a ring of 256-byte output blocks the +// hardware fills with 16-bit PCM, and the read offset the title advances +// by command. Words and bit fields, as titles write them: +// 0: input 0 size in packets (0-11), loop count (12-19, 255 forever), +// valid inputs (20-21), output size in blocks (22-26), write block +// (27-31, hardware); +// 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes +// to skip (17-19), subframes to skip at the start (24-26), sample rate +// (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31); +// 2: read position in bits (0-25), error status (26-30), error (31); +// 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input +// (31); 5, 6: input addresses; 7: output address; 8: overlap buffer; +// 9: read block (0-4). +// Titles read back only the write block, "writable" and the read block, +// and take whatever lies between read and write. +// shortcut: each enabled context decodes from a cold state and the overlap +// buffer is ignored (titles copy it between consecutive contexts of one +// voice); keep decoder state there if a title's seams turn out audible. + +use victory_formats::xma; + +const ENABLE_XMA: u32 = 5; +const ENABLE_XMAS: u32 = 6; +const DISABLE_XMA: u32 = 7; +const DISABLE_XMAS: u32 = 8; +const ADVANCE_XMA_READ: u32 = 18; + +const BLOCK_BYTES: usize = 256; +const SAMPLES_PER_BLOCK: usize = BLOCK_BYTES / 2; +/// Error status: the input ran out. +const INPUT_INVALID: u32 = 4; + +struct Voice { + decoder: Option<xma::Decoder>, + pcm: VecDeque<i16>, + /// Samples per channel still to drop (start or loop subframe skips). + skip: usize, + ended: bool, + trace: Trace, +} + +/// What a voice did, for the debug log when it is disabled. +struct Trace { + since: Instant, + /// Samples per channel written to the ring. + produced: usize, + /// Blocks the title took (command 18), how often, and how often it + /// found the ring less than full. + taken: usize, + takes: u32, + partial_takes: u32, + frames: u32, + bad_frames: u32, + /// The loudest sample written. + peak: i16, + /// Milliseconds after enabling when the input ran out. + ended_ms: Option<u128>, +} + +struct Xma { + /// Host address of the context array. + array: usize, + /// One entry per context, `Some` while enabled. Each has its own lock, + /// so a command for one voice never waits for others to decode (the + /// title sends them from its time-critical mixer thread). + voices: Vec<Mutex<Option<Voice>>>, +} + +impl Xma { + const EMPTY: Xma = Xma { + array: 0, + voices: Vec::new(), + }; +} + +/// Written only when the context arrays are allocated or released. +static XMA: RwLock<Xma> = RwLock::new(Xma::EMPTY); + +fn xma() -> RwLockReadGuard<'static, Xma> { + XMA.read().unwrap_or_else(|e| e.into_inner()) +} + +/// A context's words in title memory. +#[derive(Clone, Copy)] +struct Context(*mut u32); + +impl Context { + fn get(self, word: usize) -> u32 { + // SAFETY: inside the context array; the title reads and writes it + // concurrently, like the hardware's. + unsafe { self.0.add(word).read_volatile() } + } + + fn set(self, word: usize, value: u32) { + // SAFETY: as above. + unsafe { self.0.add(word).write_volatile(value) } + } + + fn field(self, word: usize, shift: u32, bits: u32) -> u32 { + (self.get(word) >> shift) & ((1 << bits) - 1) + } + + fn set_field(self, word: usize, shift: u32, bits: u32, value: u32) { + let mask = ((1u32 << bits) - 1) << shift; + self.set(word, (self.get(word) & !mask) | ((value << shift) & mask)); + } + + fn channels(self) -> usize { + 1 + self.field(1, 29, 1) as usize + } +} + +impl Xma { + fn context(&self, index: u32) -> Option<Context> { + ((index as usize) < self.voices.len() && self.array != 0) + .then(|| Context((self.array + index as usize * 64) as *mut u32)) + } + + fn enable(&self, index: u32) { + let Some(context) = self.context(index) else { + return; + }; + let mut slot = lock(&self.voices[index as usize]); + context.set_field(2, 26, 6, 0); + tracing::debug!( + index, + words = ?(0..10).map(|w| format!("{:08x}", context.get(w))).collect::<Vec<_>>(), + "XMA voice enabled" + ); + #[cfg(feature = "diagnostics")] + dump_input(index, context); + *slot = Some(Voice { + decoder: None, + pcm: VecDeque::new(), + skip: context.field(1, 24, 3) as usize * xma::SUBFRAME_SAMPLES, + ended: false, + trace: Trace { + since: Instant::now(), + produced: 0, + taken: 0, + takes: 0, + partial_takes: 0, + frames: 0, + bad_frames: 0, + peak: 0, + ended_ms: None, + }, + }); + drop(slot); + wake_decoder(); + } + + fn disable(&self, index: u32) { + let Some(context) = self.context(index) else { + return; + }; + let Some(voice) = lock(&self.voices[index as usize]).take() else { + return; + }; + let t = &voice.trace; + tracing::debug!( + index, + ms = t.since.elapsed().as_millis(), + produced = t.produced, + taken = t.taken * SAMPLES_PER_BLOCK / context.channels(), + takes = t.takes, + partial_takes = t.partial_takes, + frames = t.frames, + bad_frames = t.bad_frames, + peak = t.peak, + input_ended_ms = ?t.ended_ms, + read_bit = context.field(2, 0, 26), + input_bits = context.field(0, 0, 12) * xma::PACKET_BYTES as u32 * 8, + "XMA voice disabled" + ); + } + + /// Moves the title's read block on, which frees output space. + fn advance_read(&self, index: u32, blocks: u32) { + let Some(context) = self.context(index) else { + return; + }; + // The decoder writes the same words. + let mut slot = lock(&self.voices[index as usize]); + let size = context.field(0, 22, 5).max(1); + // The count is the title's: reduced first, so the sum stays small. + let read = (context.field(9, 0, 5) + blocks % size) % size; + context.set_field(9, 0, 5, read); + if blocks > 0 { + context.set_field(1, 31, 1, 1); + } + if let Some(voice) = &mut *slot { + let t = &mut voice.trace; + t.taken += blocks as usize; + t.takes += 1; + t.partial_takes += u32::from(blocks < size); + } + drop(slot); + wake_decoder(); + } + + /// Fills every enabled context's output as far as it has room. + fn pump(&self) { + 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])) + { + pump(context, voice); + active += 1; + } + } + let took = start.elapsed(); + if took.as_millis() >= 4 { + tracing::debug!(active, ms = took.as_millis(), "slow XMA decoding pass"); + } + } +} + +fn pump(context: Context, voice: &mut Voice) { + let size = context.field(0, 22, 5); + if size == 0 { + return; + } + while context.field(1, 31, 1) == 1 { + if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) { + return; + } + let write = context.field(0, 27, 5); + let address = context.get(7) as usize + write as usize * BLOCK_BYTES; + let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else { + return; + }; + for pair in out.as_chunks_mut::<2>().0 { + let sample = voice.pcm.pop_front().unwrap_or(0); + voice.trace.peak = voice.trace.peak.max(sample.saturating_abs()); + pair.copy_from_slice(&sample.to_le_bytes()); + } + voice.trace.produced += SAMPLES_PER_BLOCK / context.channels(); + let write = (write + 1) % size; + context.set_field(0, 27, 5, write); + if write == context.field(9, 0, 5) { + // Full: nothing more until the title advances its read block. + context.set_field(1, 31, 1, 0); + } + } +} + +/// Decodes the next frame of the current input into `voice.pcm`; false +/// when there is nothing left to decode. +fn decode(context: Context, voice: &mut Voice) -> bool { + if voice.ended { + return false; + } + let channels = context.channels(); + let mut current = context.field(4, 31, 1); + let valid = context.field(0, 20, 2); + if valid & (1 << current) == 0 { + if valid & (1 << (1 - current)) == 0 { + // Out of input: the overlap tail, then nothing. + if let Some(decoder) = &mut voice.decoder { + let mut tail = Vec::new(); + decoder.flush(&mut tail); + voice.pcm.extend(tail); + } + voice.ended = true; + voice.trace.ended_ms = Some(voice.trace.since.elapsed().as_millis()); + context.set_field(2, 26, 5, INPUT_INVALID); + context.set_field(2, 31, 1, 1); + return !voice.pcm.is_empty(); + } + current = 1 - current; + context.set_field(4, 31, 1, current); + context.set_field(2, 0, 26, 0); + } + let (address, packets) = match current { + 0 => (context.get(5), context.field(0, 0, 12)), + _ => (context.get(6), context.field(1, 0, 12)), + }; + let Some(data) = heap_bytes(address & !0x7ff, packets as usize * xma::PACKET_BYTES) else { + context.set_field(0, 20 + current, 1, 0); + return true; + }; + let mut at = context.field(2, 0, 26) as usize; + if at < 32 { + at = 32 + xma::packet(data, 0).map_or(0, |p| p.first_frame_bit as usize); + } + let Some(frame) = xma::read_frame(data, at) else { + // This input is used up. + context.set_field(0, 20 + current, 1, 0); + return true; + }; + let decoder = voice.decoder.get_or_insert_with(|| { + const RATES: [u32; 4] = [24_000, 32_000, 44_100, 48_000]; + xma::Decoder::new(channels, RATES[context.field(1, 27, 2) as usize]) + }); + let mut pcm = Vec::with_capacity(xma::FRAME_SAMPLES * channels); + voice.trace.frames += 1; + if let Err(e) = decoder.decode(&frame.data, frame.bits, &mut pcm) { + voice.trace.bad_frames += 1; + if voice.trace.bad_frames <= 2 { + tracing::debug!( + at, + bits = frame.bits, + head = ?&frame.data[..frame.data.len().min(8)], + %e, + "XMA frame did not decode" + ); + } + } + let mut next = frame.next.unwrap_or(0); + let loops = context.field(0, 12, 8); + let loop_end = context.field(4, 0, 26) as usize; + let ends_loop = loop_end != 0 + && (frame.start == loop_end + || (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n))); + if loops > 0 && ends_loop { + let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels; + pcm.truncate(keep); + next = context.field(3, 0, 26) as usize; + voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; + if loops != 255 { + context.set_field(0, 12, 8, loops - 1); + } + } + let skip = (voice.skip * channels).min(pcm.len()); + voice.skip -= skip / channels; + voice.pcm.extend(&pcm[skip..]); + if next == 0 { + context.set_field(0, 20 + current, 1, 0); + } + context.set_field(2, 0, 26, next as u32); + true +} + +/// `VICTORY_XMA_DUMP=<dir>`: saves the context words (`<n>-<index>.ctx`) +/// and input buffer 0 (`.xma`) of the first 32 voices enabled, to test +/// the decoder on a title's streams outside the title. +#[cfg(feature = "diagnostics")] +fn dump_input(index: u32, context: Context) { + static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let Some(dir) = std::env::var_os("VICTORY_XMA_DUMP") else { + return; + }; + let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if n >= 32 { + return; + } + let dir = std::path::PathBuf::from(dir); + let words: Vec<u8> = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect(); + let input = heap_bytes( + context.get(5) & !0x7ff, + context.field(0, 0, 12) as usize * xma::PACKET_BYTES, + ); + 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()); +} + +/// Starts the decoding thread on the first enabled voice, and has it fill +/// rings now: a voice just enabled or read from. +fn wake_decoder() { + static DECODER: OnceLock<std::thread::Thread> = OnceLock::new(); + DECODER + .get_or_init(|| { + std::thread::Builder::new() + .name("victory XMA decoder".into()) + .spawn(|| { + loop { + xma().pump(); + // A 256-byte output block lasts 2.7 ms at 48 kHz mono. + std::thread::park_timeout(std::time::Duration::from_millis(2)); + } + }) + .map_or_else(|_| std::thread::current(), |h| h.thread().clone()) + }) + .unpark(); +} + +/// Runs an XMA command; false for one this does not know. +fn xma_command(command: u32, word: impl Fn(usize) -> Option<u32>) -> bool { + let xma = xma(); + match command { + ENABLE_XMA => xma.enable(word(0).unwrap_or(u32::MAX)), + DISABLE_XMA => xma.disable(word(0).unwrap_or(u32::MAX)), + ENABLE_XMAS | DISABLE_XMAS => { + for i in 0..xma.voices.len() as u32 { + if word(i as usize / 32).unwrap_or(0) & (1 << (i % 32)) != 0 { + match command { + ENABLE_XMAS => xma.enable(i), + _ => xma.disable(i), + } + } + } + } + ADVANCE_XMA_READ => xma.advance_read(word(0).unwrap_or(u32::MAX), word(1).unwrap_or(0)), + _ => return false, + } + true +} + +// The audio coprocessor. + +const LOAD_FLOWGRAPH: u32 = 1; +const REGISTER_MESSAGES: u32 = 2; +const UNREGISTER_MESSAGES: u32 = 3; + +const FLOWGRAPH_COMPLETED: u32 = 0x02; +const COMMAND_COMPLETED: u32 = 0x10; +const DISCONNECTED: u32 = 0x80; + +/// Audio frames of 128 samples at 48 kHz. +const FRAMES_PER_SECOND: u64 = 375; + +#[repr(C, packed)] +#[derive(Clone, Copy)] +struct Message { + kind: u32, + dropped: u32, + usec: u32, + data: [u8; 16], +} + +struct State { + connected: bool, + /// Message kinds the title registered for. + mask: u32, + messages: VecDeque<Message>, + /// Queue size given to `connect`. + capacity: usize, + /// Messages lost to a full queue since the last one queued. + dropped: u32, + since: Instant, +} + +impl State { + fn usec(&self) -> u64 { + self.since.elapsed().as_micros() as u64 + } + + fn frame(&self) -> u32 { + (self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32 + } + + /// Queues a registered message; a full queue drops it and counts it in + /// the next one that fits. + fn post(&mut self, kind: u32, data: &[u8]) { + if self.mask & kind == 0 { + return; + } + if self.messages.len() >= self.capacity { + self.dropped = self.dropped.saturating_add(1); + tracing::debug!(kind, dropped = self.dropped, "coprocessor message dropped"); + return; + } + let mut message = Message { + kind, + dropped: std::mem::take(&mut self.dropped), + usec: self.usec() as u32, + data: [0; 16], + }; + message.data[..data.len()].copy_from_slice(data); + self.messages.push_back(message); + } +} + +/// The interface object: its method table, then our state. +#[repr(C)] +pub struct Acp { + vtable: &'static AcpMethods, + state: Mutex<State>, +} + +#[repr(C)] +struct AcpMethods { + connect: extern "system" fn(*mut Acp, u32, u32) -> HRESULT, + disconnect: extern "system" fn(*mut Acp) -> HRESULT, + submit: extern "system" fn(*mut Acp, u32, u64, u32, *const c_void, u32) -> HRESULT, + pop_message: extern "system" fn(*mut Acp, *mut Message) -> bool, + message_count: extern "system" fn(*mut Acp) -> u32, + release: extern "system" fn(*mut Acp), +} + +static ACP_METHODS: AcpMethods = AcpMethods { + connect, + disconnect, + submit, + pop_message, + message_count, + release, +}; + +fn state(this: *mut Acp) -> MutexGuard<'static, State> { + // SAFETY: title code calls methods on the object `AcpHalCreate` made, + // which lives until `release`. + lock(unsafe { &(*this).state }) +} + +extern "system" fn connect(this: *mut Acp, commands: u32, messages: u32) -> HRESULT { + if commands == 0 { + return E_INVALIDARG; + } + let mut state = state(this); + state.connected = true; + state.capacity = messages as usize; + S_OK +} + +extern "system" fn disconnect(this: *mut Acp) -> HRESULT { + let mut state = state(this); + if !state.connected { + return E_FAIL; + } + state.post(DISCONNECTED, &[]); + state.connected = false; + S_OK +} + +/// Done at once: message registrations take effect, a flowgraph completes +/// unprocessed, a command with an id is acknowledged, and its notification +/// word is set. +extern "system" fn submit( + this: *mut Acp, + command: u32, + id: u64, + _frame: u32, + data: *const c_void, + notification: u32, +) -> HRESULT { + static SEEN: Mutex<u64> = Mutex::new(0); + if command < 64 && *lock(&SEEN) & 1 << command == 0 { + *lock(&SEEN) |= 1 << command; + tracing::info!(command, "first coprocessor command of this kind"); + } + let mut state = state(this); + let word = |at: usize| -> Option<u32> { + // SAFETY: the command's data starts with these u32 fields. + (!data.is_null()).then(|| unsafe { data.cast::<u32>().add(at).read_unaligned() }) + }; + match command { + REGISTER_MESSAGES => state.mask |= word(0).unwrap_or(0), + UNREGISTER_MESSAGES => state.mask &= !word(0).unwrap_or(0), + LOAD_FLOWGRAPH => { + let flowgraph = word(1).unwrap_or(0); + state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes()); + } + _ if xma_command(command, word) => {} + // shortcut: context updates and the other SHAPE units' commands are + // acknowledged but not carried out; add them when a title sends + // them (each kind is logged once above). + _ => {} + } + if id != 0 { + let mut done = [0u8; 16]; + done[..4].copy_from_slice(&command.to_le_bytes()); + done[4..12].copy_from_slice(&id.to_le_bytes()); + done[12..].copy_from_slice(&state.frame().to_le_bytes()); + state.post(COMMAND_COMPLETED, &done); + } + if notification != 0 + && let Some(word) = heap_unmap(notification) + { + // SAFETY: a u32 in a heap block, which the title reads as volatile. + unsafe { word.cast::<u32>().write_volatile(1) }; + } + S_OK +} + +extern "system" fn pop_message(this: *mut Acp, out: *mut Message) -> bool { + let Some(message) = state(this).messages.pop_front() else { + return false; + }; + if !out.is_null() { + // SAFETY: the title passes room for one message. + unsafe { out.write_unaligned(message) }; + } + true +} + +extern "system" fn message_count(this: *mut Acp) -> u32 { + state(this).messages.len() as u32 +} + +extern "system" fn release(this: *mut Acp) { + // SAFETY: made by `AcpHalCreate` with `Box::into_raw`; released once. + drop(unsafe { Box::from_raw(this) }); +} + +pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let acp = Box::new(Acp { + vtable: &ACP_METHODS, + state: Mutex::new(State { + connected: false, + mask: 0, + messages: VecDeque::new(), + capacity: 0, + dropped: 0, + since: Instant::now(), + }), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(acp)) }; + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "audio", + dlls: &["acphal.dll"], + exports: vec![ + hle_export!(AcpHalAllocateShapeContexts), + hle_export!(AcpHalReleaseShapeContexts), + hle_export!(AcpHalCreate), + hle_export!(ApuAlloc), + hle_export!(ApuCreateHeap), + hle_export!(ApuFree), + hle_export!(ApuIsVirtualAddressValid), + hle_export!(ApuMapApuAddress), + hle_export!(ApuMapVirtualAddress), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn heap_maps_every_byte_of_a_block() { + let _serial = lock(&CONTEXT_TESTS); + let (mut ptr, mut apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 128, 1), S_OK); + assert!(apu != 0 && apu.is_multiple_of(128)); + let inner = ptr.cast::<u8>().wrapping_add(0x40).cast_const().cast(); + assert_eq!(ApuMapVirtualAddress(inner), apu + 0x40); + assert!(ApuIsVirtualAddressValid(ptr, 128)); + assert_eq!(heap_unmap(apu + 4), Some(ptr.cast::<u8>().wrapping_add(4))); + ApuFree(ptr); + assert_eq!(ApuMapVirtualAddress(ptr), 0); + assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG); + } + + /// The context arrays and the heap exist once per process: tests that + /// allocate from them run one at a time (a concurrent allocation could + /// take a freed range a test expects back). + static CONTEXT_TESTS: Mutex<()> = Mutex::new(()); + + #[test] + fn heap_reuses_freed_addresses() { + let _serial = lock(&CONTEXT_TESTS); + let (mut a, mut b, mut c) = ( + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ); + let (mut apu_a, mut apu_b, mut apu_c) = (0, 0, 0); + assert_eq!(ApuAlloc(&mut a, &mut apu_a, 0x1000, 0x1000, 1), S_OK); + assert_eq!(ApuAlloc(&mut b, &mut apu_b, 0x1000, 0x1000, 1), S_OK); + ApuFree(a); + assert_eq!(ApuAlloc(&mut c, &mut apu_c, 0x800, 0x800, 1), S_OK); + // The freed range is free again, whichever part `c` took. + assert!( + lock(&HEAP) + .free + .iter() + .any(|(&s, &e)| s <= apu_a + 0x800 && apu_a + 0x1000 <= e) + || apu_c == apu_a + ); + assert_eq!( + ApuMapApuAddress(apu_b + 8), + b.cast::<u8>().wrapping_add(8).cast() + ); + assert!(ApuMapApuAddress(0).is_null()); + assert_eq!( + ApuCreateHeap(64 << 20, 0), + 0x8ACA_0001_u32 as i32, + "too late" + ); + ApuFree(b); + ApuFree(c); + } + + /// Two packets of three silent mono frames each: a fixed one-subframe + /// layout, no transmitted coefficients. + fn silent_stream() -> Vec<u8> { + let mut data = vec![0xffu8; 2 * xma::PACKET_BYTES]; + let mut put = |at: usize, value: u32, width: usize| { + for i in 0..width { + let (p, bit) = (at + i, (value >> (width - 1 - i)) & 1); + data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8)); + } + }; + for packet in 0..2 { + let base = packet * xma::PACKET_BYTES * 8; + put(base, 3 << 26, 32); + for frame in 0..3 { + let at = base + 32 + frame * 31; + put(at, 31, 15); // length + put(at + 15, 0b10, 2); // fixed layout, one 512-sample subframe + put(at + 17, 0, 8 + 1 + 3 + 2); // gain, no trim, empty subframe + } + } + data + } + + #[test] + fn xma_contexts_decode_into_their_output_rings() { + let _serial = lock(&CONTEXT_TESTS); + let mut request = ShapeContexts { + counts: [0, 0, 0, 0, 4, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let context = Context(request.arrays[4].cast::<u32>().wrapping_add(16)); + + let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); + let stream = silent_stream(); + // SAFETY: two packets were allocated. + unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; + let (mut output, mut output_apu) = (std::ptr::null_mut(), 0); + assert_eq!( + ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2), + S_OK + ); + // SAFETY: the ring was just allocated. + unsafe { output.cast::<u8>().write_bytes(0x55, 0x400) }; + + // As the title sets one up: two packets, input 0 valid, a ring of + // four blocks, writable, 48 kHz mono, reading from the first frame. + context.set(0, 2 | 1 << 20 | 4 << 22); + context.set(1, 1 << 31 | 3 << 27); + context.set(2, 32); + context.set(5, input_apu); + context.set(7, output_apu); + + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x1000, 0x1000), S_OK); + let submit = |command: u32, words: &[u32]| { + assert_eq!( + (m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0), + S_OK + ); + }; + submit(ENABLE_XMA, &[1]); + xma().pump(); + // Full: all four blocks written (silence), the write block wrapped + // onto the read block, and the ring no longer writable. + assert_eq!(context.field(0, 27, 5), 0); + assert_eq!(context.field(1, 31, 1), 0); + // SAFETY: the ring. + let ring = unsafe { std::slice::from_raw_parts(output.cast::<u8>(), 0x400) }; + assert!(ring.iter().all(|&b| b == 0)); + + // Read four blocks at a time until the input has run out and the + // ring keeps room (the decoding thread may fill it too). + for _ in 0..20 { + submit(ADVANCE_XMA_READ, &[1, 4]); + xma().pump(); + if context.field(2, 31, 1) == 1 && context.field(1, 31, 1) == 1 { + break; + } + } + // Six frames and the flushed tail: 3,328 samples, 26 blocks. + let produced = |x: &Xma| lock(&x.voices[1]).as_ref().map(|v| v.trace.produced); + assert_eq!(produced(&xma()), Some(26 * SAMPLES_PER_BLOCK)); + assert_eq!(context.field(0, 20, 2), 0, "input used up"); + assert_eq!(context.field(2, 26, 5), INPUT_INVALID); + + // A count near `u32::MAX` wraps the read block like any other + // (3 + 0xffff_ffff blocks on a ring of four is block 2); the sum + // used to overflow. + context.set_field(9, 0, 5, 3); + submit(ADVANCE_XMA_READ, &[1, u32::MAX]); + assert_eq!(context.field(9, 0, 5), 2); + + submit(DISABLE_XMA, &[1]); + assert_eq!(produced(&xma()), None); + (m.release)(acp); + ApuFree(input); + ApuFree(output); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + } + + #[test] + fn full_message_queues_count_drops() { + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 16, 2), S_OK); + let mask = COMMAND_COMPLETED; + assert_eq!( + (m.submit)( + acp, + REGISTER_MESSAGES, + 0, + u32::MAX, + (&raw const mask).cast(), + 0 + ), + S_OK + ); + for id in 1..=4 { + assert_eq!((m.submit)(acp, 12, id, u32::MAX, std::ptr::null(), 0), S_OK); + } + assert_eq!((m.message_count)(acp), 2); + let mut message = Message { + kind: 0, + dropped: 0, + usec: 0, + data: [0; 16], + }; + assert!((m.pop_message)(acp, &mut message) && (m.pop_message)(acp, &mut message)); + assert_eq!((m.submit)(acp, 12, 5, u32::MAX, std::ptr::null(), 0), S_OK); + assert!((m.pop_message)(acp, &mut message)); + let dropped = message.dropped; + assert_eq!(dropped, 2); + (m.release)(acp); + } + + #[test] + fn startup_as_fmod_does_it() { + let _serial = lock(&CONTEXT_TESTS); + // Context arrays: rate conversion, DMA and XMA. + let mut request = ShapeContexts { + counts: [0x200, 0, 0, 0x400, 0x200, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(size_of::<ShapeContexts>(), 0x60); + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let arrays = request.arrays; + assert!(!arrays[0].is_null() && !arrays[3].is_null() && !arrays[4].is_null()); + assert!(arrays[1].is_null()); + // SAFETY: 0x200 rate-conversion contexts of 32 bytes were allocated. + unsafe { arrays[0].cast::<u8>().write_bytes(0, 0x200 << 5) }; + + // Connect, register every message but frame starts, then wait for + // the registration to be acknowledged. + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x804, 0x804), S_OK); + let mask = 0xfe_u32; + let data = (&raw const mask).cast(); + assert_eq!( + (m.submit)(acp, REGISTER_MESSAGES, 1, u32::MAX, data, 0), + S_OK + ); + let mut message = Message { + kind: 0, + dropped: 0, + usec: 0, + data: [0; 16], + }; + assert!((m.pop_message)(acp, &mut message)); + let (kind, dropped) = (message.kind, message.dropped); + assert_eq!((kind, dropped), (COMMAND_COMPLETED, 0)); + assert_eq!( + u64::from_le_bytes(message.data[4..12].try_into().unwrap()), + 1 + ); + assert!(!(m.pop_message)(acp, &mut message)); + assert_eq!((m.disconnect)(acp), S_OK); + assert_eq!((m.message_count)(acp), 1, "disconnected"); + (m.release)(acp); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + } +} diff --git a/crates/victory-hle/src/modules/audio/capture.rs b/crates/victory-hle/src/modules/audio/capture.rs new file mode 100644 index 000000000..f39bb3dae --- /dev/null +++ b/crates/victory-hle/src/modules/audio/capture.rs @@ -0,0 +1,229 @@ +//! Debugging aid: `VICTORY_AUDIO_CAPTURE=<file.wav>` records what the title +//! plays, 48 kHz stereo 16-bit, through process loopback: our own process +//! tree only, never the rest of the host's mix. Stretches where nothing was +//! played are written as silence, so the file keeps real time. +//! +//! The recorder runs in a child copy of this executable: an audio client +//! in the title's process raises that process's timer resolution, which +//! changes how the title's own waits behave. + +use std::fs::File; +use std::io::{Seek, SeekFrom, Write}; +use std::path::Path; +use std::time::{Duration, Instant}; + +use windows::Win32::Media::Audio::{ + AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK, + AUDIOCLIENT_ACTIVATION_PARAMS, AUDIOCLIENT_ACTIVATION_PARAMS_0, + AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, + ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, + IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl, + IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, + 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, +}; +use windows::core::{HRESULT, IUnknown, Interface, Ref, implement}; + +const RATE: u32 = 48_000; +const FRAME_BYTES: usize = 4; + +/// Activation completes asynchronously; the recording thread polls for it. +#[implement(IActivateAudioInterfaceCompletionHandler)] +struct Activated; + +impl IActivateAudioInterfaceCompletionHandler_Impl for Activated_Impl { + fn ActivateCompleted( + &self, + _: Ref<IActivateAudioInterfaceAsyncOperation>, + ) -> windows::core::Result<()> { + Ok(()) + } +} + +/// Names the process to record, in the recorder's environment. +const TARGET: &str = "VICTORY_AUDIO_CAPTURE_OF"; + +/// Starts the recorder if `VICTORY_AUDIO_CAPTURE` names a file. With this +/// module's debug log, also logs once a second what a `Sleep(1)` takes in +/// this process (the title's millisecond waits get the same). +pub fn start() { + if tracing::enabled!(tracing::Level::DEBUG) { + let _ = std::thread::Builder::new() + .name("victory timing probe".into()) + .spawn(|| { + loop { + std::thread::sleep(Duration::from_secs(1)); + let at = Instant::now(); + // SAFETY: plain wait. + unsafe { Sleep(1) }; + let ms = at.elapsed().as_secs_f32() * 1000.0; + tracing::debug!(ms, "Sleep(1) took"); + } + }); + } + if std::env::var_os("VICTORY_AUDIO_CAPTURE").is_some() + && let Err(e) = std::env::current_exe().and_then(|exe| { + std::process::Command::new(exe) + .env(TARGET, std::process::id().to_string()) + .spawn() + }) + { + tracing::warn!("audio capture not started: {e}"); + } +} + +/// In the recorder (a child started by [`start`]): records until the +/// target exits and returns true; false in any other process. +pub fn child() -> bool { + let (Some(pid), Some(path)) = ( + std::env::var(TARGET).ok().and_then(|p| p.parse().ok()), + std::env::var_os("VICTORY_AUDIO_CAPTURE"), + ) else { + return false; + }; + if let Err(e) = record(pid, Path::new(&path)) { + tracing::warn!("audio capture stopped: {e}"); + } + true +} + +fn header(frames: u64) -> [u8; 44] { + let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36); + let mut h = [0u8; 44]; + let fields: [(&[u8], usize); 11] = [ + (b"RIFF", 0), + (&(36 + data).to_le_bytes(), 4), + (b"WAVEfmt ", 8), + (&16u32.to_le_bytes(), 16), + (&1u16.to_le_bytes(), 20), + (&2u16.to_le_bytes(), 22), + (&RATE.to_le_bytes(), 24), + (&(RATE * FRAME_BYTES as u32).to_le_bytes(), 28), + (&(FRAME_BYTES as u16).to_le_bytes(), 32), + (&16u16.to_le_bytes(), 34), + (b"data", 36), + ]; + for (bytes, at) in fields { + h[at..at + bytes.len()].copy_from_slice(bytes); + } + h[40..].copy_from_slice(&data.to_le_bytes()); + h +} + +fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> { + // SAFETY: COM calls with parameters built here; buffers are used only + // between `GetBuffer` and `ReleaseBuffer`. + unsafe { + CoInitializeEx(None, COINIT_MULTITHREADED).ok()?; + let target = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?; + let params = AUDIOCLIENT_ACTIVATION_PARAMS { + ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, + Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 { + ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS { + TargetProcessId: pid, + ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, + }, + }, + }; + /// A `PROPVARIANT` holding a blob (`VT_BLOB`). + #[repr(C)] + struct Blob { + vt: u16, + reserved: [u16; 3], + size: u32, + data: *const AUDIOCLIENT_ACTIVATION_PARAMS, + } + let blob = Blob { + vt: 0x41, + reserved: [0; 3], + size: size_of_val(¶ms) as u32, + data: ¶ms, + }; + let handler: IActivateAudioInterfaceCompletionHandler = Activated.into(); + let operation = ActivateAudioInterfaceAsync( + VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, + &IAudioClient::IID, + Some((&raw const blob).cast()), + &handler, + )?; + let client = loop { + let (mut hr, mut client) = (HRESULT(0), None::<IUnknown>); + // Fails (`E_ILLEGAL_METHOD_CALL`) until activation completes. + if operation.GetActivateResult(&mut hr, &mut client).is_ok() { + hr.ok()?; + break client.ok_or("no audio client")?.cast::<IAudioClient>()?; + } + std::thread::sleep(Duration::from_millis(10)); + }; + let format = WAVEFORMATEX { + wFormatTag: WAVE_FORMAT_PCM as u16, + nChannels: 2, + nSamplesPerSec: RATE, + nAvgBytesPerSec: RATE * FRAME_BYTES as u32, + nBlockAlign: FRAME_BYTES as u16, + wBitsPerSample: 16, + cbSize: 0, + }; + client.Initialize( + AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, + 10_000_000, + 0, + &format, + None, + )?; + let capture: IAudioCaptureClient = client.GetService()?; + let mut file = File::create(path)?; + file.write_all(&header(0))?; + client.Start()?; + tracing::info!(path = %path.display(), "recording the title's audio"); + + let (mut written, mut first) = (0u64, None); + let mut patched = Instant::now(); + loop { + std::thread::sleep(Duration::from_millis(10)); + let ended = WaitForSingleObject(target, 0) == WAIT_OBJECT_0; + while capture.GetNextPacketSize()? > 0 { + let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0); + capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?; + // Where this packet belongs, from its time stamp (100 ns). + let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000; + if at > written + u64::from(RATE / 500) { + tracing::debug!( + ms = (at - written) * 1000 / u64::from(RATE), + "audio capture: nothing played" + ); + let silence = vec![0u8; (at - written) as usize * FRAME_BYTES]; + file.write_all(&silence)?; + written = at; + } + let bytes = frames as usize * FRAME_BYTES; + if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 { + file.write_all(&vec![0u8; bytes])?; + } else { + file.write_all(std::slice::from_raw_parts(data, bytes))?; + } + if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 { + tracing::debug!("audio capture: discontinuity"); + } + written += u64::from(frames); + capture.ReleaseBuffer(frames)?; + } + if ended || patched.elapsed() >= Duration::from_secs(1) { + // Valid sizes at any time: runs end by being killed. + file.seek(SeekFrom::Start(0))?; + file.write_all(&header(written))?; + file.seek(SeekFrom::End(0))?; + patched = Instant::now(); + } + if ended { + return Ok(()); + } + } + } +} diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs new file mode 100644 index 000000000..23bbccf5c --- /dev/null +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -0,0 +1,108 @@ +//! `d3d12_xs.dll`: virtual memory setup, device creation, root signature +//! serialization. The device and everything it creates live in +//! `victory-gpu`. + +use std::ffi::c_void; + +use victory_gpu::device; +use victory_gpu::object::{HRESULT, Iid, Object}; + +use crate::{HleExport, HleModule}; + +/// Device creation; first hands the device the title's general allocator +/// (`XMemAlloc`, which honours the title's hooks) for resource memory. +extern "system" fn create_device( + adapter: *const c_void, + parameters: *const u32, + 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::on_failure(host_gpu_failed); + device::create(adapter, parameters, iid, out) +} + +/// A host GPU failure ends the run like a crash: reported to the crash log, +/// then the process ends as the console ends a title. +#[cfg(windows)] +fn host_gpu_failed(what: &str) -> ! { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + victory_loader::log_crash(&format!("VIctory: host GPU failure: {what}")); + const DXGI_ERROR_DEVICE_REMOVED: u32 = 0x887A_0005; + // SAFETY: ends our own process. + unsafe { TerminateProcess(GetCurrentProcess(), DXGI_ERROR_DEVICE_REMOVED) }; + unreachable!("the process has ended") +} + +/// Keeps the host's translations of the title's shaders in `dir` (a +/// folder of the cache) across runs, and its compiled pipelines beside it +/// (`pipelines`). +pub fn use_shader_cache(dir: std::path::PathBuf) { + #[cfg(windows)] + { + victory_gpu::pipeline::use_pipeline_cache(dir.with_file_name("pipelines")); + victory_gpu::shader_cache::use_shader_cache(dir); + } + #[cfg(not(windows))] + let _ = dir; +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "d3d12x", + dlls: &["d3d12_xs.dll"], + exports: vec![ + HleExport { + name: "D3D12ConfigureVirtualMemoryX", + address: device::configure_virtual_memory as *const () as usize, + }, + HleExport { + name: "D3D12XboxCreateDevice", + address: create_device as *const () as usize, + }, + HleExport { + name: "D3D12SerializeRootSignature", + address: victory_gpu::root::serialize as *const () as usize, + }, + HleExport { + name: "D3D12SerializeVersionedRootSignature", + address: victory_gpu::root::serialize_versioned as *const () as usize, + }, + // The AMD upscaler's (Series S). + HleExport { + name: "D3D12CreateRootSignatureDeserializer", + address: victory_gpu::root::create_deserializer as *const () as usize, + }, + // A data import: the title reads the id at this address. + HleExport { + name: "IID_ID3D12Device", + address: (&raw const device::IID) as usize, + }, + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{HleResolver, HostPolicy}; + use victory_loader::ImportResolver; + use victory_loader::Resolution; + use victory_pe::ImportSymbol; + + #[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) else { + panic!("not bound"); + }; + // SAFETY: the address is our static id. + assert_eq!(unsafe { *(address as *const [u8; 16]) }, device::IID); + } +} diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs new file mode 100644 index 000000000..41f9cbd11 --- /dev/null +++ b/crates/victory-hle/src/modules/display.rs @@ -0,0 +1,195 @@ +//! The display and what the system shell does for a title: HDR mode, screen +//! timeout deferrals, launching URIs, screenshots. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, put, text, +}; + +/// HDR mode; asked for with this interface id since 2020. +pub const HDR_PROVIDER: Guid = Guid::new( + 0x03f0_fe74, + 0xfdd9, + 0x4e5c, + [0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5], +); +pub const HDR_IID: Guid = Guid::new( + 0x35f0_7670, + 0x706e, + 0x4bfb, + [0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3], +); +/// Launching URIs and screen timeout deferrals; the interface id is the +/// provider's. +pub const SHELL: Guid = Guid::new( + 0x1b33_9674, + 0x328d, + 0x4283, + [0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39], +); +/// Screenshots and clips. +pub const CAPTURE_PROVIDER: Guid = Guid::new( + 0xa4f1_aee2, + 0x4bf1, + 0x4485, + [0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27], +); +/// As Grand Theft Auto VI (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, + 0xb4e3, + 0x406c, + [0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e], +); + +pub static HDR_OBJECT: Object = Object::new("hdr", &HDR_VTABLE); +pub static SHELL_OBJECT: Object = Object::new("shell", &SHELL_VTABLE); +pub static CAPTURE_OBJECT: Object = Object::new("capture", &CAPTURE_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (HDR_PROVIDER, HDR_IID, &HDR_OBJECT), + (SHELL, SHELL, &SHELL_OBJECT), + (CAPTURE_PROVIDER, CAPTURE_IID_2026, &CAPTURE_OBJECT), +]; + +type This = *const Object; + +/// 2: disabled. We present in SDR, so the title must render SDR. +// shortcut: HDR output is not done (see the presentation items in +// `TODO.md`); report enabled, with the host display's luminance, once the +// swap chain can present HDR. +extern "system" fn try_enable_hdr(_: This, preference: u32, _info: *mut c_void) -> u32 { + tracing::info!(preference, "HDR mode: disabled (SDR presentation)"); + 2 +} + +/// Nothing launches URIs for the title: no store, browser or console app +/// exists here, and the console's are online services. +extern "system" fn launch_uri(_: This, _user: *const c_void, uri: *const c_char) -> HRESULT { + tracing::info!(uri = text(uri).unwrap_or_default(), "URI not launched"); + NOT_SUPPORTED +} + +/// A deferral keeps the host display on, as on the console, through a +/// power request; the handle is that request. +#[cfg(windows)] +extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { + use windows_sys::Win32::System::Power::{ + PowerCreateRequest, PowerRequestDisplayRequired, PowerSetRequest, + }; + use windows_sys::Win32::System::Threading::{ + POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, + }; + if out.is_null() { + return super::xasync::E_INVALIDARG; + } + let mut reason: Vec<u16> = "Title display deferral\0".encode_utf16().collect(); + let mut context = REASON_CONTEXT { + Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING, + ..Default::default() + }; + context.Reason.SimpleReasonString = reason.as_mut_ptr(); + // SAFETY: a valid context; the string is copied by the call. + let request = unsafe { PowerCreateRequest(&context) }; + if request as isize == -1 { + return last_error(); + } + // SAFETY: the request we just created. + if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 { + let hr = last_error(); + // SAFETY: as above; not handed out. + unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; + return hr; + } + put(out, request) +} + +#[cfg(windows)] +extern "system" fn close_deferral(_: This, handle: *mut c_void) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired}; + if !handle.is_null() { + // SAFETY: a request from `acquire_deferral`. + unsafe { + PowerClearRequest(handle, PowerRequestDisplayRequired); + CloseHandle(handle); + } + } +} + +#[cfg(windows)] +fn last_error() -> HRESULT { + // SAFETY: no preconditions. + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + (0x8007_0000 | (code & 0xffff)) as i32 +} + +// shortcut: screenshots fail as if capture were unavailable. Taking one needs +// a hook in the GPU side: the last presented frame read back as BGRA8 (size, +// row pitch, bytes) on request, e.g. `victory_gpu::last_frame() -> +// Option<Frame>`, copied from the back buffer after `PresentX`. +extern "system" fn take_screenshot(_: This, _user: *const c_void, _result: *mut c_void) -> HRESULT { + tracing::info!("screenshot not taken"); + NOT_SUPPORTED +} + +static HDR_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), + try_enable_hdr as *const (), // 0x20 +]); + +#[cfg(windows)] +static SHELL_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + launch_uri as *const (), // 0x18 + acquire_deferral as *const (), // 0x20 + close_deferral as *const (), // 0x28 +]); +#[cfg(not(windows))] +static SHELL_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + launch_uri as *const (), +]); + +static CAPTURE_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 diagnostic screenshot + missing::<4> as *const (), // 0x20 diagnostic clip + take_screenshot as *const (), // 0x28 +]); + +#[cfg(all(test, windows))] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + #[test] + fn sdr_and_display_deferrals() { + type Hdr = extern "system" fn(This, u32, *mut c_void) -> u32; + assert_eq!( + method::<Hdr>(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, std::ptr::null_mut()), + 2 + ); + type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; + type Close = extern "system" fn(This, *mut c_void); + let mut handle = std::ptr::null_mut(); + assert_eq!( + method::<Acquire>(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, &mut handle), + S_OK + ); + assert!(!handle.is_null()); + method::<Close>(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle); + } +} diff --git a/crates/victory-hle/src/modules/dsp.rs b/crates/victory-hle/src/modules/dsp.rs new file mode 100644 index 000000000..87c456aed --- /dev/null +++ b/crates/victory-hle/src/modules/dsp.rs @@ -0,0 +1,314 @@ +//! The console's audio DSP (`chad.dll`): streams that convolve blocks of +//! float samples with an impulse response (reverb), or run other block +//! transforms, on a coprocessor. +//! +//! A title connects once with a memory block for the DSP, activates +//! streams, and submits one command per block (gains, an input and an +//! output buffer). Activation hands back a status block whose second word is +//! the ticket of the last completed command and whose fourth is its result; +//! the title checks it one block later and treats a late command as an +//! overrun. Commands complete when submitted here. +//! +//! The transforms themselves are not computed: the hardware takes impulse +//! responses already in its own partitioned frequency-domain layout, which +//! is not known. Outputs are silence, so reverb returns are dry. +// shortcut: no convolution or block transform; outputs are zeros. Needs the +// coprocessor's impulse response and spectrum layouts to do better. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::Mutex; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; + +const CONVOLUTION: u32 = 1; +/// Option bits that need a stereo stream, and one convolution refuses. +const STEREO_OPTIONS: u32 = 2 | 8; +const NOT_FOR_CONVOLUTION: u32 = 4; + +pub struct Dsp { + max_streams: u32, + active: Mutex<u32>, +} + +/// What activation describes. +#[repr(C, packed)] +pub struct StreamDesc { + kind: u32, + options: u32, + frames: u32, + channels: u32, + ir_floats: u32, + ir: *const f32, +} + +/// The status block a stream's owner polls. +#[repr(C)] +pub struct Status { + submitted: u32, + completed: u32, + reserved: u32, + result: HRESULT, +} + +pub struct Stream { + dsp: *mut Dsp, + frames: u32, + channels: u32, + status: Box<Status>, +} + +/// One block of work. +#[repr(C)] +pub struct Command { + gains: [f32; 2], + input: *const f32, + output: *mut f32, + reserved: u64, +} + +pub extern "system" fn XDspConnectWithMaximumStreamLimit( + base: *mut c_void, + base_length: u32, + ir_seconds: u32, + max_streams: u32, + max_channels: u32, + out: *mut *mut Dsp, +) -> HRESULT { + if base.is_null() + || !(0x1_0000..=0x1F40_0000).contains(&base_length) + || ir_seconds > 0x80 + || max_streams > 0x100 + || max_channels > 2 + { + return E_INVALIDARG; + } + if out.is_null() { + return E_POINTER; + } + tracing::info!( + base_length, + ir_seconds, + max_streams, + max_channels, + "audio DSP connected" + ); + let dsp = Box::new(Dsp { + max_streams, + active: Mutex::new(0), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(dsp)) }; + S_OK +} + +pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT { + if dsp.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected + // once, after its streams. + drop(unsafe { Box::from_raw(dsp) }); + S_OK +} + +fn valid(desc: &StreamDesc) -> bool { + let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); + let shape = if kind == CONVOLUTION { + (1..=2).contains(&channels) + && matches!(frames, 0x200 | 0x400) + && options & NOT_FOR_CONVOLUTION == 0 + } else { + channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800) + }; + shape && (options & STEREO_OPTIONS == 0 || channels == 2) +} + +pub extern "system" fn XDspActivate( + dsp: *mut Dsp, + desc: *const StreamDesc, + status: *mut *const Status, + stream: *mut *mut Stream, +) -> HRESULT { + if status.is_null() || stream.is_null() { + return E_POINTER; + } + if dsp.is_null() || desc.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes its description. + let desc = unsafe { &*desc }; + if !valid(desc) { + return E_INVALIDARG; + } + let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); + tracing::debug!( + kind, + options, + frames, + channels, + "audio DSP stream activated" + ); + { + // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`. + let dsp = unsafe { &*dsp }; + let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); + if *active >= dsp.max_streams { + return E_OUTOFMEMORY; + } + *active += 1; + } + let new = Box::new(Stream { + dsp, + frames: desc.frames, + channels: desc.channels, + status: Box::new(Status { + submitted: 0, + completed: 0, + reserved: 0, + result: S_OK, + }), + }); + // SAFETY: checked non-null. + unsafe { + status.write(&*new.status); + stream.write(Box::into_raw(new)); + } + S_OK +} + +pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT { + if stream.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XDspActivate`; deactivated once. + let stream = unsafe { Box::from_raw(stream) }; + // SAFETY: the connection outlives its streams. + let dsp = unsafe { &*stream.dsp }; + *dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1; + S_OK +} + +/// Completes the command at once: its output block is silence. +pub extern "system" fn XDspSubmitCommand( + stream: *mut Stream, + command: *const Command, + ticket: *mut u32, +) -> HRESULT { + if stream.is_null() || command.is_null() { + return E_INVALIDARG; + } + // SAFETY: a stream from `XDspActivate`, the title's command. + let (stream, command) = unsafe { (&mut *stream, &*command) }; + if !command.output.is_null() { + let samples = (stream.frames * stream.channels) as usize; + // SAFETY: the title's output buffer holds one block of the stream. + unsafe { std::ptr::write_bytes(command.output, 0, samples) }; + } + let status = &mut *stream.status; + let next = status.submitted.wrapping_add(1); + // SAFETY: the status block is read by title code on other threads. + unsafe { + std::ptr::write_volatile(&mut status.submitted, next); + std::ptr::write_volatile(&mut status.result, S_OK); + std::ptr::write_volatile(&mut status.completed, next); + } + if !ticket.is_null() { + // SAFETY: optional out parameter. + unsafe { ticket.write(next) }; + } + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "dsp", + dlls: &["chad.dll"], + exports: vec![ + hle_export!(XDspConnectWithMaximumStreamLimit), + hle_export!(XDspDisconnect), + hle_export!(XDspActivate), + hle_export!(XDspDeactivate), + hle_export!(XDspSubmitCommand), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn convolution_stream_as_the_title_drives_it() { + let mut base = vec![0u8; 0x10_0000]; + let mut dsp = std::ptr::null_mut(); + assert_eq!( + XDspConnectWithMaximumStreamLimit( + base.as_mut_ptr().cast(), + 0x10_0000, + 24, + 0x80, + 1, + &mut dsp + ), + S_OK + ); + let ir = vec![0f32; 0x800]; + // Stereo convolution with option 2, as the title asks for. + let desc = StreamDesc { + kind: CONVOLUTION, + options: 2, + frames: 0x400, + channels: 2, + ir_floats: 0x800, + ir: ir.as_ptr(), + }; + let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); + assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); + let mut output = vec![1f32; 0x800]; + let input = vec![0.5f32; 0x800]; + let command = Command { + gains: [1.0, 1.0], + input: input.as_ptr(), + output: output.as_mut_ptr(), + reserved: 0, + }; + let mut ticket = 0; + assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK); + // SAFETY: the stream's status block. + let (completed, result) = unsafe { ((*status).completed, (*status).result) }; + assert_eq!((completed, result), (ticket, S_OK)); + assert!(output.iter().all(|&s| s == 0.0)); + assert_eq!(XDspDeactivate(stream), S_OK); + + // Mono streams refuse stereo options; transforms are mono only. + let bad = StreamDesc { + channels: 1, + ..desc + }; + assert_eq!( + XDspActivate(dsp, &bad, &mut status, &mut stream), + E_INVALIDARG + ); + let transform = StreamDesc { + kind: 2, + options: 0, + channels: 1, + ir_floats: 0, + ir: std::ptr::null(), + ..desc + }; + assert_eq!( + XDspActivate(dsp, &transform, &mut status, &mut stream), + S_OK + ); + assert_eq!(XDspDeactivate(stream), S_OK); + assert_eq!(XDspDisconnect(dsp), S_OK); + } +} diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs new file mode 100644 index 000000000..324db9e05 --- /dev/null +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -0,0 +1,1555 @@ +//! 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 +//! sites. Slots nobody has needed yet log their offset. +//! +//! Submitted requests of every queue run on one pool of workers, as the +//! console's hardware runs them: in parallel, started in queue order, +//! queues served by weighted round robin over their priorities (about 10x +//! per level, counted in bytes), with at most the staging buffer's worth of +//! compressed source in flight. Each request reads its source (a file or +//! memory), inflates zlib data and/or unpacks BCPack data, and writes the +//! destination (an address, or physical pages). Completion is what stays +//! in order: a status entry is written once every request enqueued before +//! it on its queue has finished, with the first failure (in queue order) +//! since the previous status entry, or success. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::ffi::{CStr, c_char, c_void}; +use std::os::windows::fs::FileExt; +use std::os::windows::io::FromRawHandle; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +use victory_formats::bcpack::{self, Tables}; + +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. +const FACTORY: Guid = Guid::new( + 0x6295_9d11, + 0xd45f, + 0x4884, + [0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae], +); +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// `HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)`: the source ends early. +const END_OF_FILE: HRESULT = 0x8007_0026_u32 as i32; +/// `HRESULT_FROM_WIN32(ERROR_INVALID_DATA)`: a bad compressed stream. +const INVALID_DATA: HRESULT = 0x8007_000D_u32 as i32; + +type Out = *mut *mut c_void; + +static FACTORY_OBJECT: Object = Object::new("dstorage factory", &FACTORY_VTABLE); + +pub extern "system" fn DStorageGetFactory(iid: *const Guid, out: Out) -> HRESULT { + // SAFETY: the title passes a GUID (null tolerated). + match unsafe { iid.as_ref() } { + Some(&iid) if iid == FACTORY => { + put(out, std::ptr::from_ref(&FACTORY_OBJECT).cast_mut().cast()) + } + iid => { + tracing::warn!(iid = ?iid.map(Guid::to_string), "DStorageGetFactory: unknown interface"); + E_NOINTERFACE + } + } +} + +/// One of our objects with state: the runtime's object header (method +/// table first), a reference count, then `T`. +#[repr(C)] +struct Instance<T> { + base: Object, + refs: AtomicU32, + state: T, +} + +impl<T> Instance<T> { + fn create(base: Object, state: T) -> *mut c_void { + Box::into_raw(Box::new(Instance { + base, + refs: AtomicU32::new(1), + state, + })) + .cast() + } +} + +extern "system" fn add_ref_instance<T>(this: *const Instance<T>) -> u32 { + // SAFETY: an instance we created and the title still holds. + unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +extern "system" fn release<T>(this: *mut Instance<T>) -> u32 { + // SAFETY: as above. + let left = unsafe { &*this }.refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: the last reference; created by `Instance::create`. + drop(unsafe { Box::from_raw(this) }); + } + left +} + +fn iid_text(iid: *const Guid) -> String { + // SAFETY: the title passes a GUID (null tolerated). + unsafe { iid.as_ref() }.map_or_else(|| "null".into(), Guid::to_string) +} + +/// `HRESULT_FROM_WIN32` of a host error. +fn from_win32(error: &std::io::Error) -> HRESULT { + error + .raw_os_error() + .map_or(E_INVALIDARG, |e| (0x8007_0000 | (e as u32 & 0xffff)) as i32) +} + +// The factory. + +type Factory = *const Object; + +/// Opens `path` for reading; the file object owns the handle. +extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out: Out) -> HRESULT { + const GENERIC_READ: u32 = 0x8000_0000; + const FILE_SHARE_READ: u32 = 1; + const OPEN_EXISTING: u32 = 3; + if path.is_null() { + return E_INVALIDARG; + } + // Goes through `files`, so paths on our virtual drives work too. + let handle = super::files::CreateFileW( + path, + GENERIC_READ, + FILE_SHARE_READ, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + // SAFETY: the title passes a NUL-terminated path. + let name = unsafe { + let len = (0..).take_while(|&i| *path.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(path, len)) + }; + if handle as isize == -1 { + let error = std::io::Error::last_os_error(); + tracing::warn!(path = name, %error, "dstorage: opening a file failed"); + return from_win32(&error); + } + 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 }); + put(out, file) +} + +/// `(capacity, name, iid, out)`. +extern "system" fn create_status_array( + _: Factory, + capacity: u32, + name: *const c_char, + iid: *const Guid, + out: Out, +) -> HRESULT { + tracing::info!( + capacity, + name = text(name), + iid = iid_text(iid), + "dstorage: status array" + ); + let entries = (0..capacity).map(|_| AtomicI32::new(S_OK)).collect(); + let array = Instance::create( + Object::new("dstorage status array", &STATUS_VTABLE), + StatusArray { entries }, + ); + put(out, array) +} + +/// The queue's description: as in 2020 (source type, capacity, priority, +/// name), plus a field Grand Theft Auto VI sets to 1. +#[repr(C)] +struct QueueDesc { + source_type: u64, + capacity: u16, + priority: i8, + name: *const c_char, + unknown: u64, +} + +extern "system" fn create_queue( + _: Factory, + desc: *const QueueDesc, + iid: *const Guid, + out: Out, +) -> HRESULT { + // SAFETY: the title passes its description (null tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + let name = text(desc.name); + tracing::info!( + source = desc.source_type, + capacity = desc.capacity, + priority = desc.priority, + name, + unknown = desc.unknown, + iid = iid_text(iid), + "dstorage: queue" + ); + let Some(scheduler) = scheduler() else { + return E_OUTOFMEMORY; + }; + let mut lanes = scheduler.lock(); + let id = lanes.next_id; + lanes.next_id += 1; + let lane = Lane::new(desc.priority, desc.capacity); + lanes.lanes.insert(id, lane); + drop(lanes); + put( + out, + Instance::create(Object::new("dstorage queue", &QUEUE_VTABLE), Queue { id }), + ) +} + +/// Grand Theft Auto VI 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() { + scheduler.lock().staging = u64::from(size); + } + S_OK +} + +fn text(name: *const c_char) -> String { + if name.is_null() { + return String::new(); + } + // SAFETY: a NUL-terminated name from the title. + unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned() +} + +static FACTORY_VTABLE: Methods<16> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 (2020: queue creation) + open_file as *const (), // 0x20 + create_status_array as *const (), // 0x28 + missing::<6> as *const (), // 0x30 (2020: CPU affinity) + missing::<7> as *const (), // 0x38 (2020: debug flags) + set_staging_buffer_size as *const (), // 0x40 + missing::<9> as *const (), + create_queue as *const (), // 0x50 + missing::<11> as *const (), + missing::<12> as *const (), + missing::<13> as *const (), + missing::<14> as *const (), + missing::<15> as *const (), +]); + +// Files. + +struct File { + file: std::fs::File, +} + +static FILE_VTABLE: Methods<8> = Methods([ + missing::<0> as *const (), + add_ref_instance::<File> as *const (), + release::<File> as *const (), + missing::<3> as *const (), + missing::<4> as *const (), + missing::<5> as *const (), + missing::<6> as *const (), + missing::<7> as *const (), +]); + +// Status arrays. + +struct StatusArray { + entries: Box<[AtomicI32]>, +} + +type Array = *mut Instance<StatusArray>; + +/// The result of the requests before entry `index`: pending, the first +/// failure, or success. +extern "system" fn status_result(this: Array, index: u32) -> HRESULT { + // SAFETY: an array we created and the title still holds. + let entries = &unsafe { &*this }.state.entries; + entries + .get(index as usize) + .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire)) +} + +/// Grand Theft Auto VI 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 +} + +static STATUS_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref_instance::<StatusArray> as *const (), + release::<StatusArray> as *const (), + is_complete as *const (), // 0x18 + status_result as *const (), // 0x20 +]); + +// Queues. + +/// A queue object: its lane in the scheduler. +struct Queue { + id: u64, +} + +impl Drop for Queue { + fn drop(&mut self) { + close_lane(self.id); + } +} + +type QueueRef = *const Instance<Queue>; + +/// Every queue's requests, run by a pool of workers. +struct Scheduler { + lanes: Mutex<Lanes>, + /// Requests to start, or staging space freed. + work: Condvar, + /// A request finished (for full queues and `close`). + finished: Condvar, +} + +/// Priority weights per class (low, normal, high and real-time), as the +/// console's: about 10x per level, counted against request sizes. +const COST: [u64; 3] = [100, 10, 1]; +/// The console's default staging buffer. +const STAGING: u64 = 32 << 20; + +struct Lanes { + lanes: HashMap<u64, Lane>, + next_id: u64, + /// Submission order over all queues. + next_seq: u64, + /// Bytes of staging held by running requests, and the limit. + staged: u64, + staging: u64, + /// A start waited for staging space since the last finish. + starved: bool, + /// Weighted round robin: each class's virtual time (bytes × cost), and + /// the time of the last start; within a class, the lane clock of the + /// last start. + clock: [u64; 3], + now: u64, + lane_now: [u64; 3], + /// Since the last debug summary: requests, bytes written, time spent + /// running them. + done: (u64, u64, std::time::Duration), + refused: u64, + /// BCPack bytes written and time spent on them. + bcpack: (u64, std::time::Duration), + since: Option<std::time::Instant>, +} + +/// A queue's requests in the scheduler. +struct Lane { + class: usize, + capacity: usize, + /// Bytes started, for round robin among the lanes of a class. + clock: u64, + /// Enqueued, not yet submitted. + unsubmitted: Vec<Command>, + /// Submitted, by sequence number: reads not started, status entries + /// not written, reads running, and failures not yet reported. + reads: VecDeque<(u64, Request)>, + statuses: VecDeque<(u64, Status)>, + running: BTreeSet<u64>, + failures: BTreeMap<u64, HRESULT>, + closed: bool, +} + +// SAFETY: requests point into title memory and our own objects, which stay +// valid until the title has seen them complete; status arrays count their +// references atomically. +unsafe impl Send for Lane {} + +/// A read a worker runs. +struct Job { + lane: u64, + seq: u64, + request: Request, + staging: u64, +} + +// SAFETY: as for `Lane`. +unsafe impl Send for Job {} + +/// The scheduler, with its workers started on first use; `None` if not +/// even one worker could start. +fn scheduler() -> Option<&'static Scheduler> { + static SCHEDULER: OnceLock<Option<Scheduler>> = OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let scheduler = SCHEDULER + .get_or_init(|| { + Some(Scheduler { + lanes: Mutex::new(Lanes { + lanes: HashMap::new(), + next_id: 0, + next_seq: 0, + staged: 0, + staging: STAGING, + starved: false, + clock: [0; 3], + now: 0, + lane_now: [0; 3], + done: Default::default(), + refused: 0, + bcpack: Default::default(), + since: None, + }), + work: Condvar::new(), + finished: Condvar::new(), + }) + }) + .as_ref()?; + STARTED.call_once(|| { + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + let started = (0..workers) + .filter(|i| { + std::thread::Builder::new() + .name(format!("dstorage {i}")) + .spawn(|| work(scheduler)) + .is_ok() + }) + .count(); + tracing::info!(workers = started, "dstorage: workers"); + }); + Some(scheduler) +} + +impl Scheduler { + fn lock(&self) -> MutexGuard<'_, Lanes> { + self.lanes.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// 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()); + continue; + }; + drop(lanes); + let started = std::time::Instant::now(); + let result = execute(&job.request); + lanes = scheduler.lock(); + lanes.finish(&job, result); + lanes.count(&job, started); + if std::mem::take(&mut lanes.starved) { + scheduler.work.notify_all(); + } + scheduler.finished.notify_all(); + } +} + +impl Lanes { + /// Counts a finished request; every 5 s a debug line sums them up. + fn count(&mut self, job: &Job, started: std::time::Instant) { + let (requests, bytes, busy) = &mut self.done; + *requests += 1; + *bytes += u64::from(job.request.destination_size); + *busy += started.elapsed(); + if job.request.options & BCPACK != 0 { + self.bcpack.0 += u64::from(job.request.destination_size); + self.bcpack.1 += started.elapsed(); + } + let since = *self.since.get_or_insert(started); + let elapsed = since.elapsed(); + if elapsed.as_secs() >= 5 { + let waiting: usize = self.lanes.values().map(|l| l.reads.len()).sum(); + let reading = READING.swap(0, Ordering::Relaxed) as f64 / 1e9; + tracing::debug!( + requests = *requests, + mb_per_s = format_args!("{:.1}", *bytes as f64 / elapsed.as_secs_f64() / 1e6), + busy_workers = format_args!("{:.2}", busy.as_secs_f64() / elapsed.as_secs_f64()), + 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()), + waiting, + "dstorage: last {:.1} s", + elapsed.as_secs_f64() + ); + self.done = Default::default(); + self.bcpack = Default::default(); + self.since = None; + } + } + + /// Starts the next read of the class with the least virtual time, from + /// its lane that has started the fewest bytes, if the staging buffer + /// has room for it (or nothing else holds any). + fn start(&mut self) -> Option<Job> { + let busy = || self.lanes.iter().filter(|(_, l)| !l.reads.is_empty()); + let (_, class) = busy().map(|(_, l)| (self.clock[l.class], l.class)).min()?; + let (_, _, id) = busy() + .filter(|(_, l)| l.class == class) + .filter_map(|(&id, l)| Some((l.clock, l.reads.front()?.0, id))) + .min()?; + let lane = self.lanes.get_mut(&id)?; + let &(seq, request) = lane.reads.front()?; + let staging = staging_bytes(&request); + if self.staged > 0 && self.staged + staging > self.staging { + self.starved = true; + self.refused += 1; + return None; + } + lane.reads.pop_front(); + lane.running.insert(seq); + self.staged += staging; + let size = u64::from(request.destination_size.max(request.source_size)).max(1); + self.now = self.clock[class]; + self.clock[class] += size * COST[class]; + self.lane_now[class] = lane.clock; + lane.clock += size; + Some(Job { + lane: id, + seq, + request, + staging, + }) + } + + fn finish(&mut self, job: &Job, result: Result<(), HRESULT>) { + self.staged -= job.staging; + if let Some(lane) = self.lanes.get_mut(&job.lane) { + lane.running.remove(&job.seq); + if let Err(hr) = result { + lane.failures.insert(job.seq, hr); + } + lane.flush(); + } + } + + /// Moves a queue's enqueued commands to the workers. + fn submit(&mut self, id: u64) { + let Some(class) = self.lanes.get(&id).map(|l| l.class) else { + return; + }; + // A class that had nothing waiting starts from now, not from the + // credit it left behind. + if !self + .lanes + .values() + .any(|l| l.class == class && !l.reads.is_empty()) + { + self.clock[class] = self.clock[class].max(self.now); + } + let Some(lane) = self.lanes.get_mut(&id) else { + return; + }; + if lane.reads.is_empty() { + lane.clock = lane.clock.max(self.lane_now[class]); + } + for command in std::mem::take(&mut lane.unsubmitted) { + let seq = self.next_seq; + self.next_seq += 1; + match command { + Command::Read(request) => lane.reads.push_back((seq, request)), + Command::Status(status) => lane.statuses.push_back((seq, status)), + } + } + lane.flush(); + } +} + +impl Lane { + fn new(priority: i8, capacity: u16) -> Lane { + Lane { + class: priority.clamp(-1, 1).wrapping_add(1) as usize, + capacity: usize::from(capacity), + clock: 0, + unsubmitted: Vec::new(), + reads: VecDeque::new(), + statuses: VecDeque::new(), + running: BTreeSet::new(), + failures: BTreeMap::new(), + closed: false, + } + } + + /// Requests and status entries held, submitted or not. + fn entries(&self) -> usize { + self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + } + + /// Writes the status entries whose earlier reads have all finished. + 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) { + return; + } + let Some((_, status)) = self.statuses.pop_front() else { + return; + }; + let later = self.failures.split_off(&seq); + let first = std::mem::replace(&mut self.failures, later) + .into_values() + .next(); + status + .entry() + .store(first.unwrap_or(S_OK), Ordering::Release); + } + } +} + +/// Staging bytes a request holds while it runs: what it buffers between +/// the file and the destination. Raw reads go straight to their +/// destination, memory sources need none (as on the console). +fn staging_bytes(request: &Request) -> u64 { + let buffered = request.options & (ZLIB | BCPACK | PAGE_DESTINATION) != 0; + if buffered && request.options & MEMORY_SOURCE == 0 { + u64::from(request.source_size) + } else { + 0 + } +} + +/// Ends a queue: what was not started is dropped, and this waits for the +/// reads already running (they write title memory). +fn close_lane(id: u64) { + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + let Some(lane) = lanes.lanes.get_mut(&id) else { + return; + }; + lane.closed = true; + lane.unsubmitted.clear(); + lane.reads.clear(); + lane.statuses.clear(); // releases their arrays + while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { + lanes = scheduler + .finished + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); + } + lanes.lanes.remove(&id); + scheduler.finished.notify_all(); +} + +/// A read request as the title builds it, 0x48 bytes. +#[repr(C)] +#[derive(Clone, Copy)] +struct Request { + options: u64, + /// An address, or with `PAGE_DESTINATION` an array of 64 KiB page + /// numbers. + destination: *mut c_void, + /// With `PAGE_DESTINATION`, the low 16 bits are where in the first page + /// the destination starts. + page_offset: u64, + destination_size: u32, + /// Our file object, or with `MEMORY_SOURCE` an address. + source: *const c_void, + offset: u64, + source_size: u32, + /// Compressed size between two decompression stages; unused here. + intermediate_size: u32, + /// Matched by cancellation; Grand Theft Auto VI leaves it 0. + tag: u64, + name: *const c_char, +} + +// Request options. +/// Inflate zlib (RFC 1950) data. +const ZLIB: u64 = 1; +/// Bits 1-4: decode BCPack data of this BC format number (0: none). +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. + +const PAGE: usize = 64 * 1024; + +enum Command { + Read(Request), + Status(Status), +} + + +/// A status entry to write, holding a reference on its array. +struct Status { + array: Array, + index: u32, +} + +impl Drop for Status { + fn drop(&mut self) { + release(self.array); + } +} + +impl Status { + fn entry(&self) -> &AtomicI32 { + // SAFETY: we hold a reference; the index was checked when enqueued. + &unsafe { &*self.array }.state.entries[self.index as usize] + } +} + +extern "system" fn enqueue_request(this: QueueRef, request: *const Request) { + // SAFETY: the title passes its request (null tolerated). + let Some(&request) = (unsafe { request.as_ref() }) else { + return; + }; + queue(this, Command::Read(request)); +} + +extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) { + // SAFETY: the title passes an array we created (null tolerated). + let Some(entries) = (unsafe { array.as_ref() }).map(|a| &a.state.entries) else { + return; + }; + let Some(entry) = entries.get(index as usize) else { + tracing::warn!(index, "dstorage: status entry out of range"); + return; + }; + entry.store(E_PENDING, Ordering::Release); + add_ref_instance(array); + queue(this, Command::Status(Status { array, index })); +} + +/// Adds a command to the queue; blocks while the queue is full, and +/// submits on its own once half of it is enqueued, as the console does. +fn queue(this: QueueRef, command: Command) { + // SAFETY: a queue we created and the title still holds. + let id = unsafe { &*this }.state.id; + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + loop { + let Some(lane) = lanes.lanes.get(&id).filter(|l| !l.closed) else { + return; // closed: dropped (a status releases its array) + }; + // One slot stays free, as the console's count of empty slots says. + if lane.entries() + 1 < lane.capacity.max(2) { + break; + } + lanes = scheduler + .finished + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); + } + let Some(lane) = lanes.lanes.get_mut(&id) else { + return; + }; + lane.unsubmitted.push(command); + if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { + lanes.submit(id); + scheduler.work.notify_all(); + } +} + +extern "system" fn submit(this: QueueRef) { + // SAFETY: as above. + let id = unsafe { &*this }.state.id; + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + tracing::debug!(commands = pending, "dstorage: submit"); + lanes.submit(id); + scheduler.work.notify_all(); +} + +/// 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`. +extern "system" fn close(this: QueueRef) { + // SAFETY: as above. + close_lane(unsafe { &*this }.state.id); +} + +/// Reads, inflates and/or unpacks, and writes one request. +fn execute(request: &Request) -> Result<(), HRESULT> { + let options = request.options; + let fail = |hr: HRESULT, why: &str| { + tracing::warn!( + options = format_args!("{options:#x}"), + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + intermediate_size = request.intermediate_size, + tag = request.tag, + name = text(request.name), + hr = format_args!("{:#010x}", hr as u32), + "dstorage: request failed: {why}" + ); + hr + }; + if options & !(ZLIB | BCPACK | PAGE_DESTINATION | MEMORY_SOURCE) != 0 { + return Err(fail(E_NOTIMPL, "unsupported options")); + } + if request.source.is_null() || request.destination.is_null() { + return Err(fail(E_INVALIDARG, "no source or destination")); + } + let bc = ((options & BCPACK) >> 1) as u8; + let size = request.destination_size as usize; + if options & (ZLIB | BCPACK) == 0 { + if request.source_size > request.destination_size { + return Err(fail(E_INVALIDARG, "source larger than destination")); + } + let size = request.source_size as usize; + return into_destination(request, size, |out| read_into(request, out).map(|()| size)) + .map_err(|hr| fail(hr, "copying")); + } + 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 { + 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 + }; + into_destination(request, size, |out| match tables { + Some(tables) => bcpack::decode(bc, &source, out, tables) + .map(|()| out.len()) + .map_err(|e| fail(INVALID_DATA, &e.to_string())), + None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")), + })?; + tracing::trace!( + options = format_args!("{options:#x}"), + offset = request.offset, + size, + "dstorage: request done" + ); + Ok(()) +} + +/// Inflates a zlib stream into `out`, returning the bytes written. A stream +/// that ends short of `out` passes: the title's chunks fill it exactly, and +/// nothing says that is required. +fn inflate(source: &[u8], out: &mut [u8]) -> Result<usize, HRESULT> { + miniz_oxide::inflate::decompress_slice_iter_to_slice(out, std::iter::once(source), true, false) + .map_err(|status| { + tracing::debug!(?status, "dstorage: zlib stream"); + INVALID_DATA + }) +} + +/// The BCPack format's constant tables, parsed once for the process. If +/// they do not parse every BCPack request fails: one warning, then debug. +fn bcpack_tables() -> Result<&'static Tables, HRESULT> { + static TABLES: OnceLock<Result<Tables, String>> = OnceLock::new(); + static WARNED: AtomicBool = AtomicBool::new(false); + match TABLES.get_or_init(load_bcpack_tables) { + Ok(tables) => Ok(tables), + Err(why) if !WARNED.swap(true, Ordering::Relaxed) => { + tracing::warn!("dstorage: BCPack requests fail: {why} (more at debug)"); + Err(E_NOTIMPL) + } + Err(_) => { + tracing::debug!("dstorage: BCPack request failed: no tables"); + Err(E_NOTIMPL) + } + } +} + +/// The tables VIctory ships with. +#[cfg(not(test))] +fn load_bcpack_tables() -> Result<Tables, String> { + Tables::builtin().map_err(|e| format!("the built-in BCPack tables: {e}")) +} + +/// Tests decode streams made against tables of their own, from this folder. +#[cfg(test)] +static BCPACK_DIR: OnceLock<std::path::PathBuf> = OnceLock::new(); + +#[cfg(test)] +fn use_bcpack_tables(dir: std::path::PathBuf) { + let _ = BCPACK_DIR.set(dir); +} + +#[cfg(test)] +fn load_bcpack_tables() -> Result<Tables, String> { + 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()) +} + +/// A compressed request's source: borrowed from memory, or read from the +/// file. +fn read_source(request: &Request) -> Result<Cow<'static, [u8]>, HRESULT> { + let size = request.source_size as usize; + if request.options & MEMORY_SOURCE != 0 { + // SAFETY: the title's source holds `size` bytes until completion. + let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) }; + return Ok(Cow::Borrowed(bytes)); + } + let mut bytes = vec![0; size]; + read_into(request, &mut bytes)?; + Ok(Cow::Owned(bytes)) +} + +/// Nanoseconds workers spent reading files, for the debug summary. +static READING: AtomicU64 = AtomicU64::new(0); + +/// Fills `out` (the source size) from the request's file or memory. +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()) }); + return Ok(()); + } + // SAFETY: a file object we created; the title keeps it open. + let file = &unsafe { &*request.source.cast::<Instance<File>>() } + .state + .file; + let started = std::time::Instant::now(); + let mut done = 0; + let result = loop { + if done == out.len() { + break Ok(()); + } + match file.seek_read(&mut out[done..], request.offset + done as u64) { + Ok(0) => break Err(END_OF_FILE), + Ok(n) => done += n, + Err(error) => break Err(from_win32(&error)), + } + }; + READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + result +} + +/// Runs `fill` on the destination's first `len` bytes; `fill` returns how +/// many it produced. GPU-visible destinations are host memory like the +/// rest (GPU address = CPU address), so an address is written in place; +/// physical pages are too when they are consecutive pages of one +/// allocation, and otherwise go through a buffer. +fn into_destination( + request: &Request, + len: usize, + fill: impl FnOnce(&mut [u8]) -> Result<usize, HRESULT>, +) -> Result<(), HRESULT> { + if request.options & PAGE_DESTINATION == 0 { + // Raw reads land through the kernel, which does not fault into the + // GPU side's guard on title buffers; open them first. + victory_gpu::kernel_will_write(request.destination as usize, len); + // SAFETY: the title's destination holds `destination_size` bytes, at + // least `len`, and nothing else writes it until completion. + let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) }; + return fill(out).map(drop); + } + let offset = (request.page_offset & 0xffff) as usize; + // SAFETY: the title passes a page number per 64 KiB of destination, + // which holds at least `len` bytes from `offset`. + let pages = unsafe { + std::slice::from_raw_parts( + request.destination.cast::<usize>(), + (offset + len).div_ceil(PAGE), + ) + }; + // Consecutive pages of one allocation (the usual case): written in + // place through one view. + if let Some(mut window) = super::xmem::page_window(pages, offset, len) { + return fill(window.bytes()).map(drop); + } + let mut data = vec![0; len]; + let n = fill(&mut data)?; + if super::xmem::write_physical(pages, offset, &data[..n]) { + Ok(()) + } else { + // Said aloud: Grand Theft Auto VI 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). +static QUEUE_VTABLE: Methods<12> = Methods([ + missing::<0> as *const (), + add_ref_instance::<Queue> as *const (), + release::<Queue> as *const (), + enqueue_request as *const (), // 0x18 + enqueue_status as *const (), // 0x20 + missing::<5> as *const (), // 0x28 (2020: fence signal) + submit as *const (), // 0x30 + missing::<7> as *const (), // 0x38 (2020: cancel by tag) + close as *const (), // 0x40 + missing::<9> as *const (), // 0x48 (2020: error event) + missing::<10> as *const (), // 0x50 (2020: error record) + missing::<11> as *const (), // 0x58 (2020: queue info) +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "dstorage", + dlls: &["xcrdapi.dll"], + exports: vec![hle_export!(DStorageGetFactory)], + } +} + +#[cfg(test)] +mod tests { + use std::os::windows::ffi::OsStrExt; + use std::time::{Duration, Instant}; + + use super::*; + use crate::modules::xgameruntime::method; + + fn call<F: Copy>(object: *mut c_void, slot: usize) -> F { + // SAFETY: every object here starts with the runtime header. + method(unsafe { &*object.cast::<Object>() }, slot) + } + + fn factory() -> *mut c_void { + let mut factory = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&FACTORY, &mut factory), S_OK); + factory + } + + fn open(path: &std::path::Path) -> *mut c_void { + let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect(); + let open: extern "system" fn(*mut c_void, *const u16, *const Guid, Out) -> HRESULT = + call(factory(), 0x20); + let mut file = std::ptr::null_mut(); + assert_eq!( + open(factory(), wide.as_ptr(), std::ptr::null(), &mut file), + S_OK + ); + file + } + + fn status_array(capacity: u32) -> *mut c_void { + let create: extern "system" fn( + *mut c_void, + u32, + *const c_char, + *const Guid, + Out, + ) -> HRESULT = call(factory(), 0x28); + let mut array = std::ptr::null_mut(); + let name = c"test".as_ptr(); + assert_eq!( + create(factory(), capacity, name, std::ptr::null(), &mut array), + S_OK + ); + array + } + + fn new_queue(source_type: u64) -> *mut c_void { + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type, + capacity: 0x80, + priority: 0, + name: c"test".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + queue + } + + fn request( + options: u64, + destination: *mut c_void, + destination_size: usize, + source: *const c_void, + offset: u64, + source_size: usize, + ) -> Request { + Request { + options, + destination, + page_offset: 0, + destination_size: destination_size as u32, + source, + offset, + source_size: source_size as u32, + intermediate_size: 0, + tag: 0, + name: std::ptr::null(), + } + } + + fn enqueue(queue: *mut c_void, request: &Request) { + let f: extern "system" fn(*mut c_void, *const Request) = call(queue, 0x18); + f(queue, request); + } + + fn enqueue_status(queue: *mut c_void, array: *mut c_void, index: u32) { + let f: extern "system" fn(*mut c_void, *mut c_void, u32) = call(queue, 0x20); + f(queue, array, index); + } + + fn void(object: *mut c_void, slot: usize) { + let f: extern "system" fn(*mut c_void) = call(object, slot); + f(object); + } + + fn result(array: *mut c_void, index: u32) -> HRESULT { + let f: extern "system" fn(*mut c_void, u32) -> HRESULT = call(array, 0x20); + f(array, index) + } + + /// Polls as the title does, then returns the entry's result. + fn wait(array: *mut c_void, index: u32) -> HRESULT { + let done: extern "system" fn(*mut c_void, u32) -> bool = call(array, 0x18); + let start = Instant::now(); + while !done(array, index) { + assert!(start.elapsed() < Duration::from_secs(10), "never completed"); + std::thread::sleep(Duration::from_millis(1)); + } + result(array, index) + } + + fn file_with(bytes: &[u8]) -> (tempfile::TempDir, *mut c_void) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, bytes).unwrap(); + let file = open(&path); + (dir, file) + } + + fn pattern(n: usize) -> Vec<u8> { + (0..n).map(|i| (i * 7 + i / 251) as u8).collect() + } + + #[test] + fn request_layout_is_the_titles() { + assert_eq!(size_of::<Request>(), 0x48); + assert_eq!(std::mem::offset_of!(Request, destination_size), 0x18); + assert_eq!(std::mem::offset_of!(Request, source), 0x20); + assert_eq!(std::mem::offset_of!(Request, source_size), 0x30); + assert_eq!(std::mem::offset_of!(Request, name), 0x40); + assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18); + } + + #[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 mut contents = plain.clone(); + contents.extend_from_slice(&packed); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(1)); + + let mut raw = vec![0u8; 1000]; + let mut inflated = vec![0u8; plain.len()]; + let at = |b: &mut Vec<u8>| b.as_mut_ptr().cast(); + enqueue(queue, &request(0, at(&mut raw), 1000, file, 5000, 1000)); + let offset = plain.len() as u64; + let zlib = request( + ZLIB, + at(&mut inflated), + plain.len(), + file, + offset, + packed.len(), + ); + enqueue(queue, &zlib); + enqueue_status(queue, array, 0); + assert_eq!(result(array, 0), E_PENDING, "pending until done"); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(raw, plain[5000..6000]); + assert_eq!(inflated, plain); + void(queue, 0x40); + } + + #[test] + fn memory_sources_inflate_too() { + let plain = pattern(70_000); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let (queue, array) = (new_queue(1), status_array(1)); + let mut out = vec![0u8; plain.len()]; + let options = ZLIB | MEMORY_SOURCE; + let r = request( + options, + out.as_mut_ptr().cast(), + out.len(), + packed.as_ptr().cast(), + 0, + packed.len(), + ); + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain); + } + + #[test] + fn statuses_complete_in_order_with_the_first_failure() { + let contents = pattern(4096); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(3)); + // 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()); + + // Segment 0: a read past the end, then a bad stream; the first wins. + enqueue(queue, &request(0, failed, 16, file, 4090, 16)); + enqueue(queue, &request(ZLIB, failed_too, 16, file, 0, 16)); + enqueue_status(queue, array, 0); + // Segment 1: two reads. + enqueue(queue, &request(0, other, 16, file, 0, 16)); + enqueue(queue, &request(0, out, 16, file, 100, 16)); + enqueue_status(queue, array, 1); + void(queue, 0x30); + // Segment 2: a BCPack request (BC7) whose stream is empty fails. + with_test_tables(); + enqueue(queue, &request(7 << 1, bcpack, 16, file, 0, 0)); + enqueue_status(queue, array, 2); + void(queue, 0x30); + + assert_eq!(wait(array, 2), INVALID_DATA); + assert_eq!(result(array, 0), END_OF_FILE); + assert_eq!(result(array, 1), S_OK); + assert_eq!(buffers[2], contents[100..116]); + assert_eq!(buffers[3], contents[..16]); + } + + #[test] + fn half_a_queue_submits_itself() { + let (_dir, file) = file_with(&pattern(64)); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"small".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let mut out = [0u8; 16]; + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16)); + enqueue_status(queue, array, 0); // the second of four: no submit needed + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, pattern(64)[8..24]); + } + + /// Lanes without workers: what `start` picks, and when statuses land. + fn lanes(staging: u64) -> Lanes { + Lanes { + lanes: HashMap::new(), + next_id: 0, + next_seq: 0, + staged: 0, + staging, + starved: false, + clock: [0; 3], + now: 0, + lane_now: [0; 3], + done: Default::default(), + refused: 0, + bcpack: Default::default(), + since: None, + } + } + + fn read(lanes: &mut Lanes, id: u64, options: u64, size: u32) { + let mut r = request(options, std::ptr::null_mut(), 0, std::ptr::null(), 0, 0); + (r.destination_size, r.source_size) = (size, size); + let lane = lanes.lanes.get_mut(&id).unwrap(); + lane.unsubmitted.push(Command::Read(r)); + } + + #[test] + fn priorities_share_by_bytes_about_tenfold() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 4096)); + l.lanes.insert(1, Lane::new(1, 4096)); + l.lanes.insert(2, Lane::new(2, 4096)); // real-time: as high + for _ in 0..400 { + for id in 0..3 { + read(&mut l, id, 0, 4096); + } + } + (0..3).for_each(|id| l.submit(id)); + let mut started = [0u32; 3]; + for _ in 0..330 { + let job = l.start().unwrap(); + started[job.lane as usize] += 1; + l.finish(&job, Ok(())); + } + // Normal gets about a tenth of what high and real-time get together. + assert_eq!(started[1] + started[2], 300, "{started:?}"); + assert_eq!(started[0], 30, "{started:?}"); + assert!(started[1].abs_diff(started[2]) <= 1, "{started:?}"); + } + + #[test] + fn staging_bounds_compressed_bytes_in_flight() { + let mut l = lanes(100); + l.lanes.insert(0, Lane::new(0, 64)); + read(&mut l, 0, ZLIB, 60); + read(&mut l, 0, ZLIB, 60); + read(&mut l, 0, 0, 1000); // raw: straight to its destination + l.submit(0); + let first = l.start().unwrap(); + assert!(l.start().is_none(), "60 + 60 > 100"); + l.finish(&first, Ok(())); + let second = l.start().unwrap(); + let raw = l.start().unwrap(); + assert_eq!((second.staging, raw.staging), (60, 0)); + // Alone, a request larger than the buffer still runs. + read(&mut l, 0, ZLIB, 500); + l.submit(0); + assert!(l.start().is_none()); + l.finish(&second, Ok(())); + assert!(l.start().is_some()); + } + + #[test] + fn a_status_waits_for_every_earlier_read() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(2).cast::<Instance<StatusArray>>(); + let status = |index| { + add_ref_instance(array); + Command::Status(Status { array, index }) + }; + read(&mut l, 0, 0, 16); + read(&mut l, 0, 0, 16); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(0)); + read(&mut l, 0, 0, 16); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(1)); + // SAFETY: an array we created. + for entry in unsafe { &(*array).state.entries }.iter() { + entry.store(E_PENDING, Ordering::Release); + } + l.submit(0); + let jobs: Vec<Job> = (0..3).map(|_| l.start().unwrap()).collect(); + // The last read and the first finish; the second then fails. + l.finish(&jobs[2], Ok(())); + l.finish(&jobs[0], Ok(())); + let results = || (result(array.cast(), 0), result(array.cast(), 1)); + assert_eq!(results(), (E_PENDING, E_PENDING)); + l.finish(&jobs[1], Err(INVALID_DATA)); + assert_eq!(results(), (INVALID_DATA, S_OK)); + } + + #[test] + fn zlib_then_bcpack() { + with_test_tables(); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&BC4_STREAM, 6); + let (_dir, file) = file_with(&packed); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + let options = ZLIB | 4 << 1; + let mut r = request(options, out.as_mut_ptr().cast(), 16, file, 0, packed.len()); + r.intermediate_size = BC4_STREAM.len() as u32; + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, bc4_blocks()); + } + + /// BCPack tables we made (uniform models; BC4 index pairs: low 3 bits, + /// next 3 bits), in a folder kept for the test process. + fn with_test_tables() { + static DIR: OnceLock<()> = OnceLock::new(); + DIR.get_or_init(|| { + let mut t = Vec::new(); + for m in 0..128 { + let g = m / 16; + for b in 0..9 { + let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 }; + t.extend_from_slice(&f.to_le_bytes()); + } + } + t.extend([0; 256 + 64 + 256]); + t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4)); + t.resize(bcpack::TABLES_SIZE, 0); + let dir = tempfile::tempdir().unwrap().keep(); + std::fs::write(dir.join("tables.bin"), t).unwrap(); + use_bcpack_tables(dir); + }); + } + + /// Two BC4 blocks from the format's test encoder: endpoints 10, -3 with + /// indices p -> p & 7, then the same block plus 1 everywhere. + const BC4_STREAM: [u8; 88] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 4, 4, 4, 4, 1, 1, 1, 1, 0x10, 0x10, 0x10, 0x10, 2, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0x14, 5, 0x20, 0x68, 0xb0, 0xf8, 3, 3, 2, 2, 0x24, 0x24, 0x24, + 0x24, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 0x10, 0x10, 0x10, 0x10, 0, 0, 0, 0, + 0x20, 0x68, 0xb0, 0xf8, 0x24, 0x24, 0x24, 0x24, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + + /// What `BC4_STREAM` unpacks to. + fn bc4_blocks() -> [u8; 16] { + let code = [0u64, 2, 3, 4, 5, 6, 7, 1]; + let block = |e0: u64, e1: u64, add: usize| { + let bits = (0..16).fold(0, |a, p| a | code[(p + add) & 7] << (16 + 3 * p)); + (e0 | e1 << 8 | bits).to_le_bytes() + }; + let mut out = [0; 16]; + out[..8].copy_from_slice(&block(138, 125, 0)); + out[8..].copy_from_slice(&block(139, 126, 1)); + out + } + + #[test] + fn bcpack_requests_unpack_into_the_destination() { + with_test_tables(); + let mut contents = pattern(100); + contents.extend_from_slice(&BC4_STREAM); + 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_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, bc4_blocks()); + } + + #[test] + fn a_closed_queue_completes_nothing() { + let (_dir, file) = file_with(&pattern(64)); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 0, 16)); + enqueue_status(queue, array, 0); + void(queue, 0x40); + void(queue, 0x30); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(result(array, 0), E_PENDING); + assert_eq!(out, [0; 16]); + } + + #[test] + fn physical_page_destinations() { + use crate::modules::xmem; + let mut pages = [0usize; 2]; + let mut n = 2; + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), + 1 + ); + // Where the title would see them: a reservation of 64 KiB pages. + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), + mapped + ); + + let plain = pattern(100); + let (queue, array) = (new_queue(1), status_array(1)); + let mut r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + pages.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + r.page_offset = (PAGE - 40) as u64; // across the page boundary + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + // SAFETY: both pages are mapped read-write. + let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>().add(PAGE - 40), 100) }; + assert_eq!(seen, plain); + } + #[test] + fn zlib_into_pages_in_place_and_across_allocations() { + use crate::modules::xmem; + let allocate = |n: usize| { + let (mut pages, mut given) = (vec![0usize; n], n); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + pages + }; + let (a, b) = (allocate(3), allocate(1)); + let plain = pattern(2 * PAGE + 100); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + // 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]]]; + let (queue, array) = (new_queue(1), status_array(1)); + for pages in &mut destinations { + let mut r = request( + ZLIB | PAGE_DESTINATION | MEMORY_SOURCE, + pages.as_mut_ptr().cast(), + plain.len(), + packed.as_ptr().cast(), + 0, + packed.len(), + ); + r.page_offset = 50; + enqueue(queue, &r); + } + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + for pages in &destinations { + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, pages.as_ptr()), + mapped + ); + // SAFETY: all three pages are mapped read-write. + let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>(), 3 * PAGE) }; + assert!(seen[..50].iter().all(|&b| b == 0)); + assert_eq!(seen[50..50 + plain.len()], plain); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, std::ptr::null()), + mapped + ); + } + assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1); + } +} diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs new file mode 100644 index 000000000..e25513d76 --- /dev/null +++ b/crates/victory-hle/src/modules/files.rs @@ -0,0 +1,941 @@ +//! Virtual drives over host folders: on the console, title storage is a +//! drive of its own, and titles build paths on that assumption. +//! +//! Every title import that takes a path is bound here. A path on a virtual +//! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host +//! folder behind it and handed to the host's own function; any other path +//! goes to the host unchanged. A rewritten narrow path goes to the host's +//! wide twin, so host folders outside the ANSI code page work; never to our +//! wide wrapper, which would rewrite the host path a second time when its +//! drive letter is mounted too. Letters are chosen among those the host +//! does not use, so no host drive is hidden. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::{CStr, c_char, c_void}; +use std::os::windows::ffi::OsStrExt; +use std::path::Path; +use std::sync::{Mutex, MutexGuard}; + +use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar}; +use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives; + +use crate::{HleExport, HleModule, hle_export}; + +/// The host's own function: what the import would have been bound to. +macro_rules! host { + ($dll:literal, $name:literal: $ty:ty) => {{ + static ADDRESS: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + let address = *ADDRESS.get_or_init(|| { + crate::host::function($dll, $name) + .unwrap_or_else(|| panic!("the host lacks {}!{}", $dll, $name)) + }); + // SAFETY: the host exports this function with this signature. + unsafe { std::mem::transmute::<usize, $ty>(address) } + }}; +} +pub(crate) use host; + +/// Mounted drives: upper-case letter and host root (UTF-16, no trailing +/// separator, no NUL). +static DRIVES: Mutex<Vec<(u16, Vec<u16>)>> = Mutex::new(Vec::new()); + +fn drives() -> MutexGuard<'static, Vec<(u16, Vec<u16>)>> { + DRIVES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Gives the host folder `root` a drive letter (the same one if it already +/// has one): the highest letter neither the host nor another mount uses. +pub fn mount(root: &Path) -> Option<char> { + let wide = root_wide(root); + let mut drives = drives(); + if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) { + return char::from_u32(letter.into()); + } + // SAFETY: no arguments. + let host = unsafe { GetLogicalDrives() }; + let letter = (b'D'..=b'Z').rev().find(|&l| { + host >> (l - b'A') & 1 == 0 && !drives.iter().any(|(m, _)| *m == u16::from(l)) + })?; + tracing::info!(drive = %char::from(letter), root = %root.display(), "virtual drive"); + drives.push((letter.into(), wide)); + Some(letter.into()) +} + +/// Gives the host folder `root` a drive letter the console fixes (titles +/// open their package as `G:\..` and temporary files as `T:\..`). A host +/// drive of that letter is hidden from the title. +pub fn mount_at(letter: char, root: &Path) { + let letter = letter.to_ascii_uppercase(); + let Some(index) = u32::from(letter) + .checked_sub(u32::from('A')) + .filter(|i| *i < 26) + else { + return; + }; + // SAFETY: no arguments. + let hides_host_drive = unsafe { GetLogicalDrives() } >> index & 1 != 0; + tracing::info!(drive = %letter, root = %root.display(), hides_host_drive, "virtual drive"); + let mut drives = drives(); + drives.retain(|(l, _)| u32::from(*l) != u32::from(letter)); + drives.push((letter as u16, root_wide(root))); +} + +/// `root` as UTF-16, absolute, without trailing separators (a drive root +/// keeps its own). +fn root_wide(root: &Path) -> Vec<u16> { + let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned()); + let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect(); + while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { + wide.pop(); + } + wide +} + +const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16]; +const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; + +/// Host paths from this length on take the `\\?\` form, which lifts the +/// host's MAX_PATH limit (248 characters for a directory, 260 for a file). +const LONG: usize = 248; + +/// `root` and the title's `tail` as a `\\?\` path. That form turns off the +/// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved +/// here (`..` stops at the root). +fn verbatim(root: &[u16], tail: &[u16]) -> Vec<u16> { + let backslash = u16::from(b'\\'); + let mut out = if root.starts_with(&VERBATIM) { + root.to_vec() + } else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) { + let mut out = VERBATIM.to_vec(); + out.extend("UNC\\".encode_utf16()); + out.extend_from_slice(unc); + out + } else { + [&VERBATIM[..], root].concat() + }; + while out.last() == Some(&backslash) { + out.pop(); + } + let dot = u16::from(b'.'); + let mut parts: Vec<&[u16]> = Vec::new(); + for part in tail.split(|c| SEPARATORS.contains(c)) { + match part { + [] => {} + [d] if *d == dot => {} + [d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()), + _ => parts.push(part), + } + } + for part in parts { + out.push(backslash); + out.extend_from_slice(part); + } + out +} + +/// The host path, NUL-terminated, for `path` (without its NUL) if it is on +/// a virtual drive. +pub(crate) fn translate(path: &[u16]) -> Option<Vec<u16>> { + let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) { + Some(rest) => (&VERBATIM[..], rest), + None => (&[][..], path), + }; + let &[letter, colon, ..] = rest else { + return None; + }; + if colon != u16::from(b':') { + return None; + } + let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?; + let letter = u16::from(letter.to_ascii_uppercase()); + let drives = drives(); + let (_, root) = drives.iter().find(|(l, _)| *l == letter)?; + let tail = &rest[2..]; + if prefix.is_empty() && root.len() + tail.len() >= LONG { + let mut out = verbatim(root, tail); + out.push(0); + return Some(out); + } + let mut out = prefix.to_vec(); + out.extend_from_slice(root); + // `X:` and `X:name` are relative to the root. + if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) { + out.push(b'\\'.into()); + } + let verbatim = !prefix.is_empty(); + out.extend(tail.iter().map(|&c| { + if verbatim && c == u16::from(b'/') { + b'\\'.into() + } else { + c + } + })); + out.push(0); + Some(out) +} + +/// A title's wide path: the host path when it is on a virtual drive, else +/// the title's own pointer. +struct Wide(*const u16, Option<Vec<u16>>); + +impl Wide { + fn ptr(&self) -> *const u16 { + self.1.as_ref().map_or(self.0, |p| p.as_ptr()) + } +} + +fn wide(path: *const u16) -> Wide { + if path.is_null() { + return Wide(path, None); + } + // SAFETY: the title passes a NUL-terminated path. + let path_slice = unsafe { + let len = (0..).take_while(|&i| *path.add(i) != 0).count(); + std::slice::from_raw_parts(path, len) + }; + let host = translate(path_slice); + trace(path_slice, host.as_deref()); + Wide(path, host) +} + +/// Every title path at debug level, with the host path if rewritten. +fn trace(path: &[u16], host: Option<&[u16]>) { + tracing::debug!( + path = %String::from_utf16_lossy(path), + host = host.map(|h| String::from_utf16_lossy(&h[..h.len() - 1])), + "title path" + ); +} + +/// A narrow path (ANSI code page, as the host decodes it) on a virtual +/// drive, as a wide host path. +fn narrow(path: *const c_char) -> Option<Vec<u16>> { + if path.is_null() { + return None; + } + // SAFETY: the title passes a NUL-terminated path. + let bytes = unsafe { CStr::from_ptr(path) }.to_bytes(); + // The drive part is ASCII in every code page; decode only candidates. + match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) { + [letter, b':', ..] if letter.is_ascii_alphabetic() => {} + _ => { + tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path"); + return None; + } + } + let len = i32::try_from(bytes.len()).ok()?; + // SAFETY: sizing call, then a call with room for `n` units. + let wide = unsafe { + let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0); + let mut wide = vec![0u16; usize::try_from(n).ok()?]; + MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n); + wide + }; + let host = translate(&wide); + trace(&wide, host.as_deref()); + host +} + +/// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call. +fn widen(mode: *const c_char) -> Vec<u16> { + if mode.is_null() { + return vec![0]; + } + // SAFETY: a NUL-terminated mode string. + let bytes = unsafe { CStr::from_ptr(mode) }.to_bytes(); + bytes.iter().map(|&b| u16::from(b)).chain([0]).collect() +} + +type Handle = *mut c_void; +type File = *mut c_void; + +// kernel32 and its file API sets. + +pub extern "system" fn CreateFileW( + path: *const u16, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: Handle, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + p.ptr(), + access, + share, + security, + disposition, + flags, + template, + ) +} + +pub extern "system" fn CreateFileA( + path: *const c_char, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: Handle, +) -> Handle { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + p.as_ptr(), + access, + share, + security, + disposition, + flags, + template, + ) + } + None => { + host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + path, + access, + share, + security, + disposition, + flags, + template, + ) + } + } +} + +/// Used by Bink. +pub extern "system" fn CreateFile2( + path: *const u16, + access: u32, + share: u32, + disposition: u32, + params: *const c_void, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "CreateFile2": extern "system" fn(*const u16, u32, u32, u32, *const c_void) -> Handle)( + p.ptr(), + access, + share, + disposition, + params, + ) +} + +pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.as_ptr()) + } + None => { + host!("kernel32.dll", "DeleteFileA": extern "system" fn(*const c_char) -> i32)(path) + } + } +} + +pub extern "system" fn DeleteFileW(path: *const u16) -> i32 { + let p = wide(path); + host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.ptr()) +} + +pub extern "system" fn RemoveDirectoryW(path: *const u16) -> i32 { + let p = wide(path); + host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr()) +} + +pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32 { + let p = wide(path); + host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)( + p.ptr(), + attributes, + ) +} + +pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)( + p.as_ptr(), + ) + } + None => { + host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)( + path, + ) + } + } +} + +pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 { + let p = wide(path); + host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)( + p.ptr(), + security, + ) +} + +pub extern "system" fn GetFileAttributesExW( + path: *const u16, + level: i32, + info: *mut c_void, +) -> i32 { + let p = wide(path); + host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)( + p.ptr(), + level, + info, + ) +} + +pub extern "system" fn GetFileAttributesW(path: *const u16) -> u32 { + let p = wide(path); + host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(p.ptr()) +} + +pub extern "system" fn GetDiskFreeSpaceExW( + path: *const u16, + available: *mut u64, + total: *mut u64, + free: *mut u64, +) -> i32 { + let p = wide(path); + host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)( + p.ptr(), + available, + total, + free, + ) +} + +/// Wants a volume root: a virtual drive answers for the host volume its +/// folder is on. +pub extern "system" fn GetDiskFreeSpaceW( + root: *const u16, + sectors_per_cluster: *mut u32, + bytes_per_sector: *mut u32, + free_clusters: *mut u32, + clusters: *mut u32, +) -> i32 { + let mut p = wide(root); + if let Some(host) = &mut p.1 + && let [letter, colon, sep, ..] = host[..] + && colon == u16::from(b':') + && SEPARATORS.contains(&sep) + { + *host = vec![letter, colon, sep, 0]; + } + host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)( + p.ptr(), + sectors_per_cluster, + bytes_per_sector, + free_clusters, + clusters, + ) +} + +pub extern "system" fn FindFirstFileW(path: *const u16, data: *mut c_void) -> Handle { + let p = wide(path); + host!("kernel32.dll", "FindFirstFileW": extern "system" fn(*const u16, *mut c_void) -> Handle)( + p.ptr(), + data, + ) +} + +pub extern "system" fn FindFirstFileExW( + path: *const u16, + level: i32, + data: *mut c_void, + search: i32, + filter: *mut c_void, + flags: u32, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "FindFirstFileExW": extern "system" fn(*const u16, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)( + p.ptr(), + level, + data, + search, + filter, + flags, + ) +} + +pub extern "system" fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32 { + let (from, to) = (wide(from), wide(to)); + host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)( + from.ptr(), + to.ptr(), + flags, + ) +} + +pub extern "system" fn SetCurrentDirectoryA(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)( + p.as_ptr(), + ) + } + None => { + host!("kernel32.dll", "SetCurrentDirectoryA": extern "system" fn(*const c_char) -> i32)( + path, + ) + } + } +} + +// The C runtime (ucrtbase, which the title's CRT imports bind to). + +pub extern "C" fn _wfopen(path: *const u16, mode: *const u16) -> File { + let p = wide(path); + host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(p.ptr(), mode) +} + +pub extern "C" fn _wfopen_s(out: *mut File, path: *const u16, mode: *const u16) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( + out, + p.ptr(), + mode, + ) +} + +pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> File { + let p = wide(path); + host!("ucrtbase.dll", "_wfsopen": extern "C" fn(*const u16, *const u16, i32) -> File)( + p.ptr(), + mode, + share, + ) +} + +// 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 +// synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned +// destinations and retry a failed `ReadFile` forever. So the destination +// is opened first. + +pub extern "system" fn ReadFile( + file: *mut c_void, + buffer: *mut u8, + len: u32, + read: *mut u32, + overlapped: *mut c_void, +) -> i32 { + victory_gpu::kernel_will_write(buffer as usize, len as usize); + host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( + file, buffer, len, read, overlapped, + ) +} + +/// The host CRT reads large requests straight into the caller's buffer. +pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { + victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); + host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( + buffer, size, count, stream, + ) +} + +pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)( + p.as_ptr(), + widen(mode).as_ptr(), + ), + None => { + host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)( + path, mode, + ) + } + } +} + +pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( + out, + p.as_ptr(), + widen(mode).as_ptr(), + ) + } + None => { + host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)( + out, path, mode, + ) + } + } +} + +/// `_open(path, flags[, mode])` is variadic; on x64 the optional integer +/// travels in the same register either way, so it is passed on as is. +pub extern "C" fn _open(path: *const c_char, flags: i32, mode: i32) -> i32 { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( + p.as_ptr(), + flags, + mode, + ), + None => host!("ucrtbase.dll", "_open": extern "C" fn(*const c_char, i32, i32) -> i32)( + path, flags, mode, + ), + } +} + +/// See [`_open`]; used by libHttpClient. +pub extern "C" fn _wopen(path: *const u16, flags: i32, mode: i32) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( + p.ptr(), + flags, + mode, + ) +} + +pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat) +} + +pub extern "C" fn _stat64i32(path: *const c_char, stat: *mut c_void) -> i32 { + match narrow(path) { + Some(p) => { + host!("ucrtbase.dll", "_wstat64i32": extern "C" fn(*const u16, *mut c_void) -> i32)( + p.as_ptr(), + stat, + ) + } + None => { + host!("ucrtbase.dll", "_stat64i32": extern "C" fn(*const c_char, *mut c_void) -> i32)( + path, stat, + ) + } + } +} + +pub extern "C" fn remove(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wremove": extern "C" fn(*const u16) -> i32)(p.as_ptr()), + None => host!("ucrtbase.dll", "remove": extern "C" fn(*const c_char) -> i32)(path), + } +} + +pub extern "C" fn _wchmod(path: *const u16, mode: i32) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wchmod": extern "C" fn(*const u16, i32) -> i32)(p.ptr(), mode) +} + +pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wutime64": extern "C" fn(*const u16, *mut c_void) -> i32)( + p.ptr(), + times, + ) +} + +// The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`. + +const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z"; +const FIOPEN_WIDE: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z"; + +/// `_Fiopen(const wchar_t* path, ios_base::openmode, int protection)`. +extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File { + let p = wide(path); + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( + p.ptr(), + mode, + protection, + ) +} + +/// `_Fiopen(const char* path, ios_base::openmode, int protection)`. +extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File { + match narrow(path) { + Some(p) => { + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( + p.as_ptr(), + mode, + protection, + ) + } + None => { + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)( + path, mode, protection, + ) + } + } +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "files", + dlls: &[ + "kernel32.dll", + "kernelbase.dll", + "api-ms-win-core-file-*", + "api-ms-win-core-processenvironment-*", + "ucrtbase.dll", + "api-ms-win-crt-stdio-*", + "api-ms-win-crt-filesystem-*", + "api-ms-win-crt-time-*", + "msvcp140.dll", + ], + exports: vec![ + hle_export!(ReadFile), + hle_export!(fread), + hle_export!(CreateFileW), + hle_export!(CreateFileA), + hle_export!(CreateFile2), + hle_export!(DeleteFileA), + hle_export!(DeleteFileW), + hle_export!(RemoveDirectoryW), + hle_export!(SetFileAttributesW), + hle_export!(GetFileAttributesA), + hle_export!(CreateDirectoryW), + hle_export!(GetFileAttributesW), + hle_export!(GetFileAttributesExW), + hle_export!(GetDiskFreeSpaceExW), + hle_export!(GetDiskFreeSpaceW), + hle_export!(FindFirstFileW), + hle_export!(FindFirstFileExW), + hle_export!(MoveFileExW), + hle_export!(SetCurrentDirectoryA), + hle_export!(_wfopen), + hle_export!(_wfopen_s), + hle_export!(_wfsopen), + hle_export!(fopen), + hle_export!(fopen_s), + hle_export!(_open), + hle_export!(_wopen), + hle_export!(_wstat64), + hle_export!(_stat64i32), + hle_export!(remove), + hle_export!(_wchmod), + hle_export!(_wutime64), + HleExport { + name: FIOPEN, + address: fiopen as *const () as usize, + }, + HleExport { + name: FIOPEN_WIDE, + address: fiopen_wide as *const () as usize, + }, + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn w(s: &str) -> Vec<u16> { + s.encode_utf16().chain([0]).collect() + } + + #[test] + fn kernel_reads_reach_the_buffer() { + use std::os::windows::io::AsRawHandle; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, b"0123456789").unwrap(); + 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_eq!((&out, n), (b"0123456789", 10)); + } + + fn text(v: &[u16]) -> String { + String::from_utf16_lossy(&v[..v.len() - 1]) + } + + #[test] + fn rewrites_only_paths_on_mounted_drives() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().to_string_lossy().into_owned(); + let letter = mount(dir.path()).unwrap(); + assert_eq!( + mount(dir.path()), + Some(letter), + "mounting twice reuses the letter" + ); + let tr = |s: String| translate(&w(&s)[..s.encode_utf16().count()]).map(|v| text(&v)); + assert_eq!( + tr(format!("{letter}:/a/b.txt")), + Some(format!("{root}/a/b.txt")) + ); + let lower = letter.to_ascii_lowercase(); + assert_eq!(tr(format!("{lower}:\\a")), Some(format!("{root}\\a"))); + assert_eq!(tr(format!("{letter}:")), Some(format!("{root}\\"))); + assert_eq!( + tr(format!(r"\\?\{letter}:/a/b")), + Some(format!(r"\\?\{root}\a\b")) + ); + assert_eq!(tr(r"C:\Windows".into()), None); + assert_eq!(tr("relative/path".into()), None); + assert_eq!(tr(String::new()), None); + + // Fixed letters, as the console's package drive; a later mount of + // the same letter replaces the earlier one. + let package = tempfile::tempdir().unwrap(); + mount_at('g', dir.path()); + mount_at('G', package.path()); + assert_eq!( + tr(r"G:\appdata0.rpf".into()), + Some(format!(r"{}\appdata0.rpf", package.path().display())) + ); + assert_ne!(mount(dir.path()), Some('G'), "free letters skip fixed ones"); + + // Long ones take the `\\?\` form, cleaned up as the host would. + let long = "d".repeat(250); + assert_eq!( + tr(format!(r"G:/a/./b/../{long}//f")), + Some(format!(r"\\?\{}\a\{long}\f", package.path().display())) + ); + assert_eq!( + verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]), + w(r"\\?\UNC\server\share\y")[..22].to_vec() + ); + } + + #[test] + fn long_title_paths_work_on_the_host() { + let dir = tempfile::tempdir().unwrap(); + let letter = mount(dir.path()).unwrap(); + let deep = format!("{letter}:/{}/{}", "a".repeat(200), "b".repeat(100)); + let null = std::ptr::null_mut(); + let first = w(&deep[..203]); + assert_ne!(CreateDirectoryW(first.as_ptr(), null), 0); + assert_ne!(CreateDirectoryW(w(&deep).as_ptr(), null), 0); + let file = format!("{deep}/../{}/f.txt", "b".repeat(100)); + let f = _wfopen(w(&file).as_ptr(), w("wb").as_ptr()); + assert!(!f.is_null(), "{file}"); + host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32)(f); + assert_ne!(DeleteFileW(w(&format!("{deep}/f.txt")).as_ptr()), 0); + assert_ne!(RemoveDirectoryW(w(&deep).as_ptr()), 0); + } + + #[test] + fn title_file_calls_land_in_the_host_folder() { + let dir = tempfile::tempdir().unwrap(); + let letter = mount(dir.path()).unwrap(); + const GENERIC_WRITE: u32 = 0x4000_0000; + const CREATE_ALWAYS: u32 = 2; + let close = host!("kernel32.dll", "CloseHandle": extern "system" fn(Handle) -> i32); + let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); + + let path = w(&format!(r"{letter}:\created.bin")); + let null = std::ptr::null_mut(); + let h = CreateFileW( + path.as_ptr(), + GENERIC_WRITE, + 0, + null, + CREATE_ALWAYS, + 0, + null, + ); + assert_ne!(h as isize, -1); + close(h); + assert!(dir.path().join("created.bin").is_file()); + + let path = format!("{letter}:/opened.txt\0"); + let f = fopen(path.as_ptr().cast(), c"wb".as_ptr()); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("opened.txt").is_file()); + + let path = format!("{letter}:/stream.txt\0"); + const OUT: i32 = 2; + let f = fiopen(path.as_ptr().cast(), OUT, 0x40); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("stream.txt").is_file()); + + assert_eq!(remove(path.as_ptr().cast()), 0); + assert!(!dir.path().join("stream.txt").exists()); + let f = fiopen_wide(w(&format!("{letter}:/wide.txt")).as_ptr(), OUT, 0x40); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("wide.txt").is_file()); + + const OPEN_EXISTING: u32 = 3; + let path = w(&format!(r"{letter}:\created.bin")); + let h = CreateFile2(path.as_ptr(), GENERIC_WRITE, 0, OPEN_EXISTING, null); + assert_ne!(h as isize, -1); + close(h); + const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; + assert_ne!(GetFileAttributesW(path.as_ptr()), INVALID_FILE_ATTRIBUTES); + + const O_WRONLY: i32 = 1; + const O_CREAT: i32 = 0x100; + const S_IWRITE: i32 = 0x80; + let path = format!("{letter}:/low.bin\0"); + let fd = _open(path.as_ptr().cast(), O_WRONLY | O_CREAT, S_IWRITE); + assert!(fd >= 0); + host!("ucrtbase.dll", "_close": extern "C" fn(i32) -> i32)(fd); + assert!(dir.path().join("low.bin").is_file()); + + // Other paths pass through untouched. + let host_path = format!("{}\0", dir.path().join("plain.txt").display()); + let f = fopen(host_path.as_ptr().cast(), c"wb".as_ptr()); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("plain.txt").is_file()); + } + + /// A narrow path is rewritten once, as its wide twin is. The inner + /// drive's folder lies on the outer virtual drive, as the title folder + /// does when it sits on a host `G:` drive and is mounted as `G:`. The + /// outer letter is no host drive, so the host finds nothing there; a + /// narrow call that reaches the outer folder rewrote the path twice. + #[test] + fn narrow_paths_are_rewritten_once() { + let dir = tempfile::tempdir().unwrap(); + let folder = dir.path().join("inner"); + std::fs::create_dir(&folder).unwrap(); + std::fs::write(folder.join("present.txt"), b"").unwrap(); + let outer = mount(dir.path()).unwrap(); + let inner = mount(Path::new(&format!(r"{outer}:\inner"))).unwrap(); + let path = |name: &str| format!("{inner}:/{name}\0"); + + const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; + let wide = GetFileAttributesW(w(&format!("{inner}:/present.txt")).as_ptr()); + assert_eq!(wide, INVALID_FILE_ATTRIBUTES); + let narrow = GetFileAttributesA(path("present.txt").as_ptr().cast()); + assert_eq!(narrow, wide, "GetFileAttributesA agrees with its wide twin"); + + const GENERIC_WRITE: u32 = 0x4000_0000; + const CREATE_ALWAYS: u32 = 2; + let null = std::ptr::null_mut(); + let h = CreateFileA( + path("a.bin").as_ptr().cast(), + GENERIC_WRITE, + 0, + null, + CREATE_ALWAYS, + 0, + null, + ); + assert_eq!(h as isize, -1); + assert!(fopen(path("b.txt").as_ptr().cast(), c"wb".as_ptr()).is_null()); + let mut f: File = std::ptr::null_mut(); + let error = fopen_s(&mut f, path("c.txt").as_ptr().cast(), c"wb".as_ptr()); + assert_ne!(error, 0); + const OUT: i32 = 2; + assert!(fiopen(path("d.txt").as_ptr().cast(), OUT, 0x40).is_null()); + + // Nothing was made behind a path rewritten twice. + let names: Vec<_> = std::fs::read_dir(&folder) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, ["present.txt"]); + } +} diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs new file mode 100644 index 000000000..a45081e98 --- /dev/null +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -0,0 +1,1629 @@ +//! `gameinput.dll`: input devices from the host. Gamepads come from XInput +//! (host slots 0-3); while none is connected, the keyboard drives one +//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own +//! 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)] +// Title code calls these through the objects, passing pointers the real API +// would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::VecDeque; +use std::ffi::c_void; +use std::ops::Deref; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; +use std::thread::ThreadId; +use std::time::{Duration, Instant}; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL}; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleExport, HleModule}; + +/// The documented errors. +pub const DEVICE_DISCONNECTED: HRESULT = 0x838A_0001_u32 as i32; +pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32; +pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32; +pub const REFERENCE_TOO_OLD: HRESULT = 0x838A_0004_u32 as i32; +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; + +/// Input kinds (bits) our devices have. +const KEYBOARD_KIND: u32 = 0x10; +const GAMEPAD_KIND: u32 = 0x4_0000; +/// Device status of a connected device: connected, input enabled. +const STATUS_CONNECTED: u32 = 0x3; +const ASYNC_ENUMERATION: u32 = 1; + +/// Gamepad buttons; the title maps each bit to one of its pad buttons. +const MENU: u32 = 0x1; +const VIEW: u32 = 0x2; +const A: u32 = 0x4; +const B: u32 = 0x8; +const X: u32 = 0x10; +const Y: u32 = 0x20; +const UP: u32 = 0x40; +const DOWN: u32 = 0x80; +const LEFT: u32 = 0x100; +const RIGHT: u32 = 0x200; +const LEFT_SHOULDER: u32 = 0x400; +const RIGHT_SHOULDER: u32 = 0x800; +const LEFT_STICK: u32 = 0x1000; +const RIGHT_STICK: u32 = 0x2000; + +/// Devices: host pad slots, the keyboard's stand-in pad, the keyboard. +const PADS: usize = 4; +const FALLBACK: usize = PADS; +const KEYBOARD: usize = PADS + 1; +const DEVICES: usize = PADS + 2; + +/// Readings kept per device for next/previous lookups. +const HISTORY: usize = 32; +const POLL: Duration = Duration::from_millis(8); + +/// The keyboard's stand-in gamepad (virtual key, button); README lists it. +/// Sticks: W/A/S/D left, I/J/K/L right; triggers Z and C. +const FALLBACK_BUTTONS: [(u8, u32); 14] = [ + (0x1B, MENU), // Esc + (0x09, VIEW), // Tab + (0x0D, A), // Enter + (0x08, B), // Backspace + (b'X', X), + (b'Y', Y), + (0x26, UP), // arrows + (0x28, DOWN), + (0x25, LEFT), + (0x27, RIGHT), + (b'Q', LEFT_SHOULDER), + (b'E', RIGHT_SHOULDER), + (b'F', LEFT_STICK), + (b'H', RIGHT_STICK), +]; + +/// A gamepad reading: triggers 0 to 1, sticks -1 to 1 (up positive). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct PadState { + buttons: u32, + left_trigger: f32, + right_trigger: f32, + left_x: f32, + left_y: f32, + right_x: f32, + right_y: f32, +} + +/// One key held down: scan code (0xE0xx when extended), character, key. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct KeyState { + scan_code: u32, + code_point: u32, + virtual_key: u8, + dead_key: bool, +} + +const _: () = assert!(size_of::<KeyState>() == 12 && size_of::<PadState>() == 28); + +/// Host input, or a fake in tests. +trait Source: Send { + /// The pad in host slot `slot`, `None` when the slot is empty. + fn pad(&mut self, slot: usize) -> Option<PadState>; + /// Keys held down; none while the title's window lacks focus. + fn keys(&mut self) -> Vec<KeyState>; + /// Motor speeds: low frequency (left), high frequency (right). + fn rumble(&mut self, slot: usize, low: u16, high: u16); +} + +fn fallback(keys: &[KeyState]) -> PadState { + let on = |vk: u8| { + if keys.iter().any(|k| k.virtual_key == vk) { + 1.0 + } else { + 0.0 + } + }; + PadState { + buttons: FALLBACK_BUTTONS + .iter() + .filter(|(vk, _)| on(*vk) != 0.0) + .fold(0, |all, (_, bit)| all | bit), + left_trigger: on(b'Z'), + right_trigger: on(b'C'), + left_x: on(b'D') - on(b'A'), + left_y: on(b'W') - on(b'S'), + right_x: on(b'L') - on(b'J'), + right_y: on(b'I') - on(b'K'), + } +} + +#[repr(C)] +struct Table<const N: usize>([*const (); N]); +// SAFETY: function addresses only. +unsafe impl<const N: usize> Sync for Table<N> {} + +/// The input object; one per hub. +#[repr(C)] +pub struct Object { + vtable: &'static Table<22>, + hub: *const Hub, +} + +#[repr(C)] +pub struct Device { + vtable: &'static Table<21>, + hub: *const Hub, + index: usize, + info: DeviceInfo, +} + +/// What a device says about itself. The title reads `id` (+0x20); the rest +/// follows the public layout and is zero where we have nothing to say. +#[repr(C)] +#[derive(Default)] +#[allow(dead_code)] // read by title code +struct DeviceInfo { + size: u32, + vendor: u16, + product: u16, + revision: u16, + interface: u8, + collection: u8, + usage: [u16; 2], + versions: [u16; 8], + id: [u8; 32], + root_id: [u8; 32], + family: i32, + capabilities: u32, + supported_input: u32, + rumble_motors: u32, + /// Counts and optional detail pointers. + rest: [u64; 26], +} + +const _: () = assert!(std::mem::offset_of!(DeviceInfo, id) == 0x20); + +fn kind(index: usize) -> u32 { + if index == KEYBOARD { + KEYBOARD_KIND + } else { + GAMEPAD_KIND + } +} + +impl Device { + fn new(index: usize) -> Device { + let mut id = [0; 32]; + id[..7].copy_from_slice(b"victory"); + id[31] = index as u8 + 1; + let info = DeviceInfo { + size: size_of::<DeviceInfo>() as u32, + id, + root_id: id, + supported_input: kind(index), + // Low and high frequency. + rumble_motors: if index < PADS { 0x3 } else { 0 }, + ..Default::default() + }; + Device { + vtable: &DEVICE, + hub: std::ptr::null(), + index, + info, + } + } + + fn hub(&self) -> &'static Hub { + // SAFETY: set by `Hub::new`; hubs are never freed. + unsafe { &*self.hub } + } +} + +#[derive(PartialEq)] +enum Value { + Pad(PadState), + Keys(Vec<KeyState>), +} + +#[repr(C)] +pub struct Reading { + vtable: &'static Table<25>, + refs: AtomicU32, + device: *const Device, + sequence: u64, + timestamp: u64, + value: Value, +} + +impl Reading { + fn kind(&self) -> u32 { + match self.value { + Value::Pad(_) => GAMEPAD_KIND, + Value::Keys(_) => KEYBOARD_KIND, + } + } +} + +/// A counted reference to a reading. +struct Ref(NonNull<Reading>); + +impl Ref { + fn new(reading: Reading) -> Ref { + Ref(NonNull::from(Box::leak(Box::new(reading)))) + } + + /// Another reference, for the title. + fn share(&self) -> *const Reading { + reading_add_ref(self.0.as_ptr()); + self.0.as_ptr() + } +} + +impl Deref for Ref { + type Target = Reading; + fn deref(&self) -> &Reading { + // SAFETY: we hold a reference, so it is alive. + unsafe { self.0.as_ref() } + } +} + +impl Drop for Ref { + fn drop(&mut self) { + reading_release(self.0.as_ptr()); + } +} + +type DeviceCallback = extern "system" fn(u64, *mut c_void, *const Device, u64, u32, u32); + +#[derive(Clone, Copy)] +struct Registration { + token: u64, + /// One device's address, or 0 for any. + device: usize, + kind: u32, + status: u32, + context: usize, + callback: DeviceCallback, +} + +impl Registration { + fn matches(&self, devices: &[Device; DEVICES], index: usize) -> bool { + kind(index) & self.kind != 0 + && (self.device == 0 || self.device == &devices[index] as *const Device as usize) + } + + fn event(&self, device: usize, timestamp: u64, current: u32, previous: u32) -> Event { + Event { + registration: *self, + device, + timestamp, + current, + previous, + } + } +} + +struct Event { + registration: Registration, + device: usize, + timestamp: u64, + current: u32, + previous: u32, +} + +#[derive(Default)] +struct Slot { + connected: bool, + sequence: u64, + history: VecDeque<Ref>, +} + +struct State { + slots: [Slot; DEVICES], + callbacks: Vec<Registration>, + /// Asynchronous enumerations, delivered by the next poll. + pending: Vec<Event>, + /// Device callbacks running now: token and thread. + running: Vec<(u64, ThreadId)>, +} + +pub struct Hub { + object: Object, + devices: [Device; DEVICES], + /// Apart from the state: XInput can be slow, and the title reads + /// readings every frame. + source: Mutex<Box<dyn Source>>, + state: Mutex<State>, + /// A device callback returned. + returned: Condvar, +} + +fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +// SAFETY: the back pointers are set before the hub is shared and never +// change; what changes sits behind the mutex or is atomic. +unsafe impl Send for Hub {} +// SAFETY: as above. +unsafe impl Sync for Hub {} + +static START: LazyLock<Instant> = LazyLock::new(Instant::now); + +/// Microseconds, the clock of every timestamp we hand out. +fn now() -> u64 { + START.elapsed().as_micros() as u64 +} + +impl Hub { + fn new(source: Box<dyn Source>) -> &'static Hub { + let hub = Box::into_raw(Box::new(Hub { + object: Object { + vtable: &INPUT, + hub: std::ptr::null(), + }, + devices: std::array::from_fn(Device::new), + source: Mutex::new(source), + state: Mutex::new(State { + slots: Default::default(), + callbacks: Vec::new(), + pending: Vec::new(), + running: Vec::new(), + }), + returned: Condvar::new(), + })); + // SAFETY: just allocated and never freed; nothing else sees it yet. + unsafe { + (*hub).object.hub = hub; + for device in &mut (*hub).devices { + device.hub = hub; + } + &*hub + } + } + + /// A hub over the host's input, polled from now on. + fn start(source: Box<dyn Source>) -> &'static Hub { + let hub = Hub::new(source); + hub.poll(); + std::thread::spawn(move || { + loop { + std::thread::sleep(POLL); + hub.poll(); + } + }); + hub + } + + fn state(&self) -> MutexGuard<'_, State> { + lock(&self.state) + } + + /// Reads the host once; device callbacks run on the calling thread. + fn poll(&self) { + let (pads, keys) = { + let mut source = lock(&self.source); + let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); + (pads, source.keys()) + }; + let events = self.state().poll(&self.devices, pads, keys); + self.deliver(events); + } + + /// Runs callbacks, never under our lock: they call back into us. One + /// unregistered since the event was taken does not run, and + /// `UnregisterCallback` waits for one that runs. + fn deliver(&self, events: Vec<Event>) { + let me = std::thread::current().id(); + for e in events { + let r = e.registration; + { + let mut state = self.state(); + if !state.callbacks.iter().any(|c| c.token == r.token) { + continue; + } + state.running.push((r.token, me)); + } + (r.callback)( + r.token, + r.context as *mut c_void, + &self.devices[e.device], + e.timestamp, + e.current, + e.previous, + ); + let mut state = self.state(); + if let Some(i) = state.running.iter().position(|&x| x == (r.token, me)) { + state.running.swap_remove(i); + } + self.returned.notify_all(); + } + } + + fn index(&self, device: *const Device) -> Option<usize> { + self.devices.iter().position(|d| std::ptr::eq(d, device)) + } +} + +impl State { + fn poll( + &mut self, + devices: &[Device; DEVICES], + pads: [Option<PadState>; PADS], + keys: Vec<KeyState>, + ) -> Vec<Event> { + let now = now(); + let mut events = std::mem::take(&mut self.pending); + 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 = (!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 + } + + /// Records a device's state: a reading when it changed, callbacks when + /// the device came or went. + fn update( + &mut self, + devices: &[Device; DEVICES], + index: usize, + value: Option<Value>, + now: u64, + events: &mut Vec<Event>, + ) { + let slot = &mut self.slots[index]; + let was = slot.connected; + slot.connected = value.is_some(); + if let Some(value) = value + && (!was || slot.history.back().is_none_or(|r| r.value != value)) + { + slot.sequence += 1; + if slot.history.len() == HISTORY { + slot.history.pop_front(); + } + slot.history.push_back(Ref::new(Reading { + vtable: &READING, + refs: AtomicU32::new(1), + device: &devices[index], + sequence: slot.sequence, + timestamp: now, + value, + })); + } + if was != slot.connected { + tracing::info!(device = index, connected = !was, "input device"); + let (current, previous) = if was { + (0, STATUS_CONNECTED) + } else { + (STATUS_CONNECTED, 0) + }; + events.extend( + self.callbacks + .iter() + .filter(|r| r.matches(devices, index) && r.status & STATUS_CONNECTED != 0) + .map(|r| r.event(index, now, current, previous)), + ); + } + } +} + +#[cfg(windows)] +fn host() -> Box<dyn Source> { + Box::new(host::Host::default()) +} + +#[cfg(not(windows))] +fn host() -> Box<dyn Source> { + struct Nothing; + impl Source for Nothing { + fn pad(&mut self, _: usize) -> Option<PadState> { + None + } + fn keys(&mut self) -> Vec<KeyState> { + Vec::new() + } + fn rumble(&mut self, _: usize, _: u16, _: u16) {} + } + Box::new(Nothing) +} + +static HUB: LazyLock<&'static Hub> = LazyLock::new(|| Hub::start(host())); + +type This = *const Object; +type Out = *mut *const c_void; + +/// The DLL's only export (ordinal 1): the input object, static and shared. +pub extern "system" fn GameInputCreate(out: *mut This) -> HRESULT { + tracing::info!("GameInputCreate"); + if out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(&HUB.object) }; + S_OK +} + +fn hub(this: This) -> &'static Hub { + // SAFETY: `this` is a hub's object; hubs are never freed. + unsafe { &*(*this).hub } +} + +/// Clears a COM out pointer and returns `hr`. +fn fail(out: Out, hr: HRESULT) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(std::ptr::null()) }; + } + hr +} + +/// Gives the title a reference to `reading`, or fails as with none. +fn hand(out: Out, reading: Option<&Ref>) -> HRESULT { + match reading { + _ if out.is_null() => E_INVALIDARG, + Some(reading) => { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(reading.share().cast()) }; + S_OK + } + None => fail(out, READING_NOT_FOUND), + } +} + +extern "system" fn no_interface(_: *const c_void, _iid: *const c_void, out: Out) -> HRESULT { + tracing::warn!("input QueryInterface not implemented"); + fail(out, E_NOINTERFACE) +} +/// The input object and devices live as long as the process. +extern "system" fn add_ref(_: *const c_void) -> u32 { + 1 +} + +extern "system" fn timestamp(_: This) -> u64 { + now() +} + +extern "system" fn current_reading( + this: This, + kind: u32, + device: *const Device, + out: Out, +) -> HRESULT { + let hub = hub(this); + let state = hub.state(); + let newest = |i: usize| { + state.slots[i] + .history + .back() + .filter(|r| r.kind() & kind != 0) + }; + let found = if device.is_null() { + (0..DEVICES) + .filter(|&i| state.slots[i].connected) + .filter_map(newest) + .max_by_key(|r| r.timestamp) + } else { + match hub.index(device) { + None => return fail(out, E_INVALIDARG), + Some(i) if !state.slots[i].connected => return fail(out, DEVICE_DISCONNECTED), + Some(i) => newest(i), + } + }; + tracing::trace!( + kind = format_args!("{kind:#x}"), + device = ?hub.index(device), + sequence = found.map(|r| r.sequence), + "current reading" + ); + hand(out, found) +} + +/// The reading after (`forward`) or before `reference` on its device. +fn relative( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, + forward: bool, +) -> HRESULT { + if reference.is_null() { + return fail(out, E_INVALIDARG); + } + let hub = hub(this); + // 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 + // 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); + }; + if !device.is_null() && !std::ptr::eq(device, reference.device) { + return fail(out, E_INVALIDARG); + } + let state = hub.state(); + let history = &state.slots[index].history; + if history + .front() + .is_none_or(|oldest| reference.sequence < oldest.sequence) + { + return fail(out, REFERENCE_TOO_OLD); + } + let wanted = |r: &&Ref| r.kind() & kind != 0; + let found = if forward { + history + .iter() + .filter(|r| r.sequence > reference.sequence) + .find(wanted) + } else { + history + .iter() + .rev() + .filter(|r| r.sequence < reference.sequence) + .find(wanted) + }; + hand(out, found) +} +extern "system" fn next_reading( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, +) -> HRESULT { + relative(this, reference, kind, device, out, true) +} +extern "system" fn previous_reading( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, +) -> HRESULT { + relative(this, reference, kind, device, out, false) +} +/// The device's reading at `time`, among those still kept. +extern "system" fn temporal_reading( + this: This, + time: u64, + device: *const Device, + out: Out, +) -> HRESULT { + let hub = hub(this); + let Some(index) = hub.index(device) else { + return fail(out, E_INVALIDARG); + }; + let state = hub.state(); + let history = &state.slots[index].history; + hand(out, history.iter().rev().find(|r| r.timestamp <= time)) +} + +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +fn token(out: *mut u64) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(NEXT_TOKEN.fetch_add(1, Ordering::Relaxed)) }; + } + S_OK +} + +// shortcut: reading callbacks never run; Grand Theft Auto VI registers none +// (it polls). +extern "system" fn register_reading( + _: This, + _device: *const c_void, + _kind: u32, + _threshold: f32, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + tracing::warn!("input reading callbacks are never called"); + token(out) +} + +/// Device callbacks run on our poll thread when a device comes or goes. +/// Enumeration reports the devices already there: blocking on the caller's +/// thread before we return (the title registers holding a lock its callback +/// takes again), asynchronous on the next poll. +extern "system" fn register_device( + this: This, + device: *const Device, + kind: u32, + status: u32, + enumeration: u32, + context: *mut c_void, + callback: Option<DeviceCallback>, + out: *mut u64, +) -> HRESULT { + let Some(callback) = callback else { + return E_INVALIDARG; + }; + let hub = hub(this); + let registration = Registration { + token: NEXT_TOKEN.fetch_add(1, Ordering::Relaxed), + device: device as usize, + kind, + status, + context: context as usize, + callback, + }; + let mut found = Vec::new(); + { + let mut state = hub.state(); + if enumeration != 0 && status & STATUS_CONNECTED != 0 { + let now = now(); + found = (0..DEVICES) + .filter(|&i| state.slots[i].connected && registration.matches(&hub.devices, i)) + .map(|i| registration.event(i, now, STATUS_CONNECTED, 0)) + .collect(); + } + tracing::info!( + kind = format_args!("{kind:#x}"), + enumeration, + devices = found.len(), + "input device callback" + ); + state.callbacks.push(registration); + if enumeration == ASYNC_ENUMERATION { + state.pending.append(&mut found); + } + } + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(registration.token) }; + } + hub.deliver(found); + S_OK +} +/// Guide button and keyboard layout callbacks: neither ever changes here. +extern "system" fn register_other( + _: This, + _device: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + token(out) +} + +fn forget(this: This, token: u64) { + let mut state = hub(this).state(); + state.callbacks.retain(|r| r.token != token); + state.pending.retain(|e| e.registration.token != token); +} +extern "system" fn stop_callback(this: This, token: u64) { + forget(this, token); +} +/// Stops the callback, then waits up to `timeout` µs for a call of it that +/// is running; false on time-out, or from inside that callback (it cannot +/// wait for itself), as documented. Either way it is never called again. +extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> bool { + forget(this, token); + let hub = hub(this); + let me = std::thread::current().id(); + let deadline = Instant::now().checked_add(Duration::from_micros(timeout)); + let mut state = hub.state(); + loop { + let running = state.running.iter().filter(|r| r.0 == token); + if running.clone().any(|r| r.1 == me) { + return false; + } + if running.count() == 0 { + return true; + } + state = match deadline { + 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; + }; + let waited = hub.returned.wait_timeout(state, left); + waited.unwrap_or_else(PoisonError::into_inner).0 + } + }; + } +} + +/// Dispatcher and aggregate device: no title of ours asks for them. +extern "system" fn create_dispatcher(_: This, out: Out) -> HRESULT { + tracing::warn!("input dispatcher not implemented"); + fail(out, E_NOTIMPL) +} +extern "system" fn create_aggregate(_: This, _kind: u32, out: Out) -> HRESULT { + tracing::warn!("aggregate input device not implemented"); + fail(out, E_NOTIMPL) +} +extern "system" fn find_by_id(this: This, id: *const [u8; 32], out: Out) -> HRESULT { + if id.is_null() || out.is_null() { + return fail(out, E_INVALIDARG); + } + // SAFETY: checked non-null; the title passes a device id. + let id = unsafe { &*id }; + match hub(this).devices.iter().find(|d| d.info.id == *id) { + Some(device) => { + // SAFETY: checked non-null. + unsafe { out.write((device as *const Device).cast()) }; + S_OK + } + None => fail(out, DEVICE_NOT_FOUND), + } +} +/// Lookup by object, platform handle or platform string: our devices have +/// none of these. +extern "system" fn find_device(_: This, _value: *const c_void, out: Out) -> HRESULT { + fail(out, DEVICE_NOT_FOUND) +} +extern "system" fn enable_oem_device( + _: This, + _vendor: u16, + _product: u16, + _interface: u8, + _collection: u8, +) -> HRESULT { + S_OK +} +extern "system" fn set_focus_policy(_: This, _policy: u32) {} + +static INPUT: Table<22> = Table([ + no_interface as *const (), // 0x00 + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release + timestamp as *const (), // 0x18 + current_reading as *const (), // 0x20 + next_reading as *const (), // 0x28 + previous_reading as *const (), // 0x30 + temporal_reading as *const (), // 0x38 + register_reading as *const (), // 0x40 + register_device as *const (), // 0x48 + register_other as *const (), // 0x50 guide button + register_other as *const (), // 0x58 keyboard layout + stop_callback as *const (), // 0x60 + unregister_callback as *const (), // 0x68 + create_dispatcher as *const (), // 0x70 + create_aggregate as *const (), // 0x78 + find_by_id as *const (), // 0x80 + find_device as *const (), // 0x88 by object + find_device as *const (), // 0x90 by platform handle + find_device as *const (), // 0x98 by platform string + enable_oem_device as *const (), // 0xa0 + set_focus_policy as *const (), // 0xa8 +]); + +extern "system" fn device_info(this: *const Device) -> *const DeviceInfo { + // SAFETY: one of our devices. + unsafe { &(*this).info } +} +extern "system" fn device_status(this: *const Device) -> u32 { + // SAFETY: one of our devices. + let device = unsafe { &*this }; + if device.hub().state().slots[device.index].connected { + STATUS_CONNECTED + } else { + 0 + } +} +// 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. +extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { + // SAFETY: one of our devices. + let device = unsafe { &*this }; + if device.index >= PADS { + return; + } + let [low, high, ..] = if params.is_null() { + [0.0; 4] + } else { + // SAFETY: checked non-null; four motor levels. + unsafe { *params } + }; + let speed = |level: f32| (level.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; + lock(&device.hub().source).rumble(device.index, speed(low), speed(high)); +} +extern "system" fn unsupported<const SLOT: usize>(_: *const c_void) -> HRESULT { + tracing::warn!( + slot = format_args!("{SLOT:#x}"), + "input device method not implemented" + ); + E_NOTIMPL +} + +static DEVICE: Table<21> = Table([ + no_interface as *const (), // 0x00 + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release + device_info as *const (), // 0x18 + device_status as *const (), // 0x20 + unsupported::<0x28> as *const (), // battery + unsupported::<0x30> as *const (), // force feedback + unsupported::<0x38> as *const (), // + unsupported::<0x40> as *const (), // + unsupported::<0x48> as *const (), // haptics + set_rumble as *const (), // 0x50 + unsupported::<0x58> as *const (), // input synchronization + unsupported::<0x60> as *const (), // + unsupported::<0x68> as *const (), // power off + unsupported::<0x70> as *const (), // raw device access + unsupported::<0x78> as *const (), // + unsupported::<0x80> as *const (), // + unsupported::<0x88> as *const (), // + unsupported::<0x90> as *const (), // + unsupported::<0x98> as *const (), // + unsupported::<0xa0> as *const (), // +]); + +fn reading<'a>(this: *const Reading) -> &'a Reading { + // SAFETY: a reading we handed out and the title still holds. + unsafe { &*this } +} +extern "system" fn reading_add_ref(this: *const Reading) -> u32 { + reading(this).refs.fetch_add(1, Ordering::Relaxed) + 1 +} +extern "system" fn reading_release(this: *const Reading) -> u32 { + let left = reading(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: the last reference is gone; `Ref::new` boxed it. + drop(unsafe { Box::from_raw(this.cast_mut()) }); + } + left +} +extern "system" fn input_kind(this: *const Reading) -> u32 { + reading(this).kind() +} +extern "system" fn sequence_number(this: *const Reading, kind: u32) -> u64 { + let reading = reading(this); + if reading.kind() & kind != 0 { + reading.sequence + } else { + 0 + } +} +extern "system" fn reading_timestamp(this: *const Reading) -> u64 { + reading(this).timestamp +} +extern "system" fn reading_device(this: *const Reading, out: *mut *const Device) { + if !out.is_null() { + // SAFETY: checked non-null; devices need no reference. + unsafe { out.write(reading(this).device) }; + } +} +extern "system" fn key_count(this: *const Reading) -> u32 { + match &reading(this).value { + Value::Keys(keys) => keys.len() as u32, + Value::Pad(_) => 0, + } +} +extern "system" fn key_state(this: *const Reading, count: u32, out: *mut KeyState) -> u32 { + let Value::Keys(keys) = &reading(this).value else { + return 0; + }; + if out.is_null() { + return 0; + } + let n = keys.len().min(count as usize); + // SAFETY: the title passes room for `count` keys. + unsafe { std::ptr::copy_nonoverlapping(keys.as_ptr(), out, n) }; + n as u32 +} +extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bool { + match &reading(this).value { + Value::Pad(state) if !out.is_null() => { + // SAFETY: checked non-null. + unsafe { out.write(*state) }; + true + } + _ => false, + } +} +/// Kinds our devices do not have: no count, no state. +extern "system" fn nothing(_: *const c_void) -> usize { + 0 +} + +static READING: Table<25> = Table([ + no_interface as *const (), // 0x00 + reading_add_ref as *const (), // 0x08 + reading_release as *const (), // 0x10 + input_kind as *const (), // 0x18 + sequence_number as *const (), // 0x20 + reading_timestamp as *const (), // 0x28 + reading_device as *const (), // 0x30 + nothing as *const (), // 0x38 raw report + nothing as *const (), // 0x40 controller axes, buttons, switches + nothing as *const (), // 0x48 + nothing as *const (), // 0x50 + nothing as *const (), // 0x58 + nothing as *const (), // 0x60 + nothing as *const (), // 0x68 + key_count as *const (), // 0x70 + key_state as *const (), // 0x78 + nothing as *const (), // 0x80 mouse + nothing as *const (), // 0x88 touch + nothing as *const (), // 0x90 + nothing as *const (), // 0x98 motion + nothing as *const (), // 0xa0 arcade stick + nothing as *const (), // 0xa8 flight stick + gamepad_state as *const (), // 0xb0 + nothing as *const (), // 0xb8 racing wheel + nothing as *const (), // 0xc0 UI navigation +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "gameinput", + dlls: &["gameinput.dll"], + // Titles import it by ordinal only. + exports: vec![HleExport { + name: "#1", + address: GameInputCreate as *const () as usize, + }], + } +} + +/// Host input: XInput pads, the keyboard while our process has focus. +#[cfg(windows)] +mod host { + use std::time::{Duration, Instant}; + + use windows_sys::Win32::System::Threading::GetCurrentProcessId; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, + }; + use windows_sys::Win32::UI::Input::XboxController::{ + XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK, + XINPUT_GAMEPAD_DPAD_DOWN, XINPUT_GAMEPAD_DPAD_LEFT, XINPUT_GAMEPAD_DPAD_RIGHT, + XINPUT_GAMEPAD_DPAD_UP, XINPUT_GAMEPAD_LEFT_SHOULDER, XINPUT_GAMEPAD_LEFT_THUMB, + XINPUT_GAMEPAD_RIGHT_SHOULDER, XINPUT_GAMEPAD_RIGHT_THUMB, XINPUT_GAMEPAD_START, + XINPUT_GAMEPAD_X, XINPUT_GAMEPAD_Y, XINPUT_STATE, XINPUT_VIBRATION, XInputGetState, + XInputSetState, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetForegroundWindow, GetWindowThreadProcessId, + }; + + use super::*; + + /// Asking XInput about an empty slot is slow; look again this often. + const EMPTY_SLOT_RECHECK: Duration = Duration::from_secs(1); + + const BUTTONS: [(u16, u32); 14] = [ + (XINPUT_GAMEPAD_START, MENU), + (XINPUT_GAMEPAD_BACK, VIEW), + (XINPUT_GAMEPAD_A, A), + (XINPUT_GAMEPAD_B, B), + (XINPUT_GAMEPAD_X, X), + (XINPUT_GAMEPAD_Y, Y), + (XINPUT_GAMEPAD_DPAD_UP, UP), + (XINPUT_GAMEPAD_DPAD_DOWN, DOWN), + (XINPUT_GAMEPAD_DPAD_LEFT, LEFT), + (XINPUT_GAMEPAD_DPAD_RIGHT, RIGHT), + (XINPUT_GAMEPAD_LEFT_SHOULDER, LEFT_SHOULDER), + (XINPUT_GAMEPAD_RIGHT_SHOULDER, RIGHT_SHOULDER), + (XINPUT_GAMEPAD_LEFT_THUMB, LEFT_STICK), + (XINPUT_GAMEPAD_RIGHT_THUMB, RIGHT_STICK), + ]; + + /// Raw values, no dead zone: titles apply their own. + pub(super) fn convert(pad: &XINPUT_GAMEPAD) -> PadState { + let stick = |v: i16| (f32::from(v) / 32767.0).max(-1.0); + PadState { + buttons: BUTTONS + .iter() + .filter(|(host, _)| pad.wButtons & host != 0) + .fold(0, |all, (_, bit)| all | bit), + left_trigger: f32::from(pad.bLeftTrigger) / 255.0, + right_trigger: f32::from(pad.bRightTrigger) / 255.0, + left_x: stick(pad.sThumbLX), + left_y: stick(pad.sThumbLY), + right_x: stick(pad.sThumbRX), + right_y: stick(pad.sThumbRY), + } + } + + #[derive(Default)] + pub(super) struct Host { + empty_until: [Option<Instant>; PADS], + } + + impl Source for Host { + fn pad(&mut self, slot: usize) -> Option<PadState> { + if self.empty_until[slot].is_some_and(|until| Instant::now() < until) { + return None; + } + let mut state = XINPUT_STATE::default(); + // SAFETY: room for the state. + if unsafe { XInputGetState(slot as u32, &mut state) } != 0 { + self.empty_until[slot] = Some(Instant::now() + EMPTY_SLOT_RECHECK); + return None; + } + self.empty_until[slot] = None; + #[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 (Grand Theft Auto VI'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<KeyState> { + #[cfg(feature = "diagnostics")] + let mut down = scripted(); + #[cfg(not(feature = "diagnostics"))] + let mut down = Vec::new(); + if focused() { + // Left/right modifier keys only, as devices report them; no + // mouse buttons (below 0x08). + let held: Vec<u8> = (0x08..=0xFE_u8) + .filter(|vk| !(0x10..=0x12).contains(vk) && !down.contains(vk)) + // SAFETY: plain queries. + .filter(|&vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0) + .collect(); + down.extend(held); + } + down.into_iter() + .map(|vk| KeyState { + // 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. + ..Default::default() + }) + .collect() + } + + fn rumble(&mut self, slot: usize, low: u16, high: u16) { + let speeds = XINPUT_VIBRATION { + wLeftMotorSpeed: low, + wRightMotorSpeed: high, + }; + // SAFETY: a valid vibration; an empty slot just fails. + unsafe { XInputSetState(slot as u32, &speeds) }; + } + } + + /// Debugging aid: `VICTORY_KEYS=<seconds>:<key>,...` holds each key for + /// 0.2 s that long after input starts, with or without focus. A key is a + /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, + /// `Left`, `Right` (the stand-in pad's table maps them to buttons). + #[cfg(feature = "diagnostics")] + fn scripted() -> Vec<u8> { + static SCRIPT: LazyLock<(Instant, Vec<(Duration, u8)>)> = LazyLock::new(|| { + let list = std::env::var("VICTORY_KEYS").unwrap_or_default(); + let keys = list.split(',').filter_map(|entry| { + let (at, key) = entry.split_once(':')?; + let vk = match key.trim() { + "Enter" => 0x0D, + "Esc" => 0x1B, + "Tab" => 0x09, + "Back" => 0x08, + "Up" => 0x26, + "Down" => 0x28, + "Left" => 0x25, + "Right" => 0x27, + k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => { + k.as_bytes()[0].to_ascii_uppercase() + } + _ => return None, + }; + Some(( + Duration::try_from_secs_f64(at.trim().parse().ok()?).ok()?, + vk, + )) + }); + (Instant::now(), keys.collect()) + }); + let (start, keys) = &*SCRIPT; + let now = start.elapsed(); + keys.iter() + .filter(|&&(at, _)| (at..at + Duration::from_millis(200)).contains(&now)) + .map(|&(_, vk)| vk) + .collect() + } + + /// The foreground window is one of ours (the title's or our fallback). + fn focused() -> bool { + let mut process = 0; + // SAFETY: plain queries; a null window gives process 0. + unsafe { + GetWindowThreadProcessId(GetForegroundWindow(), &mut process); + process == GetCurrentProcessId() + } + } + + #[test] + fn host_pads_convert_to_console_pads() { + let pad = XINPUT_GAMEPAD { + wButtons: XINPUT_GAMEPAD_A | XINPUT_GAMEPAD_START | XINPUT_GAMEPAD_DPAD_LEFT, + bLeftTrigger: 255, + sThumbLX: -32768, + sThumbLY: 32767, + ..Default::default() + }; + let state = convert(&pad); + assert_eq!(state.buttons, A | MENU | LEFT); + assert_eq!( + ( + state.left_trigger, + state.left_x, + state.left_y, + state.right_x + ), + (1.0, -1.0, 1.0, 0.0) + ); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::HleResolver; + use crate::HostPolicy; + use victory_loader::Provenance; + use victory_pe::ImportSymbol; + + #[derive(Default)] + struct FakeHost { + pads: [Option<PadState>; PADS], + keys: Vec<KeyState>, + rumble: Vec<(usize, u16, u16)>, + } + + struct Fake(Arc<Mutex<FakeHost>>); + + impl Source for Fake { + fn pad(&mut self, slot: usize) -> Option<PadState> { + self.0.lock().unwrap().pads[slot] + } + fn keys(&mut self) -> Vec<KeyState> { + self.0.lock().unwrap().keys.clone() + } + fn rumble(&mut self, slot: usize, low: u16, high: u16) { + self.0.lock().unwrap().rumble.push((slot, low, high)); + } + } + + fn fake() -> (&'static Hub, Arc<Mutex<FakeHost>>) { + let host = Arc::new(Mutex::new(FakeHost::default())); + let hub = Hub::new(Box::new(Fake(Arc::clone(&host)))); + hub.poll(); + (hub, host) + } + + fn key(virtual_key: u8) -> KeyState { + KeyState { + scan_code: u32::from(virtual_key) + 0x100, + virtual_key, + ..Default::default() + } + } + + fn slot<F: Copy, T>(object: *const T, offset: usize) -> F { + // SAFETY: our objects start with their table, which has the slot. + let f = unsafe { *(*(object as *const *const *const ())).add(offset / 8) }; + // SAFETY: the caller names the slot's signature. + unsafe { std::mem::transmute_copy(&f) } + } + + /// Device callbacks seen: device index, current and previous status. + type Log = Mutex<Vec<(usize, u32, u32)>>; + + extern "system" fn record( + _token: u64, + context: *mut c_void, + device: *const Device, + _timestamp: u64, + current: u32, + previous: u32, + ) { + // SAFETY: the test passes its log and one of the hub's devices. + let (log, index) = unsafe { (&*(context as *const Log), (*device).index) }; + log.lock().unwrap().push((index, current, previous)); + } + + fn register(hub: &Hub, kind: u32, enumeration: u32, log: &Log) -> u64 { + type Register = extern "system" fn( + This, + *const Device, + u32, + u32, + u32, + *mut c_void, + Option<DeviceCallback>, + *mut u64, + ) -> HRESULT; + let mut token = 0; + let context = log as *const Log as *mut c_void; + let register = slot::<Register, _>(&hub.object, 0x48); + let hr = register( + &hub.object, + std::ptr::null(), + kind, + 1, + enumeration, + context, + Some(record), + &mut token, + ); + assert_eq!(hr, S_OK); + assert_ne!(token, 0); + token + } + + fn result(hr: HRESULT, out: *const c_void) -> Result<*const Reading, HRESULT> { + if hr == S_OK { + Ok(out.cast()) + } else { + assert!(out.is_null()); + Err(hr) + } + } + + fn current(hub: &Hub, kind: u32, device: usize) -> Result<*const Reading, HRESULT> { + type Current = extern "system" fn(This, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let hr = slot::<Current, _>(&hub.object, 0x20)( + &hub.object, + kind, + &hub.devices[device], + &mut out, + ); + result(hr, out) + } + + fn walk(hub: &Hub, offset: usize, from: *const Reading) -> Result<*const Reading, HRESULT> { + type Walk = extern "system" fn(This, *const Reading, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let device = reading(from).device; + let hr = + slot::<Walk, _>(&hub.object, offset)(&hub.object, from, GAMEPAD_KIND, device, &mut out); + result(hr, out) + } + + fn pad(reading: *const Reading) -> PadState { + let mut state = PadState::default(); + let get = + slot::<extern "system" fn(*const Reading, *mut PadState) -> bool, _>(reading, 0xb0); + assert!(get(reading, &mut state)); + state + } + + fn stamp(reading: *const Reading) -> (u64, u64) { + let time = slot::<extern "system" fn(*const Reading) -> u64, _>(reading, 0x28); + let sequence = slot::<extern "system" fn(*const Reading, u32) -> u64, _>(reading, 0x20); + (time(reading), sequence(reading, GAMEPAD_KIND)) + } + + fn release(reading: *const Reading) { + slot::<extern "system" fn(*const Reading) -> u32, _>(reading, 0x10)(reading); + } + + #[test] + fn ordinal_one_resolves_to_create() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("GameInput.dll", &ImportSymbol::Ordinal(1)), + Some(Provenance::Hle) + ); + assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None); + } + + #[test] + fn pads_connect_report_and_disconnect() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, GAMEPAD_KIND, 2, &log); + // Blocking enumeration ran before registration returned: with no + // host pad the keyboard's stand-in is the only one. + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + host.lock().unwrap().pads[1] = Some(PadState { + buttons: A, + left_x: 0.5, + ..Default::default() + }); + hub.poll(); + assert_eq!( + log.lock().unwrap()[1..], + [(1, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] + ); + + let first = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(pad(first).buttons, A); + assert_eq!(pad(first).left_x, 0.5); + // No change, no new reading. + hub.poll(); + let again = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(again, first); + release(again); + + std::thread::sleep(Duration::from_millis(2)); + host.lock().unwrap().pads[1].as_mut().unwrap().buttons = B; + hub.poll(); + let second = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(pad(second).buttons, B); + let (t1, s1) = stamp(first); + let (t2, s2) = stamp(second); + assert!(t2 > t1 && s2 == s1 + 1); + assert!(t2 <= now()); + + // The title's edge check: previous of current, and back again. + assert_eq!(walk(hub, 0x30, second), Ok(first)); + assert_eq!(walk(hub, 0x28, first), Ok(second)); + assert_eq!(walk(hub, 0x28, second), Err(READING_NOT_FOUND)); + assert_eq!(walk(hub, 0x30, first), Err(READING_NOT_FOUND)); + for r in [first, first, second, second] { + release(r); + } + + host.lock().unwrap().pads[1] = None; + hub.poll(); + assert_eq!( + log.lock().unwrap()[3..], + [(1, 0, STATUS_CONNECTED), (FALLBACK, STATUS_CONNECTED, 0)] + ); + assert_eq!(current(hub, GAMEPAD_KIND, 1), Err(DEVICE_DISCONNECTED)); + // The stand-in is back, at rest. + let rest = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(rest), PadState::default()); + release(rest); + } + + #[test] + fn keys_feed_the_keyboard_and_the_stand_in_pad() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, KEYBOARD_KIND, 2, &log); + assert_eq!(*log.lock().unwrap(), [(KEYBOARD, STATUS_CONNECTED, 0)]); + + let keys = vec![key(b'W'), key(0x0D), key(b'L'), key(b'C')]; + host.lock().unwrap().keys = keys.clone(); + hub.poll(); + let r = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap(); + let count = slot::<extern "system" fn(*const Reading) -> u32, _>(r, 0x70); + let state = + slot::<extern "system" fn(*const Reading, u32, *mut KeyState) -> u32, _>(r, 0x78); + assert_eq!(count(r), 4); + let mut got = [KeyState::default(); 8]; + assert_eq!(state(r, 8, got.as_mut_ptr()), 4); + assert_eq!(got[..4], keys[..]); + release(r); + + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!( + pad(r), + PadState { + buttons: A, + left_y: 1.0, + right_x: 1.0, + right_trigger: 1.0, + ..Default::default() + } + ); + release(r); + // A keyboard reading is no gamepad reading. + assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND)); + } + + #[test] + fn async_enumeration_waits_for_the_poll_and_unregistering_stops_callbacks() { + let (hub, host) = fake(); + let log = Log::default(); + let token = register(hub, GAMEPAD_KIND, ASYNC_ENUMERATION, &log); + assert!(log.lock().unwrap().is_empty()); + hub.poll(); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(&hub.object, 0x68); + assert!(unregister(&hub.object, token, 5000)); + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + assert_eq!(log.lock().unwrap().len(), 1); + } + + #[test] + fn unregistering_waits_for_a_running_callback() { + use std::sync::atomic::AtomicBool; + static INSIDE: AtomicBool = AtomicBool::new(false); + static LEAVE: AtomicBool = AtomicBool::new(false); + static FROM_INSIDE: AtomicU32 = AtomicU32::new(0); + extern "system" fn slow( + token: u64, + context: *mut c_void, + _: *const Device, + _: u64, + _: u32, + _: u32, + ) { + // From inside its own callback, unregistering fails at once. + let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(context, 0x68); + if !unregister(context.cast(), token, 0) { + FROM_INSIDE.fetch_add(1, Ordering::SeqCst); + } + INSIDE.store(true, Ordering::SeqCst); + while !LEAVE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + } + let (hub, host) = fake(); + type Register = extern "system" fn( + This, + *const Device, + u32, + u32, + u32, + *mut c_void, + Option<DeviceCallback>, + *mut u64, + ) -> HRESULT; + let register = slot::<Register, _>(&hub.object, 0x48); + 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), + S_OK + ); + host.lock().unwrap().pads[1] = Some(PadState::default()); + let poller = std::thread::spawn(|| hub.poll()); + while !INSIDE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(&hub.object, 0x68); + 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); + }); + let start = Instant::now(); + assert!(unregister(&hub.object, token, u64::MAX), "waits for it"); + assert!(start.elapsed() >= Duration::from_millis(40)); + assert_eq!(FROM_INSIDE.load(Ordering::SeqCst), 1); + poller.join().unwrap(); + leave.join().unwrap(); + } + + #[test] + fn devices_are_found_by_id_and_rumble_reaches_the_host() { + let (hub, host) = fake(); + host.lock().unwrap().pads[2] = Some(PadState::default()); + hub.poll(); + let device = &hub.devices[2] as *const Device; + let info = slot::<extern "system" fn(*const Device) -> *const u8, _>(device, 0x18); + // SAFETY: the info has the id at +0x20. + let id = unsafe { *(info(device).add(0x20) as *const [u8; 32]) }; + assert_ne!(id, [0; 32]); + + type Find = extern "system" fn(This, *const [u8; 32], Out) -> HRESULT; + let find = slot::<Find, _>(&hub.object, 0x80); + let mut out = std::ptr::null(); + assert_eq!(find(&hub.object, &id, &mut out), S_OK); + assert_eq!(out, device.cast()); + assert_eq!(find(&hub.object, &[1; 32], &mut out), DEVICE_NOT_FOUND); + assert!(out.is_null()); + + type Rumble = extern "system" fn(*const Device, *const [f32; 4]); + let rumble = slot::<Rumble, _>(device, 0x50); + rumble(device, &[0.5, 1.0, 1.0, 1.0]); + rumble(&hub.devices[FALLBACK], &[1.0; 4]); + rumble(device, std::ptr::null()); + assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); + } +} diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs new file mode 100644 index 000000000..3ab306712 --- /dev/null +++ b/crates/victory-hle/src/modules/kernel.rs @@ -0,0 +1,687 @@ +//! Overrides of shared Windows APIs whose console meaning differs. +//! +//! Only the differences live here; everything else passes through to the +//! host (see `HostPolicy`). +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_void}; + +use crate::{HleModule, HostPolicy, hle_export, registry, runtime}; + +/// `GetModuleHandleW(NULL)` must return the title's image, not our exe; +/// title images and our console modules are found by name. +pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void { + if name.is_null() { + return runtime::main_image().unwrap_or(0) as *mut c_void; + } + find_module(&wide(name), false).unwrap_or_else(|| host::get_module_handle_w(name)) +} + +/// See [`GetModuleHandleW`]. +pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void { + if name.is_null() { + return runtime::main_image().unwrap_or(0) as *mut c_void; + } + find_module(&narrow(name), false).unwrap_or_else(|| host::get_module_handle_a(name)) +} + +/// A NUL-terminated string from the title. +fn narrow(text: *const u8) -> String { + // SAFETY: the title passes a NUL-terminated string. + unsafe { CStr::from_ptr(text.cast()) } + .to_string_lossy() + .into_owned() +} + +/// See [`narrow`]. +fn wide(text: *const u16) -> String { + // SAFETY: the title passes a NUL-terminated string. + unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + } +} + +/// A title image's path is its original file, not our cache copy; +/// `NULL` means the title's exe. +pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, size: u32) -> u32 { + let Some(path) = title_path(module) else { + return host::get_module_file_name_w(module, out, size); + }; + let wide: Vec<u16> = path.encode_utf16().collect(); + // SAFETY: the title passes a buffer of `size` characters. + copy_truncated(&wide, unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) +} + +/// See [`GetModuleFileNameW`]. +pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, size: u32) -> u32 { + let Some(path) = title_path(module) else { + return host::get_module_file_name_a(module, out, size); + }; + // SAFETY: the title passes a buffer of `size` bytes. + copy_truncated(path.as_bytes(), unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) +} + +fn title_path(module: *mut c_void) -> Option<String> { + let base = if module.is_null() { + runtime::main_image()? + } else { + module as usize + }; + Some(runtime::image_path(base)?.to_string_lossy().into_owned()) +} + +/// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit, +/// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return +/// the buffer size. +fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 { + let Some(room) = out.len().checked_sub(1) else { + host::set_last_error(ERROR_INSUFFICIENT_BUFFER); + return 0; + }; + let n = text.len().min(room); + out[..n].copy_from_slice(&text[..n]); + out[n] = T::default(); + if n < text.len() { + host::set_last_error(ERROR_INSUFFICIENT_BUFFER); + return out.len() as u32; + } + n as u32 +} + +const ERROR_INSUFFICIENT_BUFFER: u32 = 122; + +/// Console-only DLLs we implement load as a pseudo handle (titles load +/// `xgameruntime.dll` this way), the title's DLLs as the images we map +/// (on first use if nothing imports them); anything else loads on the host. +pub extern "system" fn LoadLibraryExA( + name: *const u8, + file: *mut c_void, + flags: u32, +) -> *mut c_void { + if !name.is_null() + && let Some(handle) = find_module(&narrow(name), runs_code(flags)) + { + return handle; + } + host::load_library_ex_a(name, file, flags) +} + +/// See [`LoadLibraryExA`]. +pub extern "system" fn LoadLibraryExW( + name: *const u16, + file: *mut c_void, + flags: u32, +) -> *mut c_void { + if !name.is_null() + && let Some(handle) = find_module(&wide(name), runs_code(flags)) + { + return handle; + } + host::load_library_ex_w(name, file, flags) +} + +/// False for loads as data or resources (`DONT_RESOLVE_DLL_REFERENCES`, +/// `LOAD_LIBRARY_AS_DATAFILE(_EXCLUSIVE)`, `AS_IMAGE_RESOURCE`): those run +/// no code, so a title DLL we have not mapped can go to the host. +fn runs_code(flags: u32) -> bool { + flags & (0x1 | 0x2 | 0x20 | 0x40) == 0 +} + +pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void { + LoadLibraryExA(name, std::ptr::null_mut(), 0) +} + +pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void { + LoadLibraryExW(name, std::ptr::null_mut(), 0) +} + +/// Looks up our implementations behind a pseudo handle; real modules go to +/// the host. +pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void { + // `NULL` is the process's exe, which for the title is its own image. + let module = if module.is_null() { + runtime::main_image().unwrap_or(0) as *mut c_void + } else { + module + }; + let Some(m) = registry().iter().find(|m| handle(m) == module) else { + return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name)); + }; + // Values below 0x10000 are ordinals; we export by name only. + if (name as usize) < 0x1_0000 { + tracing::warn!( + module = m.name, + ordinal = name as usize, + "GetProcAddress by ordinal" + ); + return std::ptr::null_mut(); + } + // SAFETY: not an ordinal, so the title passes a NUL-terminated name. + let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); + match m.exports.iter().find(|e| e.name == name) { + Some(e) => e.address as *mut c_void, + None => { + tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented"); + std::ptr::null_mut() + } + } +} + +/// What a host module's `name` (or ordinal) is bound to at import binding +/// when we override it: a title that looks a function up by name must not +/// get past our overrides (the network guard, path rewriting). +fn host_override(module: *mut c_void, name: *const u8) -> Option<*mut c_void> { + if module.is_null() || runtime::image_path(module as usize).is_some() { + return None; + } + let symbol = if (name as usize) < 0x1_0000 { + format!("#{}", name as usize) + } else { + narrow(name) + }; + let mut path = [0u16; 260]; + let len = host::get_module_file_name_w(module, path.as_mut_ptr(), path.len() as u32) as usize; + let path = String::from_utf16_lossy(&path[..len.min(path.len())]); + let file = path.rsplit('\\').next()?; + crate::registry::lookup(file, &symbol).map(|address| address as *mut c_void) +} + +/// Our pseudo modules and the title's images stay loaded: `LoadLibrary` +/// took no reference on them, so the host's count must not drop. +pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { + if registry().iter().any(|m| handle(m) == module) + || runtime::image_path(module as usize).is_some() + { + return 1; + } + host::free_library(module) +} + +/// Title images hear of thread starts and ends from us, not from the +/// Windows loader (`victory_loader::disable_thread_calls`). +pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 { + host::disable_thread_library_calls(module) +} + +/// Title debug output goes to our log (no debugger needs to be attached). +pub extern "system" fn OutputDebugStringA(text: *const u8) { + if !text.is_null() { + let text = narrow(text); + host::note_title_output(text.trim()); + tracing::info!(target: "title", "{}", text.trim_end()); + } +} + +/// See [`OutputDebugStringA`]. +pub extern "system" fn OutputDebugStringW(text: *const u16) { + if !text.is_null() { + let text = wide(text); + host::note_title_output(text.trim()); + tracing::info!(target: "title", "{}", text.trim_end()); + } +} + +/// The CRT's `exit`, through which the title's entry point returns: logs +/// the code and the caller, then exits on the host. +pub extern "C" fn exit(code: i32) -> ! { + tracing::warn!(code, from = %host::callers(), "title exits"); + host::exit(code) +} + +/// The CRT's `abort` (also reached from `terminate`): logged like [`exit`]. +pub extern "C" fn abort() -> ! { + tracing::error!(from = %host::callers(), "title aborts"); + host::abort() +} + +/// The CRT's `terminate` and the STL's invalid-argument exit: logged, then +/// the host's `abort`. +pub extern "C" fn terminate() -> ! { + tracing::error!(from = %host::callers(), "title calls terminate"); + host::abort() +} + +/// See [`terminate`]. +pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! { + tracing::error!(from = %host::callers(), "title passed an invalid parameter"); + host::abort() +} + +/// The title's unhandled-exception filter. Ours stands in front of it and +/// reports the crash first; the title still gets its own back. +static TITLE_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize { + host::set_unhandled_exception_filter(report_unhandled); + TITLE_FILTER.swap(filter, std::sync::atomic::Ordering::AcqRel) +} + +extern "system" fn report_unhandled(info: *const c_void) -> i32 { + host::report_unhandled(info); + match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { + 0 => 0, // EXCEPTION_CONTINUE_SEARCH + filter => { + type Filter = extern "system" fn(*const c_void) -> i32; + // SAFETY: the title registered this filter. + let filter: Filter = unsafe { std::mem::transmute(filter) }; + filter(info) + } + } +} + +/// See [`exit`]; only the current process is logged. +pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 { + if process as isize == -1 { + tracing::warn!(code, from = %host::callers(), "title terminates the process"); + } + host::terminate_process(process, code) +} + +/// The pseudo handle of one of our modules: its address, never a real image. +fn handle(m: &HleModule) -> *mut c_void { + m as *const HleModule as *mut c_void +} + +/// The title's images and our console modules by name; `None` leaves the +/// name to the host, which only DLLs `HostPolicy` passes through get (as at +/// import binding); others fail. With `load`, a title DLL not mapped yet is +/// mapped now. +fn find_module(path: &str, load: bool) -> Option<*mut c_void> { + let file = path.rsplit(['\\', '/']).next().unwrap_or(path); + // As the Windows loader does, a name without extension means a DLL. + let file = if file.contains('.') { + file.to_owned() + } else { + format!("{file}.dll") + }; + // Loads go through the title DLL loader first: it waits for a DLL that + // another thread is still initialising, as the Windows loader lock does. + if load { + match runtime::load_title_dll(&file) { + Ok(Some(base)) => return Some(base as *mut c_void), + Ok(None) => {} + // Not the host: it would load the unpatched DLL from the title's folder. + Err(error) => { + tracing::error!(dll = file, %error, "mapping a title DLL failed"); + host::set_last_error(ERROR_MOD_NOT_FOUND); + return Some(std::ptr::null_mut()); + } + } + } + if let Some(base) = runtime::image_named(&file) { + return Some(base as *mut c_void); + } + // DLLs the host has too are real host modules, whatever `--strict` says. + let host_dll = HostPolicy::default().allows(&file); + if !host_dll && let Some(m) = registry().iter().find(|m| m.serves(&file)) { + if load { + tracing::info!(dll = file, "loaded as a pseudo module"); + } + return Some(handle(m)); + } + if host_dll { + return None; + } + // Any other host DLL (wininet, urlmon, ...) is beyond what we guard, and + // the console does not have it. + refuse(&file); + host::set_last_error(ERROR_MOD_NOT_FOUND); + Some(std::ptr::null_mut()) +} + +/// Logs a DLL name the title is refused, once. +fn refuse(file: &str) { + static REFUSED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); + let file = file.to_ascii_lowercase(); + let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); + if !refused.contains(&file) { + tracing::warn!(dll = file, "a host DLL outside the host policy: refused"); + refused.push(file); + } +} + +const ERROR_MOD_NOT_FOUND: u32 = 126; + +pub(crate) fn module() -> HleModule { + HleModule { + name: "kernel", + dlls: &[ + "kernel32.dll", + "kernelbase.dll", + "api-ms-win-core-libraryloader-*", + "api-ms-win-core-processthreads-*", + "api-ms-win-core-debug-*", + "api-ms-win-core-errorhandling-*", + "api-ms-win-crt-runtime-*", + ], + exports: vec![ + hle_export!(GetModuleHandleW), + hle_export!(GetModuleHandleA), + hle_export!(GetModuleFileNameW), + hle_export!(GetModuleFileNameA), + hle_export!(LoadLibraryExA), + hle_export!(LoadLibraryExW), + hle_export!(LoadLibraryA), + hle_export!(LoadLibraryW), + hle_export!(GetProcAddress), + hle_export!(FreeLibrary), + hle_export!(DisableThreadLibraryCalls), + hle_export!(OutputDebugStringA), + hle_export!(OutputDebugStringW), + hle_export!(exit), + hle_export!(abort), + hle_export!(terminate), + hle_export!(_invalid_parameter_noinfo_noreturn), + hle_export!(TerminateProcess), + hle_export!(SetUnhandledExceptionFilter), + ], + } +} + +/// The return addresses above the caller, as `module+rva`, for logs. +#[cfg(feature = "diagnostics")] +pub(crate) fn callers() -> String { + host::callers() +} + +#[cfg(windows)] +mod host { + use std::ffi::c_void; + + use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError}; + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + use windows_sys::Win32::System::LibraryLoader::{ + DisableThreadLibraryCalls, GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, + GetModuleHandleW, GetProcAddress, LoadLibraryExA, LoadLibraryExW, + }; + use windows_sys::Win32::System::Threading::TerminateProcess; + + unsafe extern "C" { + #[link_name = "exit"] + fn crt_exit(code: i32) -> !; + #[link_name = "abort"] + fn crt_abort() -> !; + } + + // SAFETY (every function): forwarding the title's own arguments to the + // host API of the same name. + + pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void { + // SAFETY: see above. + unsafe { GetModuleHandleW(name) } + } + + pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void { + // SAFETY: see above. + unsafe { GetModuleHandleA(name) } + } + + pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 { + // SAFETY: see above. + unsafe { GetModuleFileNameW(module, out, size) } + } + + pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 { + // SAFETY: see above. + unsafe { GetModuleFileNameA(module, out, size) } + } + + pub(super) fn set_last_error(code: u32) { + // SAFETY: see above. + unsafe { SetLastError(code) } + } + + pub(super) fn load_library_ex_a(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void { + // SAFETY: see above. + unsafe { LoadLibraryExA(name, file, flags) } + } + + pub(super) fn load_library_ex_w( + name: *const u16, + file: *mut c_void, + flags: u32, + ) -> *mut c_void { + // SAFETY: see above. + unsafe { LoadLibraryExW(name, file, flags) } + } + + pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void { + // SAFETY: see above. + unsafe { GetProcAddress(module, name) }.map_or(std::ptr::null_mut(), |f| f as *mut c_void) + } + + pub(super) fn free_library(module: *mut c_void) -> i32 { + // SAFETY: see above. + unsafe { FreeLibrary(module) } + } + + pub(super) fn disable_thread_library_calls(module: *mut c_void) -> i32 { + match victory_loader::disable_thread_calls(module as usize) { + Some(done) => i32::from(done), + // SAFETY: see above. + None => unsafe { DisableThreadLibraryCalls(module) }, + } + } + + pub(super) fn exit(code: i32) -> ! { + // SAFETY: see above. + unsafe { crt_exit(code) } + } + + pub(super) fn abort() -> ! { + // SAFETY: see above. + unsafe { crt_abort() } + } + + pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 { + // SAFETY: see above. + unsafe { TerminateProcess(process, code) } + } + + pub(super) fn set_unhandled_exception_filter(filter: extern "system" fn(*const c_void) -> i32) { + // SAFETY: our filter takes the exception pointers as an opaque pointer. + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter( + std::mem::transmute::< + extern "system" fn(*const c_void) -> i32, + windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER, + >(filter), + ) + }; + } + + pub(super) fn report_unhandled(info: *const c_void) { + // SAFETY: the system's exception pointers, passed to the filter. + unsafe { victory_loader::report_unhandled(info.cast()) }; + } + + pub(super) fn note_title_output(line: &str) { + victory_loader::note_title_output(line); + } + + /// Our caller's callers, as `module+rva`. + pub(super) fn callers() -> String { + let mut frames = [std::ptr::null_mut(); 12]; + // SAFETY: fills at most `frames.len()` return addresses. + let n = unsafe { + RtlCaptureStackBackTrace( + 2, + frames.len() as u32, + frames.as_mut_ptr(), + std::ptr::null_mut(), + ) + }; + let names: Vec<_> = frames[..usize::from(n)] + .iter() + .map(|&f| victory_loader::locate(f as usize)) + .collect(); + names.join(" < ") + } +} + +#[cfg(not(windows))] +mod host { + use std::ffi::c_void; + + pub(super) fn get_module_handle_w(_: *const u16) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn load_library_ex_a(_: *const u8, _: *mut c_void, _: u32) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_module_file_name_w(_: *mut c_void, _: *mut u16, _: u32) -> u32 { + 0 + } + + pub(super) fn get_module_file_name_a(_: *mut c_void, _: *mut u8, _: u32) -> u32 { + 0 + } + + pub(super) fn set_last_error(_: u32) {} + + pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_proc_address(_: *mut c_void, _: *const u8) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn free_library(_: *mut c_void) -> i32 { + 0 + } + + pub(super) fn disable_thread_library_calls(_: *mut c_void) -> i32 { + 0 + } + + pub(super) fn exit(code: i32) -> ! { + std::process::exit(code) + } + + pub(super) fn abort() -> ! { + std::process::abort() + } + + pub(super) fn terminate_process(_: *mut c_void, code: u32) -> i32 { + std::process::exit(code as i32) + } + + pub(super) fn set_unhandled_exception_filter(_: extern "system" fn(*const c_void) -> i32) {} + + pub(super) fn report_unhandled(_: *const c_void) {} + + pub(super) fn note_title_output(_: &str) {} + + pub(super) fn callers() -> String { + String::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + 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")); + let module = base as *mut c_void; + let mut buf = [0xFFFFu16; 32]; + let n = GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32); + assert_eq!( + String::from_utf16_lossy(&buf[..n as usize]), + r"C:\title\game.exe" + ); + assert_eq!(buf[n as usize], 0); + + // Too small: truncated, NUL-terminated, the buffer size returned. + let mut small = [0u8; 4]; + assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4); + assert_eq!(&small, &[b'C', b':', b'\\', 0]); + } + + fn w(text: &str) -> Vec<u16> { + text.encode_utf16().chain(Some(0)).collect() + } + + #[cfg(windows)] + #[test] + fn host_lookups_by_name_get_our_overrides() { + let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr()); + assert!(!kernel32.is_null()); + let ours = crate::registry::lookup("kernel32.dll", "CreateFileW").unwrap(); + assert_eq!( + GetProcAddress(kernel32, c"CreateFileW".as_ptr().cast()) as usize, + ours + ); + // A plain name stays the host's. + let host = host::get_proc_address(kernel32, c"GetTickCount".as_ptr().cast()); + assert!(!host.is_null()); + assert_eq!( + GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()), + host + ); + // Host DLLs outside the host policy do not exist for the title. + assert!(LoadLibraryW(w("wininet.dll").as_ptr()).is_null()); + assert!(LoadLibraryA(c"C:\\Windows\\System32\\urlmon".as_ptr().cast()).is_null()); + assert!(GetModuleHandleW(w("WININET.DLL").as_ptr()).is_null()); + assert_eq!( + // SAFETY: reads this thread's last error. + unsafe { windows_sys::Win32::Foundation::GetLastError() }, + ERROR_MOD_NOT_FOUND + ); + assert!(!LoadLibraryW(w("kernel32").as_ptr()).is_null()); + // By ordinal too (ws2_32 #4 is `connect`). + let ws2 = LoadLibraryW(w("ws2_32.dll").as_ptr()); + assert_eq!( + GetProcAddress(ws2, 4 as *const u8) as usize, + crate::registry::lookup("ws2_32.dll", "connect").unwrap() + ); + } + + #[test] + 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")); + runtime::set_title_dll_loader(Box::new(|file| match file { + "late.dll" => Ok(Some(0x7200_0000_0000)), + "broken.dll" => Err("bad image".into()), + _ => Ok(None), + })); + let mapped = base as *mut c_void; + assert_eq!(GetModuleHandleW(w("MAPPED").as_ptr()), mapped); + assert_eq!(GetModuleHandleA(c"sub\\mapped.dll".as_ptr().cast()), mapped); + assert_eq!(LoadLibraryW(w("mapped.dll").as_ptr()), mapped); + assert_eq!(FreeLibrary(mapped), 1, "title images stay loaded"); + + // Not mapped yet: `LoadLibrary` maps it, `GetModuleHandle` does not. + assert!(GetModuleHandleW(w("late.dll").as_ptr()).is_null()); + assert_eq!( + LoadLibraryA(c"late".as_ptr().cast()) as usize, + 0x7200_0000_0000 + ); + assert!(LoadLibraryA(c"broken.dll".as_ptr().cast()).is_null()); + // As data it runs no code, so the host loads it (and finds nothing). + let data = LoadLibraryExW(w("late.dll").as_ptr(), std::ptr::null_mut(), 0x2); + assert_ne!(data as usize, 0x7200_0000_0000); + + let runtime = LoadLibraryA(c"xgameruntime.dll".as_ptr().cast()); + assert!(!runtime.is_null()); + assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime); + } +} diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs new file mode 100644 index 000000000..4eb9649a3 --- /dev/null +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -0,0 +1,438 @@ +//! The title's life cycle. A console title is never told it is closing: +//! quitting it or launching a new game first suspends it (its suspend +//! routines run, and it has a second to save) and then ends the process. +//! Closing the title's window does the same here; a new launch then starts +//! `victory` again, which waits for this process to be gone. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; + +use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; +use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU}; +use windows_sys::core::{PCSTR, PCWSTR, w}; + +use crate::{HleModule, hle_export}; + +type Routine = extern "system" fn(quiesced: u8, context: *mut c_void); + +/// Registration id, routine and context of each suspend routine. +static ROUTINES: Mutex<Vec<(usize, Routine, usize)>> = Mutex::new(Vec::new()); + +fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> { + ROUTINES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// How long the console lets suspend routines run before it ends the title. +const SUSPEND_DEADLINE: Duration = Duration::from_secs(1); + +const ERROR_INVALID_PARAMETER: u32 = 87; + +pub extern "system" fn RegisterAppStateChangeNotification( + routine: Option<Routine>, + context: *mut c_void, + registration: *mut usize, +) -> u32 { + let Some(routine) = routine else { + return ERROR_INVALID_PARAMETER; + }; + if registration.is_null() { + return ERROR_INVALID_PARAMETER; + } + static NEXT: AtomicUsize = AtomicUsize::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + routines().push((id, routine, context as usize)); + // SAFETY: checked non-null; the title passes room for its registration. + unsafe { registration.write(id) }; + 0 +} + +pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) { + routines().retain(|&(id, ..)| id != registration); +} + +/// The window procedure a title window had before ours. +const TITLE_PROC: PCWSTR = w!("victory.wndproc"); + +pub extern "system" fn CreateWindowExW( + ex_style: u32, + class: PCWSTR, + name: PCWSTR, + style: u32, + x: i32, + y: i32, + width: i32, + height: i32, + parent: HWND, + menu: HMENU, + instance: HINSTANCE, + param: *const c_void, +) -> HWND { + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). + let hwnd = unsafe { + wm::CreateWindowExW( + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ) + }; + hook(hwnd); + hwnd +} + +/// See [`CreateWindowExW`]. +pub extern "system" fn CreateWindowExA( + ex_style: u32, + class: PCSTR, + name: PCSTR, + style: u32, + x: i32, + y: i32, + width: i32, + height: i32, + parent: HWND, + menu: HMENU, + instance: HINSTANCE, + param: *const c_void, +) -> HWND { + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). + let hwnd = unsafe { + wm::CreateWindowExA( + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ) + }; + hook(hwnd); + 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 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). +fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) { + let mut area = RECT::default(); + // SAFETY: `area` receives the primary monitor's work area. + let known = + unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) }; + let fitted = fit_into(&area, width, height); + if !parent.is_null() || known == 0 || fitted == (width, height) { + return (x, y, width, height); + } + tracing::info!(width, height, to = ?fitted, "title window fitted to the screen"); + let (w, h) = fitted; + let left = area.left + (area.right - area.left - w) / 2; + let top = area.top + (area.bottom - area.top - h) / 2; + (left, top, w, h) +} + +/// `width` x `height` scaled down to fit `area`, or unchanged if it fits +/// (or is `CW_USEDEFAULT`). +fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { + let (aw, ah) = (area.right - area.left, area.bottom - area.top); + if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) { + return (width, height); + } + let scale = f64::min( + f64::from(aw) / f64::from(width), + f64::from(ah) / f64::from(height), + ); + ( + (f64::from(width) * scale) as i32, + (f64::from(height) * scale) as i32, + ) +} + +/// Puts our procedure in front of the title's. +fn hook(hwnd: HWND) { + if hwnd.is_null() { + return; + } + // SAFETY: a window this thread just created. The title's procedure is + // stored before ours can run. + unsafe { + let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC); + wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void); + wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize); + } +} + +extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + // A user close (close button, Alt+F4, window or taskbar menu); a + // console title never sees one, nor a WM_CLOSE from it. + if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize { + end_title("window closed", Box::new(|| {})); + return 0; + } + // 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 + // menu. The mouse still opens it from the title bar. + if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { + return 0; + } + // SAFETY: the procedure `hook` stored, called the way the system would. + unsafe { + let title = wm::GetPropW(hwnd, TITLE_PROC); + if message == wm::WM_NCDESTROY { + wm::RemovePropW(hwnd, TITLE_PROC); + } + let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title); + wm::CallWindowProcW(title, hwnd, message, wparam, lparam) + } +} + +/// Suspends the title as the console does when it ends it, runs `then` +/// (once), then ends the process. Returns at once; later calls do nothing. +pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) { + static ENDING: AtomicBool = AtomicBool::new(false); + if ENDING.swap(true, Ordering::SeqCst) { + return; + } + let suspend = routines().clone(); + tracing::info!(routines = suspend.len(), "{why}: suspending the title"); + // Whoever comes first (the routines or the deadline) runs `then`; the + // other waits for it, so the process never ends halfway through. + let then = std::sync::Arc::new(Mutex::new(Some(then))); + let finish = move |how: &str| { + let mut then = then.lock().unwrap_or_else(|e| e.into_inner()); + tracing::info!("{how}; ending the title"); + if let Some(then) = then.take() { + then(); + } + end(); + }; + let late = finish.clone(); + // Not on the calling thread: titles hand the suspend to their window + // thread and wait for it inside the routine. + std::thread::spawn(move || { + for (_, routine, context) in suspend { + routine(1, context as *mut c_void); + } + finish("title suspended"); + }); + std::thread::spawn(move || { + std::thread::sleep(SUSPEND_DEADLINE); + late("title did not finish suspending in time"); + }); +} + +/// Set in the environment of a relaunched `victory`: an inherited handle +/// of the process it replaces. +const RELAUNCHED_FROM: &str = "VICTORY_RELAUNCHED_FROM"; + +/// Starts `victory` again with `args` (after the title has suspended); the +/// new process waits until this one has ended. +pub(crate) fn relaunch(args: Vec<std::ffi::OsString>) { + use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE}; + let mut me: HANDLE = std::ptr::null_mut(); + // SAFETY: an inheritable duplicate of our own process handle. + let duplicated = unsafe { + DuplicateHandle( + GetCurrentProcess(), + GetCurrentProcess(), + GetCurrentProcess(), + &mut me, + 0, + 1, + DUPLICATE_SAME_ACCESS, + ) + } != 0; + let spawned = std::env::current_exe().and_then(|exe| { + let mut command = std::process::Command::new(exe); + command.args(&args); + if duplicated { + command.env(RELAUNCHED_FROM, (me as usize).to_string()); + } + command.spawn() + }); + match spawned { + Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"), + Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"), + } +} + +/// In a relaunched `victory`: waits (30 s at most) for the process it +/// replaces to be gone, so the two never share the title's files. +pub fn wait_for_previous() { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + let Some(handle) = std::env::var(RELAUNCHED_FROM) + .ok() + .and_then(|h| h.parse::<usize>().ok()) + else { + return; + }; + // SAFETY: removing our own variable before any other thread reads it. + unsafe { std::env::remove_var(RELAUNCHED_FROM) }; + let handle = handle as HANDLE; + // SAFETY: the inherited process handle the previous process gave us. + unsafe { + WaitForSingleObject(handle, 30_000); + CloseHandle(handle); + } +} + +fn end() { + // Compiled host pipelines kept for the next run. + #[cfg(windows)] + victory_gpu::pipeline::save_pipeline_cache(); + // SAFETY: ends this process, as the console ends a suspended title. + unsafe { TerminateProcess(GetCurrentProcess(), 0) }; +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "lifecycle", + dlls: &[ + "api-ms-win-core-psm-appnotify-*", + "ext-ms-win-rtcore-ntuser-window-*", + ], + exports: vec![ + hle_export!(RegisterAppStateChangeNotification), + hle_export!(UnregisterAppStateChangeNotification), + hle_export!(CreateWindowExW), + hle_export!(CreateWindowExA), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + extern "system" fn noop(_: u8, _: *mut c_void) {} + + #[test] + fn registrations_come_and_go() { + let (mut a, mut b) = (0, 0); + assert_eq!( + RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut a), + 0 + ); + assert_eq!( + RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut b), + 0 + ); + UnregisterAppStateChangeNotification(a); + let left: Vec<_> = routines().iter().map(|r| r.0).collect(); + assert_eq!(left, [b]); + } + + #[test] + fn oversized_windows_shrink_to_the_screen() { + let area = RECT { + left: 0, + top: 0, + right: 1920, + bottom: 1040, + }; + assert_eq!(fit_into(&area, 3840, 2160), (1848, 1040)); + assert_eq!(fit_into(&area, 1280, 720), (1280, 720)); + assert_eq!( + fit_into(&area, wm::CW_USEDEFAULT, 0), + (wm::CW_USEDEFAULT, 0) + ); + } + + #[test] + fn hooked_windows_still_reach_the_title_procedure() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("before"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + assert!(!hwnd.is_null()); + let mut text = [0u16; 16]; + // SAFETY: our window; the buffer holds 16 characters. + unsafe { + wm::SetWindowTextW(hwnd, w!("after")); + let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16); + assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after"); + assert!(!wm::GetPropW(hwnd, TITLE_PROC).is_null()); + wm::DestroyWindow(hwnd); + } + } + + thread_local! { + /// The system commands `recording` received, low four bits cleared. + static COMMANDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// Stands in for a title's procedure: notes system commands and acts + /// on none of them (no menu loop, no minimising). + extern "system" fn recording( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> LRESULT { + if message == wm::WM_SYSCOMMAND { + COMMANDS.with(|c| c.borrow_mut().push(wparam & 0xFFF0)); + return 0; + } + // SAFETY: the system's default procedure, called as the system would. + unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) } + } + + #[test] + fn the_keyboard_menu_never_reaches_the_title() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("menu"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + assert!(!hwnd.is_null()); + // SAFETY: our window, owned by this thread, so each message is + // handled before SendMessageW returns. `recording` stands in for the + // title's procedure and the original is put back before the window + // is destroyed. + unsafe { + let title = wm::GetPropW(hwnd, TITLE_PROC); + wm::SetPropW(hwnd, TITLE_PROC, recording as *const () as *mut c_void); + let command = |c: u32, key: u8| { + wm::SendMessageW(hwnd, wm::WM_SYSCOMMAND, c as usize, LPARAM::from(key)) + }; + command(wm::SC_KEYMENU, 0); // Alt or F10 + command(wm::SC_KEYMENU, b' '); // Alt+Space + command(wm::SC_KEYMENU | 1, 0); // the low bits are the system's + command(wm::SC_MINIMIZE, 0); + wm::SetPropW(hwnd, TITLE_PROC, title); + wm::DestroyWindow(hwnd); + } + let seen = COMMANDS.with(|c| c.borrow().clone()); + assert_eq!(seen, [wm::SC_MINIMIZE as usize]); + } +} diff --git a/crates/victory-hle/src/modules/media.rs b/crates/victory-hle/src/modules/media.rs new file mode 100644 index 000000000..aa6e91c5b --- /dev/null +++ b/crates/victory-hle/src/modules/media.rs @@ -0,0 +1,531 @@ +//! Media Foundation is the host's (`mfplat.dll` passes through), except for +//! the source resolver: the host's would fetch `http`, `rtsp` and other +//! URLs over the network, past `modules::net`. Titles get a proxy that +//! opens local files only, with paths on our virtual drives rewritten to +//! their host folders, and forwards everything else to the host's resolver. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::HashSet; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use super::files; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +/// What Media Foundation answers for a URL scheme it has no handler for. +const UNSUPPORTED_SCHEME: HRESULT = 0xC00D_36C3_u32 as i32; + +const IID_IUNKNOWN: [u8; 16] = guid(0x0000_0000, 0x0000, 0x0000, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]); +const IID_RESOLVER: [u8; 16] = guid( + 0xFBE5_A32D, + 0xA497, + 0x4B61, + [0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3], +); + +const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] { + let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes()); + [ + a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6], + d[7], + ] +} + +// The URL rule. + +/// Where a resolver may read `url` from: `Ok` with the NUL-terminated +/// string to hand to the host, or `Err((scheme, host))` for anything that +/// is not a local file. +fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> { + let text = String::from_utf16_lossy(url); + let drive = |s: &str| { + let b = s.as_bytes(); + b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' + }; + let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string(); + let path = if let Some(rest) = text.strip_prefix(r"\\?\") { + if !drive(rest) { + return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\")))); + } + text.clone() + } else if let Some(rest) = text.strip_prefix(r"\\").or_else(|| text.strip_prefix("//")) { + return Err(("unc".into(), host_of(rest))); + } else if drive(&text) { + text.clone() + } else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| { + s.len() > 1 + && s.bytes() + .all(|c| c.is_ascii_alphanumeric() || b"+-.".contains(&c)) + }) { + let scheme = scheme.to_ascii_lowercase(); + let authority = rest.strip_prefix("//"); + if scheme != "file" { + return Err((scheme, authority.map(host_of).unwrap_or_default())); + } + let path = match authority { + Some(rest) => { + let host = host_of(rest); + if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") { + return Err((scheme, host)); + } + &rest[host.len()..] + } + None => rest, + }; + let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\"); + if !drive(&path) { + // A local file without a drive: the host resolves it as is. + return Ok(with_nul(url)); + } + path + } else { + // A relative path. + return Ok(with_nul(url)); + }; + let wide: Vec<u16> = path.encode_utf16().collect(); + Ok(files::translate(&wide).unwrap_or_else(|| with_nul(&wide))) +} + +fn with_nul(s: &[u16]) -> Vec<u16> { + s.iter().copied().chain([0]).collect() +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let hex = b + .get(i + 1..i + 3) + .and_then(|h| std::str::from_utf8(h).ok()); + match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) { + (b'%', Some(v)) => { + out.push(v); + i += 3; + } + (c, _) => { + out.push(c); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The URL to give the host, or the refusal (logged once per scheme and +/// host). +fn checked(url: *const u16) -> Result<Vec<u16>, HRESULT> { + if url.is_null() { + return Err(E_POINTER); + } + // SAFETY: a NUL-terminated wide string from the title. + let len = (0..) + .take_while(|&i| unsafe { url.add(i).read() } != 0) + .count(); + // SAFETY: as above, `len` characters before the NUL. + let wide = unsafe { std::slice::from_raw_parts(url, len) }; + local(wide).map_err(|(scheme, host)| { + static REFUSED: Mutex<Option<HashSet<(String, String)>>> = Mutex::new(None); + let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); + if refused + .get_or_insert_with(HashSet::new) + .insert((scheme.clone(), host.clone())) + { + tracing::warn!( + scheme, + host, + "media: refused a URL that is not a local file" + ); + } + UNSUPPORTED_SCHEME + }) +} + +// The proxy resolver. + +/// The host's resolver, called through its method table. +#[repr(C)] +struct Host { + vtable: *const usize, +} + +impl Host { + /// Method `n` of the host object, typed by the caller. + unsafe fn method<F: Copy>(this: *mut Host, n: usize) -> F { + // SAFETY: the caller names the slot's real signature; `this` is the + // host's live resolver. + unsafe { std::mem::transmute_copy(&*(*this).vtable.add(n)) } + } +} + +#[repr(C)] +pub struct Resolver { + vtable: &'static Methods, + host: *mut Host, + refs: AtomicU32, +} + +type Unknown = *mut c_void; + +#[repr(C)] +struct Methods { + query_interface: + extern "system" fn(*mut Resolver, *const [u8; 16], *mut *mut c_void) -> HRESULT, + add_ref: extern "system" fn(*mut Resolver) -> u32, + release: extern "system" fn(*mut Resolver) -> u32, + create_from_url: extern "system" fn( + *mut Resolver, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT, + create_from_stream: extern "system" fn( + *mut Resolver, + Unknown, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT, + begin_from_url: extern "system" fn( + *mut Resolver, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT, + end_from_url: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT, + begin_from_stream: extern "system" fn( + *mut Resolver, + Unknown, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT, + end_from_stream: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT, + cancel: extern "system" fn(*mut Resolver, Unknown) -> HRESULT, +} + +static METHODS: Methods = Methods { + query_interface, + add_ref, + release, + create_from_url, + create_from_stream, + begin_from_url, + end_from_url, + begin_from_stream, + end_from_stream, + cancel, +}; + +fn host(this: *mut Resolver) -> *mut Host { + // SAFETY: title code calls methods on a proxy we made, alive until its + // last release. + unsafe { (*this).host } +} + +/// Only the resolver's own interfaces: anything else could hand out the +/// host object unguarded. +extern "system" fn query_interface( + this: *mut Resolver, + iid: *const [u8; 16], + out: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || out.is_null() { + return E_POINTER; + } + // SAFETY: checked non-null. + let iid = unsafe { *iid }; + let found = iid == IID_IUNKNOWN || iid == IID_RESOLVER; + // SAFETY: checked non-null. + unsafe { + out.write(if found { + this.cast() + } else { + std::ptr::null_mut() + }) + }; + if !found { + return E_NOINTERFACE; + } + add_ref(this); + S_OK +} + +extern "system" fn add_ref(this: *mut Resolver) -> u32 { + // SAFETY: as in `host`. + unsafe { (*this).refs.fetch_add(1, Ordering::Relaxed) + 1 } +} + +extern "system" fn release(this: *mut Resolver) -> u32 { + // SAFETY: as in `host`. + let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1; + if left == 0 { + // SAFETY: made by `MFCreateSourceResolver`; this was the last + // reference, to the proxy and to the host object it holds. + let proxy = unsafe { Box::from_raw(this) }; + // SAFETY: slot 2 is `Release`. + let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) }; + release(proxy.host); + } + left +} + +extern "system" fn create_from_url( + this: *mut Resolver, + url: *const u16, + flags: u32, + props: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(url) => url, + Err(error) => { + if !object.is_null() { + // SAFETY: the title's out parameter. + unsafe { object.write(std::ptr::null_mut()) }; + } + return error; + } + }; + let host = host(this); + // SAFETY: slot 3 is `CreateObjectFromURL`. + let f: extern "system" fn( + *mut Host, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT = unsafe { Host::method(host, 3) }; + f(host, url.as_ptr(), flags, props, kind, object) +} + +extern "system" fn begin_from_url( + this: *mut Resolver, + url: *const u16, + flags: u32, + props: Unknown, + cookie: *mut Unknown, + callback: Unknown, + state: Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(url) => url, + Err(error) => return error, + }; + let host = host(this); + // SAFETY: slot 5 is `BeginCreateObjectFromURL`. + let f: extern "system" fn( + *mut Host, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT = unsafe { Host::method(host, 5) }; + f(host, url.as_ptr(), flags, props, cookie, callback, state) +} + +extern "system" fn create_from_stream( + this: *mut Resolver, + stream: Unknown, + url: *const u16, + flags: u32, + props: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 4 is `CreateObjectFromByteStream`; the URL is only a + // hint for picking a handler. + let f: extern "system" fn( + *mut Host, + Unknown, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT = unsafe { Host::method(host, 4) }; + f(host, stream, url, flags, props, kind, object) +} + +extern "system" fn end_from_url( + this: *mut Resolver, + result: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 6 is `EndCreateObjectFromURL`. + let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT = + unsafe { Host::method(host, 6) }; + f(host, result, kind, object) +} + +#[allow(clippy::too_many_arguments)] +extern "system" fn begin_from_stream( + this: *mut Resolver, + stream: Unknown, + url: *const u16, + flags: u32, + props: Unknown, + cookie: *mut Unknown, + callback: Unknown, + state: Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 7 is `BeginCreateObjectFromByteStream`. + let f: extern "system" fn( + *mut Host, + Unknown, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT = unsafe { Host::method(host, 7) }; + f(host, stream, url, flags, props, cookie, callback, state) +} + +extern "system" fn end_from_stream( + this: *mut Resolver, + result: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 8 is `EndCreateObjectFromByteStream`. + let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT = + unsafe { Host::method(host, 8) }; + f(host, result, kind, object) +} + +extern "system" fn cancel(this: *mut Resolver, cookie: Unknown) -> HRESULT { + let host = host(this); + // SAFETY: slot 9 is `CancelObjectCreation`. + let f: extern "system" fn(*mut Host, Unknown) -> HRESULT = unsafe { Host::method(host, 9) }; + f(host, cookie) +} + +/// The host's resolver behind our proxy. +pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + static CREATE: OnceLock<Option<usize>> = OnceLock::new(); + let Some(create) = + *CREATE.get_or_init(|| crate::host::function("mfplat.dll", "MFCreateSourceResolver")) + else { + return UNSUPPORTED_SCHEME; + }; + // SAFETY: the host's `MFCreateSourceResolver(IMFSourceResolver**)`. + let create: extern "system" fn(*mut *mut Host) -> HRESULT = + unsafe { std::mem::transmute(create) }; + let mut host = std::ptr::null_mut(); + let hr = create(&mut host); + if hr < 0 || host.is_null() { + return hr; + } + let proxy = Box::new(Resolver { + vtable: &METHODS, + host, + refs: AtomicU32::new(1), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(proxy)) }; + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "media", + dlls: &["mfplat.dll"], + exports: vec![hle_export!(MFCreateSourceResolver)], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn wide(s: &str) -> Vec<u16> { + s.encode_utf16().collect() + } + + fn text(v: &[u16]) -> String { + String::from_utf16_lossy(v.strip_suffix(&[0]).unwrap_or(v)) + } + + #[test] + fn only_local_files_reach_the_host() { + // Network schemes and shares are refused, naming scheme and host. + let refused = |url: &str| local(&wide(url)).unwrap_err(); + assert_eq!( + refused("https://cdn.example.com/a.mp4"), + ("https".into(), "cdn.example.com".into()) + ); + assert_eq!(refused("RTSP://10.0.0.1:554/x").0, "rtsp"); + assert_eq!(refused("mms://h/x").0, "mms"); + assert_eq!( + refused(r"\\server\share\a.mp4"), + ("unc".into(), "server".into()) + ); + assert_eq!( + refused("file://server/share/a.mp4"), + ("file".into(), "server".into()) + ); + + // A path on a virtual drive goes to its host folder, also as a + // `file:` URL; other local files pass as they are. + // Checked by opening the files: `files` may spell the host root + // differently (absolute, `\\?\` for long paths) from the temp dir. + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("movies")).unwrap(); + std::fs::write(dir.path().join("movies").join("intro.mp4"), b"1").unwrap(); + std::fs::write(dir.path().join("movies").join("intro a.mp4"), b"2").unwrap(); + let letter = files::mount(dir.path()).expect("a free drive letter"); + let host = text(&local(&wide(&format!(r"{letter}:\movies\intro.mp4"))).unwrap()); + assert_eq!( + std::fs::read(&host).ok().as_deref(), + Some(&b"1"[..]), + "{host}" + ); + let from_url = + text(&local(&wide(&format!("file:///{letter}:/movies/intro%20a.mp4"))).unwrap()); + assert_eq!( + std::fs::read(&from_url).ok().as_deref(), + Some(&b"2"[..]), + "{from_url}" + ); + assert_eq!( + text(&local(&wide("file:///C:/Windows/a.wav")).unwrap()), + r"C:\Windows\a.wav" + ); + assert_eq!(text(&local(&wide("clip.mp4")).unwrap()), "clip.mp4"); + } + + #[test] + fn interface_ids_are_the_resolvers() { + assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]); + assert_eq!(&IID_RESOLVER[..4], &[0x2D, 0xA3, 0xE5, 0xFB]); + } +} diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs new file mode 100644 index 000000000..51e3590bf --- /dev/null +++ b/crates/victory-hle/src/modules/mod.rs @@ -0,0 +1,74 @@ +//! Implementations, one module per area of the console API. +//! +//! Adding an API: write an `extern "system"` function named exactly like +//! the import, then list it with `hle_export!` in the module's `module()`. +//! Run `victory census` over your titles to see what is still missing. +//! +//! Planned areas (driven by census results, not by completeness): +//! `file` (package paths), `thread` (TLS callbacks for title threads), +//! `xaudio2`, `xstore` stubs. + +#[cfg(windows)] +pub mod apu; +pub mod audio; +pub mod d3d12x; +pub mod display; +pub mod dsp; +#[cfg(windows)] +pub mod dstorage; +#[cfg(windows)] +pub mod files; +pub mod gameinput; +pub mod kernel; +#[cfg(windows)] +pub mod lifecycle; +#[cfg(windows)] +pub mod media; +#[cfg(windows)] +pub mod net; +pub mod speech; +pub mod storage; +pub mod xasync; +pub mod xg; +pub mod xgame; +pub mod xgameruntime; +pub mod xgamesave; +pub mod xgameui; +#[cfg(windows)] +pub mod xmem; +pub mod xnetworking; +pub mod xpackage; +pub mod xstore; +pub mod xsystem; +pub mod xuser; + +use crate::HleModule; + +pub(crate) fn all() -> Vec<HleModule> { + let mut all = vec![ + kernel::module(), + xgameruntime::module(), + gameinput::module(), + d3d12x::module(), + audio::module(), + dsp::module(), + xg::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 new file mode 100644 index 000000000..857b351c7 --- /dev/null +++ b/crates/victory-hle/src/modules/net.rs @@ -0,0 +1,1069 @@ +//! A console without a network cable: the title reaches loopback only. +//! +//! Every way out of Winsock and WinHTTP a title can import or look up by +//! name is vetted here; the rest of both DLLs is the host's own. +//! +//! * Connects (also by name, by list, `ConnectEx` from `WSAIoctl`) and +//! datagram sends to anything but 127.0.0.0/8 and ::1 fail with +//! `WSAENETUNREACH`. +//! * Forward lookups other than `localhost` and IP literals fail with +//! `WSAHOST_NOT_FOUND`; reverse lookups of other addresses come back +//! numeric, or fail if a name is required, as with no network. +//! * `WinHttpConnect` to a host that is not loopback fails with +//! `ERROR_WINHTTP_CANNOT_CONNECT`, so no request (or WebSocket) handle can +//! exist for one. Proxies are off and proxy auto-detection (WPAD, PAC +//! downloads) fails with `ERROR_WINHTTP_AUTODETECTION_FAILED`. +//! * A bind to all interfaces is narrowed to loopback, so nothing on the +//! network can connect in. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::{CStr, c_char, c_void}; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Mutex; + +use windows_sys::Win32::Foundation::SetLastError; + +use crate::modules::files::host; +use crate::{HleExport, HleModule, hle_export}; + +const SOCKET_ERROR: i32 = -1; +const INVALID_SOCKET: Socket = !0; +const WSAEINVAL: i32 = 10022; +const WSAEADDRNOTAVAIL: i32 = 10049; +const WSAENETUNREACH: i32 = 10051; +const WSASERVICE_NOT_FOUND: i32 = 10108; +const WSAHOST_NOT_FOUND: i32 = 11001; +const ERROR_WINHTTP_CANNOT_CONNECT: u32 = 12029; +const ERROR_WINHTTP_AUTODETECTION_FAILED: u32 = 12180; +const AF_INET: u16 = 2; +const AF_INET6: u16 = 23; +const NI_NUMERICHOST: i32 = 0x02; +const NI_NAMEREQD: i32 = 0x04; +const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006; +const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0024; +const WINHTTP_ACCESS_TYPE_NO_PROXY: u32 = 1; +const WINHTTP_OPTION_PROXY: u32 = 38; + +#[repr(C)] +#[derive(Clone, Copy, PartialEq, Eq)] +struct Guid(u32, u16, u16, [u8; 8]); + +const WSAID_CONNECTEX: Guid = Guid( + 0x25a2_07b9, + 0xddf3, + 0x4660, + [0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e], +); +const WSAID_WSASENDMSG: Guid = Guid( + 0xa441_e712, + 0x754f, + 0x43ca, + [0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d], +); + +type Socket = usize; +type Handle = *mut c_void; + +/// Logs `what` for `destination` the first time (no payload, ever). +fn once(what: &'static str, destination: String) { + static SEEN: Mutex<Vec<(&str, String)>> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.iter().any(|(w, d)| *w == what && *d == destination) { + tracing::info!(%destination, "{what}"); + seen.push((what, destination)); + } +} + +fn wsa_error(code: i32) { + host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32))(code); +} + +fn narrow(text: *const c_char) -> Option<String> { + (!text.is_null()).then(|| { + // SAFETY: the title passes a NUL-terminated string. + unsafe { CStr::from_ptr(text) } + .to_string_lossy() + .into_owned() + }) +} + +fn wide(text: *const u16) -> Option<String> { + // SAFETY: the title passes a NUL-terminated string or null. + (!text.is_null()).then(|| unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }) +} + +/// An IPv4 or IPv6 `sockaddr` of `len` bytes. +fn socket_addr(addr: *const u8, len: i32) -> Option<SocketAddr> { + let len = usize::try_from(len).ok()?; + if addr.is_null() || len < 4 { + return None; + } + // SAFETY: the title passes `len` readable bytes. + let b = unsafe { std::slice::from_raw_parts(addr, len) }; + let port = u16::from_be_bytes([b[2], b[3]]); + match u16::from_le_bytes([b[0], b[1]]) { + AF_INET if len >= 16 => Some((<[u8; 4]>::try_from(&b[4..8]).ok()?, port).into()), + AF_INET6 if len >= 28 => Some((<[u8; 16]>::try_from(&b[8..24]).ok()?, port).into()), + _ => None, + } +} + +/// A raw address of family `kind` (`gethostbyaddr` style). +fn raw_ip(addr: *const c_char, len: i32, kind: i32) -> Option<IpAddr> { + let len = usize::try_from(len).ok()?; + if addr.is_null() { + return None; + } + // SAFETY: the title passes `len` readable bytes. + let b = unsafe { std::slice::from_raw_parts(addr.cast::<u8>(), len) }; + match (u16::try_from(kind).ok()?, len) { + (AF_INET, 4..) => Some(<[u8; 4]>::try_from(&b[..4]).ok()?.into()), + (AF_INET6, 16..) => Some(<[u8; 16]>::try_from(&b[..16]).ok()?.into()), + _ => None, + } +} + +fn loopback(ip: IpAddr) -> bool { + ip.to_canonical().is_loopback() +} + +/// `localhost` or a loopback literal (bracketed IPv6 too). +fn loopback_name(name: &str) -> bool { + let bare = name.trim_start_matches('[').trim_end_matches(']'); + bare.eq_ignore_ascii_case("localhost") || bare.parse().is_ok_and(loopback) +} + +fn shown(addr: Option<impl ToString>) -> String { + addr.map_or_else(|| "not an IP address".into(), |a| a.to_string()) +} + +/// True for a loopback `sockaddr`; otherwise logs it and sets +/// `WSAENETUNREACH`. Other address families count as off the machine. +fn reachable(what: &'static str, addr: *const u8, len: i32) -> bool { + match socket_addr(addr, len) { + Some(a) if loopback(a.ip()) => true, + a => { + once(what, shown(a)); + wsa_error(WSAENETUNREACH); + false + } + } +} + +/// Connecting by name: only to loopback. A name would need a lookup +/// (`WSAHOST_NOT_FOUND`), an address a route (`WSAENETUNREACH`). +fn reachable_name(name: Option<String>) -> bool { + match name { + Some(name) if !loopback_name(&name) => { + let literal = name.parse::<IpAddr>().is_ok(); + once("network connect blocked", name); + wsa_error(if literal { + WSAENETUNREACH + } else { + WSAHOST_NOT_FOUND + }); + false + } + // No name: the host rejects the call itself. + _ => true, + } +} + +/// Names answered without asking the network: none, `localhost`, IP +/// literals (connecting to one is vetted separately). +fn resolvable(name: Option<String>) -> bool { + match name { + Some(name) + if !(name.is_empty() + || name.eq_ignore_ascii_case("localhost") + || name.parse::<IpAddr>().is_ok()) => + { + once("network name lookup blocked", name); + wsa_error(WSAHOST_NOT_FOUND); + false + } + _ => true, + } +} + +/// Reverse lookups ask DNS unless the address is loopback. +fn reverse_resolvable(ip: Option<IpAddr>) -> bool { + match ip { + Some(ip) if loopback(ip) => true, + ip => { + once("network reverse lookup blocked", shown(ip)); + false + } + } +} + +/// `getnameinfo` flags that keep a host name lookup on the machine: the +/// numeric form, as without a network, or `None` if a name is required. +fn name_info_flags(sa: *const u8, len: i32, host_wanted: bool, flags: i32) -> Option<i32> { + if !host_wanted + || flags & NI_NUMERICHOST != 0 + || reverse_resolvable(socket_addr(sa, len).map(|a| a.ip())) + { + Some(flags) + } else if flags & NI_NAMEREQD != 0 { + wsa_error(WSAHOST_NOT_FOUND); + None + } else { + Some(flags | NI_NUMERICHOST) + } +} + +// Connects. + +pub extern "system" fn connect(s: Socket, name: *const u8, len: i32) -> i32 { + if !reachable("network connect blocked", name, len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32)(s, name, len) +} + +pub extern "system" fn WSAConnect( + s: Socket, + name: *const u8, + len: i32, + caller_data: *const c_void, + callee_data: *mut c_void, + sqos: *const c_void, + gqos: *const c_void, +) -> i32 { + if !reachable("network connect blocked", name, len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSAConnect": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void) -> i32)( + s, + name, + len, + caller_data, + callee_data, + sqos, + gqos, + ) +} + +pub extern "system" fn WSAConnectByNameA( + s: Socket, + node: *const c_char, + service: *const c_char, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !reachable_name(narrow(node)) { + return 0; + } + host!("ws2_32.dll", "WSAConnectByNameA": extern "system" fn(Socket, *const c_char, *const c_char, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, node, service, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +pub extern "system" fn WSAConnectByNameW( + s: Socket, + node: *const u16, + service: *const u16, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !reachable_name(wide(node)) { + return 0; + } + host!("ws2_32.dll", "WSAConnectByNameW": extern "system" fn(Socket, *const u16, *const u16, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, node, service, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +/// `SOCKET_ADDRESS`; a `SOCKET_ADDRESS_LIST` is an `i32` count, then these +/// (pointer aligned). +#[repr(C)] +struct SocketAddress { + addr: *const u8, + len: i32, +} + +/// Every candidate must be loopback. +pub extern "system" fn WSAConnectByList( + s: Socket, + list: *const u8, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !list.is_null() { + // SAFETY: the title passes a `SOCKET_ADDRESS_LIST`. + let entries = unsafe { + let count = usize::try_from(list.cast::<i32>().read()).unwrap_or(0); + std::slice::from_raw_parts(list.add(8).cast::<SocketAddress>(), count) + }; + if !entries + .iter() + .all(|e| reachable("network connect blocked", e.addr, e.len)) + { + return 0; + } + } + 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( + s: Socket, + name: *const u8, + len: i32, + caller_data: *const c_void, + callee_data: *mut c_void, + sqos: *const c_void, + gqos: *const c_void, + flags: u32, +) -> Socket { + if !reachable("network connect blocked", name, len) { + return INVALID_SOCKET; + } + host!("ws2_32.dll", "WSAJoinLeaf": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void, u32) -> Socket)( + s, + name, + len, + caller_data, + callee_data, + sqos, + gqos, + flags, + ) +} + +/// `ConnectEx` as `WSAIoctl` hands it out: vetted, then the socket's own. +extern "system" fn connect_ex( + s: Socket, + name: *const u8, + len: i32, + send: *const c_void, + send_len: u32, + sent: *mut u32, + overlapped: *mut c_void, +) -> i32 { + if !reachable("network connect blocked", name, len) { + return 0; + } + let (mut real, mut size) = (0usize, 0u32); + let ioctl = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32); + let guid = WSAID_CONNECTEX; + let found = ioctl( + s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (&raw const guid).cast(), + 16, + (&raw mut real).cast(), + 8, + &mut size, + std::ptr::null_mut(), + std::ptr::null(), + ); + if found != 0 || real == 0 { + return 0; + } + // SAFETY: the provider's `ConnectEx` for this socket. + let real = unsafe { + std::mem::transmute::< + usize, + extern "system" fn( + Socket, + *const u8, + i32, + *const c_void, + u32, + *mut u32, + *mut c_void, + ) -> i32, + >(real) + }; + real(s, name, len, send, send_len, sent, overlapped) +} + +/// The `ConnectEx` and `WSASendMsg` pointers it hands out are ours; the +/// multi-pointer query (Registered I/O, whose `RIOSendEx` takes any +/// address) is refused as by an old system. Other controls pass through. +pub extern "system" fn WSAIoctl( + s: Socket, + code: u32, + input: *const c_void, + input_len: u32, + output: *mut c_void, + output_len: u32, + returned: *mut u32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + if code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER { + wsa_error(WSAEINVAL); + return SOCKET_ERROR; + } + let result = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)( + s, code, input, input_len, output, output_len, returned, overlapped, completion, + ); + if result == 0 && code == SIO_GET_EXTENSION_FUNCTION_POINTER && input_len >= 16 { + // SAFETY: the host just read a GUID from `input` and wrote a pointer to `output`. + unsafe { + let ours = match input.cast::<Guid>().read_unaligned() { + WSAID_CONNECTEX => connect_ex as *const () as usize, + WSAID_WSASENDMSG => WSASendMsg as *const () as usize, + _ => return result, + }; + output.cast::<usize>().write_unaligned(ours); + } + } + result +} + +// Datagram sends. + +/// Without an address it sends to the connected peer, which `connect` vetted; +/// so does a stream socket whatever `to` says (Winsock ignores it there). +pub extern "system" fn sendto( + s: Socket, + buf: *const u8, + len: i32, + flags: i32, + to: *const u8, + to_len: i32, +) -> i32 { + if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "sendto": extern "system" fn(Socket, *const u8, i32, i32, *const u8, i32) -> i32)( + s, buf, len, flags, to, to_len, + ) +} + +pub extern "system" fn WSASendTo( + s: Socket, + buffers: *const c_void, + count: u32, + sent: *mut u32, + flags: u32, + to: *const u8, + to_len: i32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSASendTo": extern "system" fn(Socket, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)( + s, buffers, count, sent, flags, to, to_len, overlapped, completion, + ) +} + +/// A connection-oriented socket, whose sends go to the peer `connect` vetted. +fn stream(s: Socket) -> bool { + const SOL_SOCKET: i32 = 0xffff; + const SO_TYPE: i32 = 0x1008; + const SOCK_STREAM: i32 = 1; + let (mut kind, mut len) = (0i32, 4i32); + let getsockopt = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut i32, *mut i32) -> i32); + getsockopt(s, SOL_SOCKET, SO_TYPE, &mut kind, &mut len) == 0 && kind == SOCK_STREAM +} + +/// The start of a `WSAMSG`: the destination. +#[repr(C)] +struct MessageName { + name: *const u8, + len: i32, +} + +pub extern "system" fn WSASendMsg( + s: Socket, + message: *const c_void, + flags: u32, + sent: *mut u32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + // SAFETY: the title passes a `WSAMSG` or null. + if let Some(m) = unsafe { message.cast::<MessageName>().as_ref() } + && !m.name.is_null() + && !reachable("network datagram blocked", m.name, m.len) + { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSASendMsg": extern "system" fn(Socket, *const c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)( + s, message, flags, sent, overlapped, completion, + ) +} + +/// All interfaces become loopback, the only one an unplugged console has; +/// any other address is not ours (`WSAEADDRNOTAVAIL`). +// shortcut: `[::]` becomes `[::1]`, so a dual-stack listener no longer hears +// 127.0.0.1; bind both families if a title relies on that. +pub extern "system" fn bind(s: Socket, name: *const u8, len: i32) -> i32 { + let host_bind = host!("ws2_32.dll", "bind": extern "system" fn(Socket, *const u8, i32) -> i32); + match socket_addr(name, len) { + Some(a) if loopback(a.ip()) => host_bind(s, name, len), + Some(a) if a.ip().is_unspecified() => { + once("network bind narrowed to loopback", a.to_string()); + // SAFETY: `socket_addr` checked `len` readable bytes. + let mut local = unsafe { std::slice::from_raw_parts(name, len as usize) }.to_vec(); + match a { + SocketAddr::V4(_) => local[4..8].copy_from_slice(&[127, 0, 0, 1]), + SocketAddr::V6(_) => local[23] = 1, + } + host_bind(s, local.as_ptr(), len) + } + a => { + once("network bind blocked", shown(a)); + wsa_error(WSAEADDRNOTAVAIL); + SOCKET_ERROR + } + } +} + +// Forward lookups. + +pub extern "system" fn getaddrinfo( + node: *const c_char, + service: *const c_char, + hints: *const c_void, + result: *mut *mut c_void, +) -> i32 { + if !resolvable(narrow(node)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)( + node, service, hints, result, + ) +} + +pub extern "system" fn GetAddrInfoW( + node: *const u16, + service: *const u16, + hints: *const c_void, + result: *mut *mut c_void, +) -> i32 { + if !resolvable(wide(node)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)( + node, service, hints, result, + ) +} + +pub extern "system" fn GetAddrInfoExA( + name: *const c_char, + service: *const c_char, + namespace: u32, + provider: *const c_void, + hints: *const c_void, + result: *mut *mut c_void, + timeout: *const c_void, + overlapped: *mut c_void, + completion: *const c_void, + handle: *mut Handle, +) -> i32 { + if !resolvable(narrow(name)) { + return WSAHOST_NOT_FOUND; + } + 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, + ) +} + +pub extern "system" fn GetAddrInfoExW( + name: *const u16, + service: *const u16, + namespace: u32, + provider: *const c_void, + hints: *const c_void, + result: *mut *mut c_void, + timeout: *const c_void, + overlapped: *mut c_void, + completion: *const c_void, + handle: *mut Handle, +) -> i32 { + if !resolvable(wide(name)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoExW": extern "system" fn(*const u16, *const u16, 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, + ) +} + +pub extern "system" fn gethostbyname(name: *const c_char) -> *mut c_void { + if !resolvable(narrow(name)) { + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "gethostbyname": extern "system" fn(*const c_char) -> *mut c_void)(name) +} + +pub extern "system" fn WSAAsyncGetHostByName( + window: Handle, + message: u32, + name: *const c_char, + buf: *mut c_char, + buf_len: i32, +) -> Handle { + if !resolvable(narrow(name)) { + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "WSAAsyncGetHostByName": extern "system" fn(Handle, u32, *const c_char, *mut c_char, i32) -> Handle)( + window, message, name, buf, buf_len, + ) +} + +/// Name-space queries (DNS, also network lists and Bluetooth) are refused +/// as a console without a network answers them. +// shortcut: local name spaces are refused too; pass those through if a title +// needs one. +pub extern "system" fn WSALookupServiceBeginA( + _restrictions: *const c_void, + _flags: u32, + _lookup: *mut Handle, +) -> i32 { + once("network name-space query blocked", "any".into()); + wsa_error(WSASERVICE_NOT_FOUND); + SOCKET_ERROR +} + +/// See [`WSALookupServiceBeginA`]. +pub extern "system" fn WSALookupServiceBeginW( + restrictions: *const c_void, + flags: u32, + lookup: *mut Handle, +) -> i32 { + WSALookupServiceBeginA(restrictions, flags, lookup) +} + +// Reverse lookups. + +pub extern "system" fn gethostbyaddr(addr: *const c_char, len: i32, kind: i32) -> *mut c_void { + if !reverse_resolvable(raw_ip(addr, len, kind)) { + wsa_error(WSAHOST_NOT_FOUND); + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "gethostbyaddr": extern "system" fn(*const c_char, i32, i32) -> *mut c_void)( + addr, len, kind, + ) +} + +pub extern "system" fn WSAAsyncGetHostByAddr( + window: Handle, + message: u32, + addr: *const c_char, + len: i32, + kind: i32, + buf: *mut c_char, + buf_len: i32, +) -> Handle { + if !reverse_resolvable(raw_ip(addr, len, kind)) { + wsa_error(WSAHOST_NOT_FOUND); + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "WSAAsyncGetHostByAddr": extern "system" fn(Handle, u32, *const c_char, i32, i32, *mut c_char, i32) -> Handle)( + window, message, addr, len, kind, buf, buf_len, + ) +} + +pub extern "system" fn getnameinfo( + sa: *const u8, + sa_len: i32, + host: *mut c_char, + host_len: u32, + serv: *mut c_char, + serv_len: u32, + flags: i32, +) -> i32 { + let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else { + return WSAHOST_NOT_FOUND; + }; + host!("ws2_32.dll", "getnameinfo": extern "system" fn(*const u8, i32, *mut c_char, u32, *mut c_char, u32, i32) -> i32)( + sa, sa_len, host, host_len, serv, serv_len, flags, + ) +} + +pub extern "system" fn GetNameInfoW( + sa: *const u8, + sa_len: i32, + host: *mut u16, + host_len: u32, + serv: *mut u16, + serv_len: u32, + flags: i32, +) -> i32 { + let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else { + return WSAHOST_NOT_FOUND; + }; + host!("ws2_32.dll", "GetNameInfoW": extern "system" fn(*const u8, i32, *mut u16, u32, *mut u16, u32, i32) -> i32)( + sa, sa_len, host, host_len, serv, serv_len, flags, + ) +} + +// WinHTTP. + +/// The one door to a server: requests, uploads and WebSockets all hang off +/// the handle this returns. +pub extern "system" fn WinHttpConnect( + session: Handle, + server: *const u16, + port: u16, + reserved: u32, +) -> Handle { + if let Some(name) = wide(server) + && !loopback_name(&name) + { + once("HTTP connection blocked", format!("{name}:{port}")); + // SAFETY: no pointers. + unsafe { SetLastError(ERROR_WINHTTP_CANNOT_CONNECT) }; + return std::ptr::null_mut(); + } + host!("winhttp.dll", "WinHttpConnect": extern "system" fn(Handle, *const u16, u16, u32) -> Handle)( + session, server, port, reserved, + ) +} + +/// Sessions never use a proxy: only loopback is reachable, and a proxy +/// (named, or found by auto-detection) would carry it off the machine. +pub extern "system" fn WinHttpOpen( + agent: *const u16, + access: u32, + _proxy: *const u16, + _bypass: *const u16, + flags: u32, +) -> Handle { + if access != WINHTTP_ACCESS_TYPE_NO_PROXY { + once("HTTP proxy ignored", format!("access type {access}")); + } + host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)( + agent, + WINHTTP_ACCESS_TYPE_NO_PROXY, + std::ptr::null(), + std::ptr::null(), + flags, + ) +} + +/// 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 { + once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into()); + return 1; + } + host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)( + handle, option, buffer, len, + ) +} + +/// Proxy auto-detection asks the network (DHCP, DNS, a PAC download). +fn no_auto_proxy() -> u32 { + once("HTTP proxy auto-detection blocked", "WPAD/PAC".into()); + ERROR_WINHTTP_AUTODETECTION_FAILED +} + +pub extern "system" fn WinHttpDetectAutoProxyConfigUrl(_flags: u32, _url: *mut *mut u16) -> i32 { + // SAFETY: no pointers. + unsafe { SetLastError(no_auto_proxy()) }; + 0 +} + +pub extern "system" fn WinHttpGetProxyForUrl( + _session: Handle, + _url: *const u16, + _options: *const c_void, + _info: *mut c_void, +) -> i32 { + // SAFETY: no pointers. + unsafe { SetLastError(no_auto_proxy()) }; + 0 +} + +pub extern "system" fn WinHttpGetProxyForUrlEx( + _resolver: Handle, + _url: *const u16, + _options: *const c_void, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +pub extern "system" fn WinHttpGetProxyForUrlEx2( + _resolver: Handle, + _url: *const u16, + _options: *const c_void, + _selection_len: u32, + _selection: *const u8, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +pub extern "system" fn WinHttpGetProxySettingsEx( + _resolver: Handle, + _kind: i32, + _params: *const c_void, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +/// Winsock imports by ordinal; the Winsock 1.1 numbers are fixed. +fn ordinal(name: &'static str, f: usize) -> HleExport { + HleExport { name, address: f } +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "net", + dlls: &["ws2_32.dll", "winhttp.dll"], + exports: vec![ + hle_export!(connect), + hle_export!(WSAConnect), + hle_export!(WSAConnectByNameA), + hle_export!(WSAConnectByNameW), + hle_export!(WSAConnectByList), + hle_export!(WSAJoinLeaf), + hle_export!(WSAIoctl), + hle_export!(sendto), + hle_export!(WSASendTo), + hle_export!(WSASendMsg), + hle_export!(bind), + hle_export!(getaddrinfo), + hle_export!(GetAddrInfoW), + hle_export!(GetAddrInfoExA), + hle_export!(GetAddrInfoExW), + hle_export!(gethostbyname), + hle_export!(WSAAsyncGetHostByName), + hle_export!(WSALookupServiceBeginA), + hle_export!(WSALookupServiceBeginW), + hle_export!(gethostbyaddr), + hle_export!(WSAAsyncGetHostByAddr), + hle_export!(getnameinfo), + hle_export!(GetNameInfoW), + hle_export!(WinHttpConnect), + hle_export!(WinHttpOpen), + hle_export!(WinHttpSetOption), + hle_export!(WinHttpDetectAutoProxyConfigUrl), + hle_export!(WinHttpGetProxyForUrl), + hle_export!(WinHttpGetProxyForUrlEx), + hle_export!(WinHttpGetProxyForUrlEx2), + hle_export!(WinHttpGetProxySettingsEx), + ordinal("#2", bind as *const () as usize), + ordinal("#4", connect as *const () as usize), + ordinal("#20", sendto as *const () as usize), + ordinal("#51", gethostbyaddr as *const () as usize), + ordinal("#52", gethostbyname as *const () as usize), + ordinal("#102", WSAAsyncGetHostByAddr as *const () as usize), + ordinal("#103", WSAAsyncGetHostByName as *const () as usize), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use victory_pe::ImportSymbol; + + fn v4(ip: [u8; 4], port: u16) -> [u8; 16] { + 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 + } + + // 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 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::<c_void>(); + + // Connects. + let s = socket(2, 1, 6); + assert_ne!(s, INVALID_SOCKET); + assert_eq!(connect(s, v4(AWAY, 80).as_ptr(), 16), SOCKET_ERROR); + assert_eq!(last_error(), WSAENETUNREACH); + let n = null.cast(); + assert_eq!( + WSAConnectByNameA( + s, + c"example.com".as_ptr(), + c"80".as_ptr(), + n, + null, + n, + null, + null, + null + ), + 0 + ); + 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); + + // `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!(last_error(), WSAENETUNREACH); + close(s); + + // Datagram sends. + let u = socket(2, 2, 17); + assert_eq!( + sendto(u, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), + SOCKET_ERROR + ); + assert_eq!(last_error(), WSAENETUNREACH); + assert_eq!( + sendto(u, b"x".as_ptr(), 1, 0, v4(HOME, port).as_ptr(), 16), + 1 + ); + close(u); + + // Forward and reverse lookups. + let mut result = null; + assert_eq!( + getaddrinfo( + c"example.com".as_ptr(), + std::ptr::null(), + std::ptr::null(), + &mut result + ), + WSAHOST_NOT_FOUND + ); + let name: Vec<u16> = "example.com\0".encode_utf16().collect(); + assert_eq!( + GetAddrInfoW( + name.as_ptr(), + std::ptr::null(), + std::ptr::null(), + &mut result + ), + WSAHOST_NOT_FOUND + ); + let mut text = [0 as c_char; 64]; + let away = v4(AWAY, 80); + assert_eq!( + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + 0 + ), + 0 + ); + // 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!( + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + NI_NAMEREQD + ), + WSAHOST_NOT_FOUND + ); + assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, 2).is_null()); + + // 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!( + WinHttpGetProxyForUrlEx(null, name.as_ptr(), std::ptr::null(), 0), + ERROR_WINHTTP_AUTODETECTION_FAILED + ); + + // The ordinals we override name the functions they stand for. + let m = module(); + for e in m.exports.iter().filter(|e| e.name.starts_with('#')) { + let named = m + .exports + .iter() + .find(|n| n.address == e.address && !n.name.starts_with('#')) + .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 {}", + e.name, + named.name + ); + } + // 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, e.name).is_some(); + if !present && NEWER_WINDOWS_ONLY.contains(&e.name) { + continue; + } + assert!(present, "{dll} lacks {}", e.name); + } + } +} diff --git a/crates/victory-hle/src/modules/speech.rs b/crates/victory-hle/src/modules/speech.rs new file mode 100644 index 000000000..15e8eca86 --- /dev/null +++ b/crates/victory-hle/src/modules/speech.rs @@ -0,0 +1,151 @@ +//! Accessibility: speech synthesis for the title's narration. No voice is +//! installed here, and every stream is valid WAVE audio of no length, so +//! narration is silent. +// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT +// speech synthesis) needs COM bindings this crate has only in diagnostics +// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the +// title then plays the empty stream and goes on. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; + +/// Closed captions, high contrast, speech to text and synthesis. +pub const PROVIDER: Guid = Guid::new( + 0x3e24_1977, + 0x6237, + 0x41e9, + [0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1], +); +/// Unchanged since 2020. +pub const IID: Guid = Guid::new( + 0xd722_b373, + 0x8c4d, + 0x4692, + [0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d], +); + +pub static OBJECT: Object = Object::new("accessibility", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; + +/// A WAVE file of 16 kHz mono 16-bit PCM with no samples: RIFF size 36, +/// a 16-byte format chunk (PCM, 1 channel, 16,000 Hz, 32,000 bytes/s, +/// block 2, 16 bits), an empty data chunk. +const SILENCE: [u8; 44] = + *b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0"; + +/// Synthesizers and streams hold nothing, so their handles are fixed +/// addresses and closing them is free. +static SYNTHESIZER: u8 = 0; +static STREAM: u8 = 0; + +type This = *const Object; + +/// No voice is installed, so the callback never runs. +extern "system" fn enumerate_voices( + _: This, + _context: *mut c_void, + _callback: *const c_void, +) -> HRESULT { + S_OK +} +extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT { + put(out, &raw const SYNTHESIZER) +} +extern "system" fn close(_: This, _: *const u8) -> HRESULT { + S_OK +} +extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT { + S_OK +} +extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT { + S_OK +} +extern "system" fn create_stream( + _: This, + _: *const u8, + words: *const c_char, + out: *mut *const u8, +) -> HRESULT { + tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)"); + put(out, &raw const STREAM) +} +extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT { + put(out, SILENCE.len()) +} +extern "system" fn stream_data( + _: This, + _: *const u8, + size: usize, + buffer: *mut u8, + used: *mut usize, +) -> HRESULT { + if buffer.is_null() || size < SILENCE.len() { + return super::xasync::E_NOT_SUFFICIENT_BUFFER; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) }; + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(SILENCE.len()) }; + } + S_OK +} + +static VTABLE: Methods<22> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 closed captions + missing::<4> as *const (), // 0x20 + missing::<5> as *const (), // 0x28 high contrast + missing::<6> as *const (), // 0x30 speech to text + missing::<7> as *const (), // 0x38 + enumerate_voices as *const (), // 0x40 + create as *const (), // 0x48 + close as *const (), // 0x50 + set_default_voice as *const (), // 0x58 + set_custom_voice as *const (), // 0x60 + create_stream as *const (), // 0x68 from text + close as *const (), // 0x70 a stream + stream_size as *const (), // 0x78 + stream_data as *const (), // 0x80 + missing::<17> as *const (), // 0x88 speech to text + missing::<18> as *const (), // 0x90 + missing::<19> as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + create_stream as *const (), // 0xa8 from SSML +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn streams_are_empty_wave_files() { + let this: This = &OBJECT; + type Create = extern "system" fn(This, *mut *const u8) -> HRESULT; + type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT; + type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT; + type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT; + let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0); + assert_eq!(method::<Create>(&OBJECT, 0x48)(this, &mut synth), S_OK); + let say = method::<Stream>(&OBJECT, 0x68); + assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK); + assert_eq!(method::<Size>(&OBJECT, 0x78)(this, stream, &mut size), S_OK); + let mut wav = vec![0u8; size]; + let mut used = 0; + let data = method::<Data>(&OBJECT, 0x80); + assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK); + assert_eq!( + (&wav[..4], &wav[8..16], &wav[36..40]), + (&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..]) + ); + assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000); + assert_eq!(used, 44); + } +} diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs new file mode 100644 index 000000000..585b641a1 --- /dev/null +++ b/crates/victory-hle/src/modules/storage.rs @@ -0,0 +1,240 @@ +//! Persistent local storage: a host folder of the title's own +//! (`runtime::Title::storage`, under the data directory, never the cache) +//! with the quota its manifest declares, seen by the title as a drive +//! (`files`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::path::Path; + +use super::xasync::{self, AsyncBlock, E_ABORT}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put, + put_string, +}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0xf4fa_f4d4, + 0x2d04, + 0x4fce, + [0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84], +); +pub const IID: Guid = Guid::new( + 0xd294_11df, + 0x0794, + 0x4553, + [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], +); + +/// As Grand Theft Auto VI (2026) asks for it; it calls 0x20 (path) and 0x28 +/// (space) with the same arguments. +pub const IID_2026: Guid = Guid::new( + 0x41a4_e10c, + 0x5a7e, + 0x41d9, + [0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6], +); + +pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; + +type This = *const Object; + +/// The path titles get: the root of a virtual drive over the folder. On the +/// console storage is a drive of its own, and titles rely on it: Minecraft +/// keeps only what precedes the path's last `:\` and mounts that as a +/// drive, so a host folder such as `C:\Users\..` would make it write to the +/// root of `C:`. None (the path calls fail) before the title is set. +fn folder() -> Option<String> { + let storage = runtime::title().storage; + if storage.as_os_str().is_empty() { + return None; + } + #[cfg(windows)] + return super::files::mount(&storage).map(|letter| format!("{letter}:\\")); + #[cfg(not(windows))] + None +} + +extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT { + match folder() { + Some(path) => put(out, path.len() + 1), + None => NOT_SUPPORTED, + } +} + +/// A buffer too small for the path fails with `E_FAIL`, the documented +/// Xbox result (a PC gets `ERROR_INSUFFICIENT_BUFFER`). +extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + match folder() { + Some(path) if size <= path.len() => E_FAIL, + Some(path) => put_string(&path, size, buffer, used), + None => NOT_SUPPORTED, + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SpaceInfo { + /// Writable now. + pub available_free: u64, + /// Left in the quota. + pub total_free: u64, + pub used: u64, + /// The quota. + pub total: u64, +} + +fn used_bytes(dir: &Path) -> u64 { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| match e.metadata() { + Ok(m) if m.is_dir() => used_bytes(&e.path()), + Ok(m) => m.len(), + Err(_) => 0, + }) + .sum() +} + +/// What the host disk under `dir` has free (unlimited if unknown). +pub(crate) fn disk_free(dir: &Path) -> u64 { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + let wide: Vec<u16> = dir.as_os_str().encode_wide().chain([0]).collect(); + let mut free = 0; + let null = std::ptr::null_mut(); + // SAFETY: a NUL-terminated path and a valid output. + let ok = unsafe { + windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW( + wide.as_ptr(), + &mut free, + null, + null, + ) + }; + if ok != 0 { + return free; + } + } + let _ = dir; + u64::MAX +} + +fn space() -> SpaceInfo { + let title = runtime::title(); + let used = used_bytes(&title.storage); + let free = title.storage_bytes.saturating_sub(used); + SpaceInfo { + // Writable now: the quota's rest, as far as the host disk allows. + available_free: free.min(disk_free(&title.storage)), + total_free: free, + used, + total: title.storage_bytes, + } +} + +extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT { + put(out, space()) +} + +/// Tells our prompts apart from other calls on the same block. +static PROMPT: u8 = 0; + +/// There is nobody to ask: granted when the quota has room, else declined. +extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT { + let hr = if bytes <= space().total_free { + S_OK + } else { + E_ABORT + }; + xasync::finished(block, (&raw const PROMPT).cast(), hr) +} + +extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast()) +} + +static VTABLE: Methods<8> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + path_size as *const (), // 0x18 + path as *const (), // 0x20 + space_info as *const (), // 0x28 + prompt_for_space as *const (), // 0x30 + prompt_result as *const (), // 0x38 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + 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; + type Space = extern "system" fn(This, *mut SpaceInfo) -> HRESULT; + type Prompt = extern "system" fn(This, u64, *mut AsyncBlock) -> HRESULT; + type Result = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + let this: This = &OBJECT; + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("save.dat"), [0u8; 100]).unwrap(); + runtime::set_title(runtime::Title { + id: 1, + storage: dir.path().to_owned(), + storage_bytes: 1000, + ..Default::default() + }); + + // The path is a drive root, never the host folder. + let mut size = 0; + assert_eq!(method::<Size>(&OBJECT, 0x18)(this, &mut size), S_OK); + assert_eq!(size, 4, "X:\\ and its NUL"); + let (mut buffer, mut used) = ([0u8; 4], 0); + let get = method::<Get>(&OBJECT, 0x20); + assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK); + assert_eq!(get(this, 3, buffer.as_mut_ptr(), &mut used), E_FAIL); + let drive = std::str::from_utf8(&buffer[..3]).unwrap(); + assert!(drive.ends_with(":\\"), "{drive}"); + // Title file calls on it reach the folder. + let path = format!("{drive}save.dat\0"); + let mut attributes = [0u8; 36]; + let get_attributes = super::super::files::GetFileAttributesExW; + let wide: Vec<u16> = 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, + total_free: 0, + used: 0, + total: 0, + }; + assert_eq!(method::<Space>(&OBJECT, 0x28)(this, &mut info), S_OK); + assert_eq!((info.used, info.total_free, info.total), (100, 900, 1000)); + + let prompt = method::<Prompt>(&OBJECT, 0x30); + let result = method::<Result>(&OBJECT, 0x38); + for (bytes, expect) in [(900, S_OK), (901, E_ABORT)] { + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!(prompt(this, bytes, &mut block), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), expect); + assert_eq!(result(this, &mut block), expect, "{bytes} bytes"); + } + } +} diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs new file mode 100644 index 000000000..068d75f2a --- /dev/null +++ b/crates/victory-hle/src/modules/xasync.rs @@ -0,0 +1,1337 @@ +//! XTaskQueue and XAsync: the runtime's callback queues and async-call +//! blocks, served as the task-queue provider's object from `QueryApiImpl`. +//! +//! As documented for the public API: a queue has a work port and a +//! completion port, each dispatched manually (the title calls dispatch), +//! on a thread pool, serialised on one thread, or immediately on the +//! submitting thread. A null queue handle means the process queue. An +//! async block's system area holds its status and result size, so both +//! stay readable after our state for the call is gone. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; +use std::time::Duration; + +use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing}; + +/// The task-queue provider; it is also the interface id titles ask for. +pub const PROVIDER: Guid = Guid { + data1: 0x073b_7dcb, + data2: 0x1fcf, + data3: 0x4030, + data4: [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28], +}; + +pub const E_PENDING: HRESULT = 0x8000_000A_u32 as i32; +pub const E_ABORT: HRESULT = 0x8000_4004_u32 as i32; +pub const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +pub const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; +pub const E_NOT_SUFFICIENT_BUFFER: HRESULT = 0x8007_007A_u32 as i32; +pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000_000E_u32 as i32; + +const WORK: u32 = 0; +const COMPLETION: u32 = 1; +const INFINITE: u32 = u32::MAX; + +type Callback = extern "system" fn(*mut c_void, bool); +type MonitorCallback = extern "system" fn(*mut c_void, *const Queue, u32); +type TerminatedCallback = extern "system" fn(*mut c_void); +type CompletionRoutine = extern "system" fn(*mut AsyncBlock); +type Provider = extern "system" fn(u32, *const ProviderData) -> HRESULT; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + Manual, + ThreadPool, + Serialized, + Immediate, +} + +impl Mode { + fn from_raw(mode: u32) -> Option<Mode> { + [ + Mode::Manual, + Mode::ThreadPool, + Mode::Serialized, + Mode::Immediate, + ] + .get(mode as usize) + .copied() + } +} + +/// A title callback and its context (addresses, so tasks can cross threads). +#[derive(Clone, Copy)] +struct Task { + context: usize, + callback: usize, +} + +impl Task { + fn new(context: *mut c_void, callback: Callback) -> Task { + Task { + context: context as usize, + callback: callback as usize, + } + } + + fn run(self, canceled: bool) { + // SAFETY: built from a `Callback` in `new`. + let callback: Callback = unsafe { std::mem::transmute(self.callback) }; + callback(self.context as *mut c_void, canceled); + } +} + +struct Port { + mode: Mode, + tasks: Mutex<VecDeque<Task>>, + ready: Condvar, +} + +impl Port { + fn new(mode: Mode) -> Arc<Port> { + let port = Arc::new(Port { + mode, + tasks: Mutex::default(), + ready: Condvar::new(), + }); + if mode == Mode::Serialized { + // The worker ends once it holds the last reference (every queue + // using the port is closed) and nothing is left to run. + let worker = port.clone(); + std::thread::spawn(move || { + loop { + match worker.take(1000, || false) { + Some(task) => task.run(false), + None if Arc::strong_count(&worker) == 1 => break, + None => {} + } + } + }); + } + port + } + + fn submit(&self, task: Task) { + match self.mode { + Mode::Immediate => task.run(false), + Mode::ThreadPool => POOL.submit(task), + Mode::Manual | Mode::Serialized => { + lock(&self.tasks).push_back(task); + self.ready.notify_one(); + } + } + } + + /// The next queued task, waiting up to `timeout_ms`, or until `ended` + /// (checked whenever the port is woken) says no task will come. + fn take(&self, timeout_ms: u32, ended: impl Fn() -> bool) -> Option<Task> { + let waiting = |t: &mut VecDeque<Task>| t.is_empty() && !ended(); + let tasks = lock(&self.tasks); + let mut tasks = if timeout_ms == INFINITE { + self.ready + .wait_while(tasks, waiting) + .unwrap_or_else(|e| e.into_inner()) + } else { + let timeout = Duration::from_millis(timeout_ms.into()); + self.ready + .wait_timeout_while(tasks, timeout, waiting) + .unwrap_or_else(|e| e.into_inner()) + .0 + }; + tasks.pop_front() + } +} + +/// The thread pool behind thread-pool ports: idle workers are reused, and a +/// new one starts whenever more tasks wait than workers idle, so a callback +/// that blocks on another never starves it. Workers stay for reuse. +struct Pool { + /// Queued tasks and the number of idle workers. + state: Mutex<(VecDeque<Task>, usize)>, + ready: Condvar, +} + +static POOL: Pool = Pool { + state: Mutex::new((VecDeque::new(), 0)), + ready: Condvar::new(), +}; + +impl Pool { + fn submit(&'static self, task: Task) { + let mut state = lock(&self.state); + state.0.push_back(task); + if state.0.len() > state.1 { + std::thread::spawn(move || self.work()); + } else { + self.ready.notify_one(); + } + } + + fn work(&self) { + let mut state = lock(&self.state); + loop { + while state.0.is_empty() { + state.1 += 1; + state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner()); + state.1 -= 1; + } + let task = state.0.pop_front(); + drop(state); + if let Some(task) = task { + task.run(false); + } + state = lock(&self.state); + } + } +} + +/// A queue handle is `Arc::into_raw` of this; duplicating and closing a +/// handle add and drop a reference. +pub struct Queue { + ports: [Arc<Port>; 2], + monitors: Mutex<Vec<(u64, usize, usize)>>, + terminated: AtomicBool, +} + +impl Queue { + fn new(ports: [Arc<Port>; 2]) -> Arc<Queue> { + Arc::new(Queue { + ports, + monitors: Mutex::default(), + terminated: AtomicBool::new(false), + }) + } + + fn submit(self: &Arc<Self>, port: u32, delay_ms: u32, task: Task) -> HRESULT { + if port > COMPLETION { + return E_INVALIDARG; + } + if self.terminated.load(Ordering::Acquire) { + return E_ABORT; + } + if delay_ms == 0 { + self.deliver(port, task); + } else { + let queue = self.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(delay_ms.into())); + queue.deliver(port, task); + }); + } + S_OK + } + + fn deliver(self: &Arc<Self>, port: u32, task: Task) { + self.ports[port as usize].submit(task); + // Copied out: a monitor may unregister itself. + let monitors = lock(&self.monitors).clone(); + for (_, context, callback) in monitors { + // SAFETY: stored from a `MonitorCallback` in `register_monitor`. + let callback: MonitorCallback = unsafe { std::mem::transmute(callback) }; + callback(context as *mut c_void, Arc::as_ptr(self), port); + } + } +} + +fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The process queue: `None` until first used (then a thread-pool queue), +/// `Some(None)` once the title clears it. +static PROCESS_QUEUE: Mutex<Option<Option<Arc<Queue>>>> = Mutex::new(None); + +fn process_queue() -> Option<Arc<Queue>> { + lock(&PROCESS_QUEUE) + .get_or_insert_with(|| { + Some(Queue::new([ + Port::new(Mode::ThreadPool), + Port::new(Mode::ThreadPool), + ])) + }) + .clone() +} + +/// A new reference to the queue behind `handle` (null: the process queue). +fn queue(handle: *const Queue) -> Option<Arc<Queue>> { + if handle.is_null() { + return process_queue(); + } + // SAFETY: a handle we returned, which the title has not closed. + unsafe { + Arc::increment_strong_count(handle); + Some(Arc::from_raw(handle)) + } +} + +pub fn XTaskQueueCreate(work: u32, completion: u32, out: *mut *const Queue) -> HRESULT { + let (Some(work), Some(completion)) = (Mode::from_raw(work), Mode::from_raw(completion)) else { + return E_INVALIDARG; + }; + if out.is_null() { + return E_INVALIDARG; + } + let queue = Queue::new([Port::new(work), Port::new(completion)]); + // SAFETY: checked non-null; the title passes room for a handle. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK +} + +/// A port handle points at the port, which its queue keeps alive. +pub fn XTaskQueueGetPort(handle: *const Queue, port: u32, out: *mut *const c_void) -> HRESULT { + let Some(queue) = queue(handle) else { + return E_INVALIDARG; + }; + if port > COMPLETION || out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + unsafe { out.write(Arc::as_ptr(&queue.ports[port as usize]).cast()) }; + S_OK +} + +pub fn XTaskQueueCreateComposite( + work: *const c_void, + completion: *const c_void, + out: *mut *const Queue, +) -> HRESULT { + if work.is_null() || completion.is_null() || out.is_null() { + return E_INVALIDARG; + } + let port = |p: *const c_void| { + // SAFETY: a port handle from `XTaskQueueGetPort`, whose queue is open. + unsafe { + Arc::increment_strong_count(p.cast::<Port>()); + Arc::from_raw(p.cast::<Port>()) + } + }; + let queue = Queue::new([port(work), port(completion)]); + // SAFETY: checked non-null. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK +} + +pub fn XTaskQueueDuplicateHandle(handle: *const Queue, out: *mut *const Queue) -> HRESULT { + match queue(handle) { + Some(queue) if !out.is_null() => { + // SAFETY: checked non-null. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK + } + _ => E_INVALIDARG, + } +} + +pub fn XTaskQueueCloseHandle(handle: *const Queue) { + if !handle.is_null() { + // SAFETY: a handle we returned; this drops its reference. + unsafe { Arc::decrement_strong_count(handle) }; + } +} + +/// Runs one queued callback of a manual port; false if none came in time, +/// or none can come: the queue was terminated (which ends a wait under way, +/// as a dispatcher thread's loop expects). +pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool { + let Some(queue) = queue(handle) else { + return false; + }; + let Some(port) = queue.ports.get(port as usize) else { + return false; + }; + if port.mode != Mode::Manual { + return false; + } + match port.take(timeout_ms, || queue.terminated.load(Ordering::Acquire)) { + Some(task) => { + task.run(false); + true + } + None => false, + } +} + +pub fn XTaskQueueSubmitDelayedCallback( + handle: *const Queue, + port: u32, + delay_ms: u32, + context: *mut c_void, + callback: Option<Callback>, +) -> HRESULT { + match (queue(handle), callback) { + (Some(queue), Some(callback)) => queue.submit(port, delay_ms, Task::new(context, callback)), + _ => E_INVALIDARG, + } +} + +/// Cancels what is still queued (callbacks see `canceled`), refuses new +/// work, then calls `callback`. +pub fn XTaskQueueTerminate( + handle: *const Queue, + _wait: bool, + context: *mut c_void, + callback: Option<TerminatedCallback>, +) -> HRESULT { + let Some(queue) = queue(handle) else { + return E_INVALIDARG; + }; + queue.terminated.store(true, Ordering::Release); + for port in &queue.ports { + let pending: Vec<Task> = lock(&port.tasks).drain(..).collect(); + // Dispatches waiting on this queue end: nothing more will come. + // (Those of other queues on the port see theirs is open and wait + // on.) After the lock above, so none misses both flag and wake. + port.ready.notify_all(); + for task in pending { + task.run(true); + } + } + if let Some(callback) = callback { + callback(context); + } + S_OK +} + +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +pub fn XTaskQueueRegisterMonitor( + handle: *const Queue, + context: *mut c_void, + callback: Option<MonitorCallback>, + token: *mut u64, +) -> HRESULT { + let (Some(queue), Some(callback)) = (queue(handle), callback) else { + return E_INVALIDARG; + }; + if token.is_null() { + return E_INVALIDARG; + } + let id = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed); + lock(&queue.monitors).push((id, context as usize, callback as usize)); + // SAFETY: checked non-null. + unsafe { token.write(id) }; + S_OK +} + +pub fn XTaskQueueUnregisterMonitor(handle: *const Queue, token: u64) { + if let Some(queue) = queue(handle) { + lock(&queue.monitors).retain(|m| m.0 != token); + } +} + +/// A new handle to the process queue, if there is one. +pub fn XTaskQueueGetCurrentProcessTaskQueue(out: *mut *const Queue) -> bool { + let found = process_queue(); + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(found.clone().map_or(std::ptr::null(), Arc::into_raw)) }; + } + found.is_some() +} + +pub fn XTaskQueueSetCurrentProcessTaskQueue(handle: *const Queue) { + let new = if handle.is_null() { + None + } else { + queue(handle) + }; + *lock(&PROCESS_QUEUE) = Some(new); +} + +/// An async block: what the title fills in, then the system area. +#[repr(C)] +pub struct AsyncBlock { + pub queue: *const Queue, + pub context: *mut c_void, + pub callback: Option<CompletionRoutine>, + /// Ours: [unused, status, result size, unused]. + pub internal: [usize; 4], +} + +#[repr(C)] +pub struct ProviderData { + pub block: *mut AsyncBlock, + pub buffer_size: usize, + pub buffer: *mut c_void, + pub context: *mut c_void, +} + +const OP_BEGIN: u32 = 0; +const OP_DO_WORK: u32 = 1; +const OP_GET_RESULT: u32 = 2; +const OP_CANCEL: u32 = 3; +const OP_CLEANUP: u32 = 4; + +/// One call in flight, until its result is taken or it fails. +struct Call { + provider: Provider, + context: usize, + identity: usize, + done: Mutex<bool>, + finished: Condvar, +} + +impl Call { + fn provider( + &self, + op: u32, + block: *mut AsyncBlock, + size: usize, + buffer: *mut c_void, + ) -> HRESULT { + let data = ProviderData { + block, + buffer_size: size, + buffer, + context: self.context as *mut c_void, + }; + (self.provider)(op, &data) + } +} + +/// Calls by block address. +static CALLS: LazyLock<Mutex<HashMap<usize, Arc<Call>>>> = LazyLock::new(Default::default); + +fn call(block: *mut AsyncBlock) -> Option<Arc<Call>> { + lock(&CALLS).get(&(block as usize)).cloned() +} + +/// The block's status and result-size words. +fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) { + // SAFETY: the title's block outlives the call; its system area is ours. + unsafe { + let internal = std::ptr::addr_of_mut!((*block).internal).cast::<AtomicUsize>(); + (&*internal.add(1), &*internal.add(2)) + } +} + +fn status(block: *mut AsyncBlock) -> HRESULT { + words(block).0.load(Ordering::Acquire) as u32 as i32 +} + +fn release(block: *mut AsyncBlock) { + // Unlocked before the provider runs: it may call back into us. + let removed = lock(&CALLS).remove(&(block as usize)); + if let Some(call) = removed { + call.provider(OP_CLEANUP, block, 0, std::ptr::null_mut()); + } +} + +pub fn XAsyncBegin( + block: *mut AsyncBlock, + context: *mut c_void, + identity: *const c_void, + _identity_name: *const u8, + provider: Option<Provider>, +) -> HRESULT { + let Some(provider) = provider else { + return E_INVALIDARG; + }; + if block.is_null() || call(block).is_some() { + return E_INVALIDARG; + } + let (status, size) = words(block); + status.store(E_PENDING as u32 as usize, Ordering::Release); + size.store(0, Ordering::Release); + let call = Arc::new(Call { + provider, + context: context as usize, + identity: identity as usize, + done: Mutex::new(false), + finished: Condvar::new(), + }); + lock(&CALLS).insert(block as usize, call.clone()); + // A failed begin fails the call, so the completion routine still runs. + let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut()); + if hr < 0 { + XAsyncComplete(block, hr, 0); + } + S_OK +} + +/// Queues the provider's `DoWork` on the block's work port. +pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT { + extern "system" fn work(block: *mut c_void, canceled: bool) { + let block = block.cast::<AsyncBlock>(); + let Some(call) = call(block) else { return }; + let hr = if canceled { + E_ABORT + } else { + call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut()) + }; + if hr != E_PENDING { + XAsyncComplete(block, hr, 0); + } + } + if block.is_null() || call(block).is_none() { + return E_INVALIDARG; + } + // SAFETY: a block in flight is valid. + let handle = unsafe { (*block).queue }; + match queue(handle) { + Some(queue) => queue.submit(WORK, delay_ms, Task::new(block.cast(), work)), + None => E_INVALIDARG, + } +} + +/// Records the result (the first one wins), wakes waiters and queues the +/// completion routine on the block's completion port. +pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) { + extern "system" fn complete(block: *mut c_void, _canceled: bool) { + let block = block.cast::<AsyncBlock>(); + // SAFETY: read before the status was published; see below. + if let Some(routine) = unsafe { (*block).callback } { + routine(block); + } + } + let Some(call) = call(block) else { return }; + if result == E_PENDING { + return; + } + let mut done = lock(&call.done); + if *done { + return; + } + // Read before publishing: once the status is set, the title may free + // the block. + // SAFETY: a block in flight is valid. + let (handle, routine) = unsafe { ((*block).queue, (*block).callback) }; + let (status, size) = words(block); + if result < 0 || required_size == 0 { + release(block); + } + size.store(required_size, Ordering::Release); + status.store(result as u32 as usize, Ordering::Release); + *done = true; + call.finished.notify_all(); + drop(done); + if routine.is_some() { + let task = Task::new(block.cast(), complete); + match queue(handle) { + Some(queue) if queue.submit(COMPLETION, 0, task) == S_OK => {} + _ => task.run(true), + } + } +} + +pub fn XAsyncGetStatus(block: *mut AsyncBlock, wait: bool) -> HRESULT { + if block.is_null() { + return E_INVALIDARG; + } + if wait && let Some(call) = call(block) { + let done = lock(&call.done); + drop(call.finished.wait_while(done, |d| !*d)); + } + status(block) +} + +pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + if block.is_null() || out.is_null() { + return E_INVALIDARG; + } + let hr = status(block); + // Any nonnegative completion carries a result, not just S_OK: S_FALSE + // is a success code too and a provider may return data with it. + if hr >= 0 { + // SAFETY: checked non-null. + unsafe { out.write(words(block).1.load(Ordering::Acquire)) }; + } + hr +} + +/// Asks the provider to cancel; the call fails with `E_ABORT` unless the +/// provider completed it first. +pub fn XAsyncCancel(block: *mut AsyncBlock) { + if let Some(call) = call(block) { + call.provider(OP_CANCEL, block, 0, std::ptr::null_mut()); + XAsyncComplete(block, E_ABORT, 0); + } +} + +/// Has the provider write the result into `buffer`, then ends the call. +pub fn XAsyncGetResult( + block: *mut AsyncBlock, + identity: *const c_void, + buffer_size: usize, + buffer: *mut c_void, + used: *mut usize, +) -> HRESULT { + if block.is_null() { + return E_INVALIDARG; + } + let hr = status(block); + let size = words(block).1.load(Ordering::Acquire); + if hr < 0 || size == 0 { + if hr >= 0 && !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(0) }; + } + return hr; + } + let Some(call) = call(block) else { + return E_ILLEGAL_METHOD_CALL; + }; + if call.identity != identity as usize { + return E_INVALIDARG; + } + if buffer_size < size || buffer.is_null() { + return E_NOT_SUFFICIENT_BUFFER; + } + let hr = call.provider(OP_GET_RESULT, block, buffer_size, buffer); + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(size) }; + } + release(block); + hr +} + +/// Starts a call on `block` that is already over: it completes with `hr` +/// and no result data, through the block's completion port as usual. +pub fn finished(block: *mut AsyncBlock, identity: *const c_void, hr: HRESULT) -> HRESULT { + finished_with( + block, + identity, + if hr < 0 { Err(hr) } else { Ok(Vec::new()) }, + ) +} + +/// Like [`finished`], with the bytes `XAsyncGetResult` hands out for +/// `identity` (an error has none). +pub fn finished_with( + block: *mut AsyncBlock, + identity: *const c_void, + result: Result<Vec<u8>, HRESULT>, +) -> HRESULT { + type Data = Result<Vec<u8>, HRESULT>; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data; the context is the + // boxed result until cleanup frees it. + let data = unsafe { &*data }; + let result = data.context.cast::<Data>(); + match op { + // SAFETY: boxed in `finished_with`; nothing runs after cleanup. + OP_CLEANUP => drop(unsafe { Box::from_raw(result) }), + OP_BEGIN => { + // SAFETY: as above. Copied out: completing may clean up. + let (hr, len) = match unsafe { &*result } { + Ok(bytes) => (S_OK, bytes.len()), + Err(hr) => (*hr, 0), + }; + XAsyncComplete(data.block, hr, len); + } + // SAFETY: as above; the runtime checked the buffer's size. + OP_GET_RESULT => unsafe { + if let Ok(bytes) = &*result { + data.buffer + .cast::<u8>() + .copy_from(bytes.as_ptr(), bytes.len()); + } + }, + _ => {} + } + S_OK + } + let context = Box::into_raw(Box::new(result)); + let hr = XAsyncBegin( + block, + context.cast(), + identity, + std::ptr::null(), + Some(provider), + ); + if hr < 0 { + // Refused before the call existed, so no cleanup will come. + // SAFETY: still ours. + drop(unsafe { Box::from_raw(context) }); + } + hr +} + +/// Like [`finished_with`], but the result comes from `work`, run on a +/// thread of ours; the call stays pending until it returns (a dialog, say). +pub fn pending_with( + block: *mut AsyncBlock, + identity: *const c_void, + work: impl FnOnce() -> Result<Vec<u8>, HRESULT> + Send + 'static, +) -> HRESULT { + type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>; + 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. + let data = unsafe { &*data }; + let state = data.context.cast::<Data>(); + match op { + // SAFETY: boxed in `pending_with`; nothing runs after cleanup. + 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 (block, state) = (data.block as usize, state as usize); + std::thread::spawn(move || { + let result = work.map_or(Err(E_ABORT), |work| work()); + let (hr, len) = match &result { + Ok(bytes) => (S_OK, bytes.len()), + Err(hr) => (*hr, 0), + }; + if let Ok(bytes) = result { + // SAFETY: the call is pending, so its state lives. + let state = unsafe { &*(state as *const Data) }; + state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes; + } + XAsyncComplete(block as *mut AsyncBlock, hr, len); + }); + } + // SAFETY: as above; the runtime checked the buffer's size. + OP_GET_RESULT => unsafe { + let state = (*state).lock().unwrap_or_else(|e| e.into_inner()); + data.buffer + .cast::<u8>() + .copy_from(state.1.as_ptr(), state.1.len()); + }, + _ => {} + } + S_OK + } + let state: Box<Data> = 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)); + if hr < 0 { + // SAFETY: refused before the call existed; still ours. + drop(unsafe { Box::from_raw(context) }); + } + hr +} + +/// The result of a call begun with [`finished_with`] for `identity`, as a +/// `T` written through `out`. +pub fn result<T>(block: *mut AsyncBlock, identity: *const c_void, out: *mut T) -> HRESULT { + XAsyncGetResult( + block, + identity, + size_of::<T>(), + out.cast(), + std::ptr::null_mut(), + ) +} + +/// The bytes of a value, for [`finished_with`]. +pub fn bytes<T: Copy>(value: T) -> Vec<u8> { + // SAFETY: a `Copy` value is plain data; padding bytes are never read. + unsafe { std::slice::from_raw_parts((&raw const value).cast::<u8>(), size_of::<T>()) }.to_vec() +} + +type Work = extern "system" fn(*mut AsyncBlock) -> HRESULT; + +/// Runs `work` on the block's work port as an async call of its own; its +/// return value is the call's result. +pub fn XAsyncRun(block: *mut AsyncBlock, work: Option<Work>) -> HRESULT { + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + // SAFETY: the context is the `Work` given to `XAsyncRun`. + let work = unsafe { std::mem::transmute::<*mut c_void, Work>(data.context) }; + work(data.block) + } + _ => S_OK, + } + } + let Some(work) = work else { + return E_INVALIDARG; + }; + let identity = XAsyncRun as *const c_void; + XAsyncBegin( + block, + work as *mut c_void, + identity, + std::ptr::null(), + Some(provider), + ) +} + +// The object `QueryApiImpl` returns. Each method takes the object first, +// then the API's arguments; slot offsets as titles call them. + +pub static OBJECT: Object = Object::new("task queue", &VTABLE); + +/// Its interface id is the provider's. +pub const INTERFACES: &[Interface] = &[(PROVIDER, PROVIDER, &OBJECT)]; + +type This = *const Object; +extern "system" fn m_get_status(_: This, b: *mut AsyncBlock, wait: u8) -> HRESULT { + XAsyncGetStatus(b, wait != 0) +} +extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usize) -> HRESULT { + XAsyncGetResultSize(b, out) +} +extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) { + XAsyncCancel(b) +} +extern "system" fn m_run(_: This, b: *mut AsyncBlock, work: Option<Work>) -> HRESULT { + XAsyncRun(b, work) +} +extern "system" fn m_begin( + _: This, + b: *mut AsyncBlock, + context: *mut c_void, + identity: *const c_void, + name: *const u8, + provider: Option<Provider>, +) -> HRESULT { + XAsyncBegin(b, context, identity, name, provider) +} +extern "system" fn m_schedule(_: This, b: *mut AsyncBlock, delay: u32) -> HRESULT { + XAsyncSchedule(b, delay) +} +extern "system" fn m_complete(_: This, b: *mut AsyncBlock, hr: HRESULT, size: usize) { + XAsyncComplete(b, hr, size) +} +extern "system" fn m_get_result( + _: This, + b: *mut AsyncBlock, + identity: *const c_void, + size: usize, + buffer: *mut c_void, + used: *mut usize, +) -> HRESULT { + XAsyncGetResult(b, identity, size, buffer, used) +} +extern "system" fn m_create( + _: This, + work: u32, + completion: u32, + out: *mut *const Queue, +) -> HRESULT { + XTaskQueueCreate(work, completion, out) +} +extern "system" fn m_create_composite( + _: This, + work: *const c_void, + completion: *const c_void, + out: *mut *const Queue, +) -> HRESULT { + XTaskQueueCreateComposite(work, completion, out) +} +extern "system" fn m_get_port( + _: This, + q: *const Queue, + port: u32, + out: *mut *const c_void, +) -> HRESULT { + XTaskQueueGetPort(q, port, out) +} +extern "system" fn m_duplicate(_: This, q: *const Queue, out: *mut *const Queue) -> HRESULT { + XTaskQueueDuplicateHandle(q, out) +} +extern "system" fn m_dispatch(_: This, q: *const Queue, port: u32, timeout: u32) -> bool { + XTaskQueueDispatch(q, port, timeout) +} +extern "system" fn m_close(_: This, q: *const Queue) { + XTaskQueueCloseHandle(q) +} +extern "system" fn m_submit( + _: This, + q: *const Queue, + port: u32, + context: *mut c_void, + callback: Option<Callback>, +) -> HRESULT { + XTaskQueueSubmitDelayedCallback(q, port, 0, context, callback) +} +extern "system" fn m_submit_delayed( + _: This, + q: *const Queue, + port: u32, + delay: u32, + context: *mut c_void, + callback: Option<Callback>, +) -> HRESULT { + XTaskQueueSubmitDelayedCallback(q, port, delay, context, callback) +} +extern "system" fn m_terminate( + _: This, + q: *const Queue, + wait: u8, + context: *mut c_void, + callback: Option<TerminatedCallback>, +) -> HRESULT { + XTaskQueueTerminate(q, wait != 0, context, callback) +} +extern "system" fn m_register_monitor( + _: This, + q: *const Queue, + context: *mut c_void, + callback: Option<MonitorCallback>, + token: *mut u64, +) -> HRESULT { + XTaskQueueRegisterMonitor(q, context, callback, token) +} +extern "system" fn m_unregister_monitor(_: This, q: *const Queue, token: u64) { + XTaskQueueUnregisterMonitor(q, token) +} +extern "system" fn m_get_process_queue(_: This, out: *mut *const Queue) -> bool { + XTaskQueueGetCurrentProcessTaskQueue(out) +} +extern "system" fn m_set_process_queue(_: This, q: *const Queue) { + XTaskQueueSetCurrentProcessTaskQueue(q) +} +/// The runtime's debug check that the caller is not a time-critical thread, +/// which every runtime call in a title makes first. +extern "system" fn m_check_thread(_: This) {} + +static VTABLE: Methods<31> = Methods([ + missing::<0> as *const (), // 0x00 QueryInterface + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + m_get_status as *const (), // 0x18 + m_get_result_size as *const (), // 0x20 + m_cancel as *const (), // 0x28 + m_run as *const (), // 0x30 + m_begin as *const (), // 0x38 + missing::<8> as *const (), // 0x40 + m_schedule as *const (), // 0x48 + m_complete as *const (), // 0x50 + m_get_result as *const (), // 0x58 + m_create as *const (), // 0x60 + m_create_composite as *const (), // 0x68 + m_get_port as *const (), // 0x70 + m_duplicate as *const (), // 0x78 + m_dispatch as *const (), // 0x80 + m_close as *const (), // 0x88 + m_submit as *const (), // 0x90 + m_submit_delayed as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 register a wait handle + missing::<21> as *const (), // 0xa8 unregister it + m_terminate as *const (), // 0xb0 + m_register_monitor as *const (), // 0xb8 + m_unregister_monitor as *const (), // 0xc0 + m_get_process_queue as *const (), // 0xc8 + m_set_process_queue as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 thread time-sensitivity + missing::<28> as *const (), // 0xe0 + m_check_thread as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 +]); + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicU32; + + fn slot<F: Copy>(offset: usize) -> F { + crate::modules::xgameruntime::method(&OBJECT, offset) + } + + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn count(context: *mut c_void, canceled: bool) { + RAN.fetch_add( + if canceled { 100 } else { context as u32 }, + Ordering::SeqCst, + ); + } + + #[test] + fn manual_ports_run_callbacks_when_dispatched() { + type Create = extern "system" fn(This, u32, u32, *mut *const Queue) -> HRESULT; + type Submit = extern "system" fn(This, *const Queue, u32, *mut c_void, Callback) -> HRESULT; + type Dispatch = extern "system" fn(This, *const Queue, u32, u32) -> bool; + type Close = extern "system" fn(This, *const Queue); + let this: This = &OBJECT; + let mut q = std::ptr::null(); + assert_eq!(slot::<Create>(0x60)(this, 0, 0, &mut q), S_OK); + assert_eq!( + slot::<Submit>(0x90)(this, q, COMPLETION, 5 as *mut c_void, count), + S_OK + ); + assert_eq!(RAN.load(Ordering::SeqCst), 0, "manual: nothing runs yet"); + assert!( + !slot::<Dispatch>(0x80)(this, q, WORK, 0), + "work port is empty" + ); + assert!(slot::<Dispatch>(0x80)(this, q, COMPLETION, 0)); + assert_eq!(RAN.load(Ordering::SeqCst), 5); + assert!(!slot::<Dispatch>(0x80)(this, q, COMPLETION, 0)); + slot::<Close>(0x88)(this, q); + } + + /// A provider that schedules its work and returns a u64 result. + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + XAsyncComplete(data.block, S_OK, 8); + S_OK + } + OP_GET_RESULT => { + // SAFETY: at least 8 bytes, checked by the runtime. + unsafe { data.buffer.cast::<u64>().write(data.context as u64) }; + S_OK + } + _ => S_OK, + } + } + + static COMPLETED: AtomicU32 = AtomicU32::new(0); + extern "system" fn completed(_: *mut AsyncBlock) { + COMPLETED.fetch_add(1, Ordering::SeqCst); + } + + #[test] + fn async_calls_complete_and_return_results() { + let mut q = std::ptr::null(); + // Work on a thread pool, completion dispatched by hand. + assert_eq!(XTaskQueueCreate(1, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: Some(completed), + internal: [0; 4], + }; + let identity = 0x1d as *const c_void; + assert_eq!( + XAsyncBegin( + &mut block, + 42 as *mut c_void, + identity, + std::ptr::null(), + Some(provider) + ), + S_OK + ); + assert_eq!(XAsyncGetStatus(&mut block, true), S_OK); + let mut size = 0; + assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK); + assert_eq!(size, 8); + assert_eq!(COMPLETED.load(Ordering::SeqCst), 0, "completion is manual"); + assert!(XTaskQueueDispatch(q, COMPLETION, INFINITE)); + assert_eq!(COMPLETED.load(Ordering::SeqCst), 1); + + let mut value = 0u64; + let mut small = 0u32; + let out = (&mut small as *mut u32).cast(); + assert_eq!( + XAsyncGetResult(&mut block, identity, 4, out, std::ptr::null_mut()), + E_NOT_SUFFICIENT_BUFFER + ); + let out = (&mut value as *mut u64).cast(); + let mut used = 0; + assert_eq!( + XAsyncGetResult(&mut block, identity, 8, out, &mut used), + S_OK + ); + assert_eq!((value, used), (42, 8)); + assert!(call(&mut block).is_none(), "the call ends with its result"); + XTaskQueueCloseHandle(q); + } + + #[test] + fn a_nonnegative_completion_still_returns_its_payload() { + const S_FALSE: HRESULT = 1; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + XAsyncComplete(data.block, S_FALSE, 8); + S_OK + } + OP_GET_RESULT => { + // SAFETY: the caller checked eight bytes. + unsafe { data.buffer.cast::<u64>().write(0x1234) }; + S_OK + } + _ => S_OK, + } + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + let identity = 0x77 as *const c_void; + assert_eq!( + XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), + S_OK + ); + assert!(XTaskQueueDispatch(q, WORK, 0)); + assert_eq!(XAsyncGetStatus(&mut block, false), S_FALSE); + let mut size = 0; + assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_FALSE); + assert_eq!(size, 8); + let mut value = 0u64; + let mut used = 0; + assert_eq!( + 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"); + XTaskQueueCloseHandle(q); + } + + #[test] + fn run_returns_the_work_result() { + extern "system" fn work(_: *mut AsyncBlock) -> HRESULT { + E_ABORT + } + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!( + slot::<extern "system" fn(This, *mut AsyncBlock, Option<Work>) -> HRESULT>(0x30)( + &OBJECT, + &mut block, + Some(work) + ), + S_OK + ); + assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT); + } + + #[test] + fn pool_callbacks_may_wait_for_each_other() { + static SECOND: AtomicBool = AtomicBool::new(false); + static FIRST: AtomicBool = AtomicBool::new(false); + extern "system" fn waits(_: *mut c_void, _: bool) { + let start = std::time::Instant::now(); + while !SECOND.load(Ordering::SeqCst) && start.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + FIRST.store(SECOND.load(Ordering::SeqCst), Ordering::SeqCst); + } + extern "system" fn releases(_: *mut c_void, _: bool) { + SECOND.store(true, Ordering::SeqCst); + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK); + let none = std::ptr::null_mut(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(waits)), + S_OK + ); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(releases)), + S_OK + ); + let start = std::time::Instant::now(); + while !FIRST.load(Ordering::SeqCst) && start.elapsed().as_secs() < 10 { + std::thread::sleep(Duration::from_millis(1)); + } + assert!(FIRST.load(Ordering::SeqCst)); + XTaskQueueCloseHandle(q); + } + + /// A dispatcher thread's loop, `while (XTaskQueueDispatch(queue, port, + /// INFINITE));`, ends when its queue is terminated: nothing can be + /// submitted to it any more, so nothing else would ever wake it. + #[test] + fn terminate_ends_a_waiting_dispatch() { + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn ran(_: *mut c_void, _: bool) { + RAN.fetch_add(1, Ordering::SeqCst); + } + /// Dispatches `queue`'s work until a dispatch returns false, then + /// says so. + fn dispatcher(queue: *const Queue) -> std::sync::mpsc::Receiver<()> { + let (done, ended) = std::sync::mpsc::channel(); + let queue = queue as usize; + std::thread::spawn(move || { + while XTaskQueueDispatch(queue as *const Queue, WORK, INFINITE) {} + let _ = done.send(()); + }); + ended + } + let run_one = |queue, total| { + let none = std::ptr::null_mut(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(queue, WORK, 0, none, Some(ran)), + S_OK + ); + for _ in 0..500 { + if RAN.load(Ordering::SeqCst) == total { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + panic!("callback {total} did not run"); + }; + let (long, short) = (Duration::from_secs(5), Duration::from_millis(200)); + let none = std::ptr::null_mut(); + + // Two queues on the same manual ports. + let (mut a, mut b) = (std::ptr::null(), std::ptr::null()); + assert_eq!(XTaskQueueCreate(0, 0, &mut a), S_OK); + let (mut work, mut completion) = (std::ptr::null(), std::ptr::null()); + assert_eq!(XTaskQueueGetPort(a, WORK, &mut work), S_OK); + assert_eq!(XTaskQueueGetPort(a, COMPLETION, &mut completion), S_OK); + assert_eq!(XTaskQueueCreateComposite(work, completion, &mut b), S_OK); + + let ended = dispatcher(a); + run_one(a, 1); + // The other queue's end is not this one's: the wait goes on and + // still runs what comes in. + assert_eq!(XTaskQueueTerminate(b, false, none, None), S_OK); + assert!( + ended.recv_timeout(short).is_err(), + "ended with another queue" + ); + run_one(a, 2); + // Its own queue's end is. + assert_eq!(XTaskQueueTerminate(a, false, none, None), S_OK); + assert!( + ended.recv_timeout(long).is_ok(), + "still waiting on a terminated queue" + ); + // And a dispatch that starts after the end returns at once. + assert!(!XTaskQueueDispatch(a, WORK, INFINITE)); + XTaskQueueCloseHandle(a); + XTaskQueueCloseHandle(b); + } + + #[test] + fn terminate_cancels_what_is_queued() { + static TERMINATED: AtomicBool = AtomicBool::new(false); + extern "system" fn terminated(_: *mut c_void) { + TERMINATED.store(true, Ordering::SeqCst); + } + extern "system" fn note(context: *mut c_void, canceled: bool) { + // SAFETY: the test passes a pointer to its flag. + unsafe { *context.cast::<bool>() = canceled }; + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut canceled = false; + let flag = (&mut canceled as *mut bool).cast(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)), + S_OK + ); + assert_eq!( + XTaskQueueTerminate(q, true, std::ptr::null_mut(), Some(terminated)), + S_OK + ); + assert!(canceled && TERMINATED.load(Ordering::SeqCst)); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)), + E_ABORT + ); + XTaskQueueCloseHandle(q); + } +} diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs new file mode 100644 index 000000000..46912d7c5 --- /dev/null +++ b/crates/victory-hle/src/modules/xg.rs @@ -0,0 +1,780 @@ +//! `xg_xs.dll`: the console's texture layout library. Titles ask it which +//! swizzle mode a texture should use, how large it is, where each mip and +//! slice lies, and to copy linear data into tiled memory and back. Served +//! from `victory_formats::texture`. +//! +//! Grand Theft Auto VI 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. +#![allow(non_snake_case)] +// Title code passes pointers the real library would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::atomic::{AtomicU32, Ordering}; + +use victory_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc}; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL}; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; + +/// `D3D12_RESOURCE_DESC`, whose layout field carries `0x100 | swizzle +/// mode` on the console (1 row major, 0 "pick one"). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct ResourceDesc { + pub dimension: u32, + pub alignment: u64, + pub width: u64, + pub height: u32, + pub depth_or_array: u16, + pub mips: u16, + pub format: u32, + pub samples: u32, + pub quality: u32, + pub layout: u32, + pub flags: u32, +} +const _: () = assert!(size_of::<ResourceDesc>() == 0x38); + +const SWIZZLED: u32 = 0x100; +const ROW_MAJOR: u32 = 1; +const ALLOW_RENDER_TARGET: u32 = 1; +const ALLOW_DEPTH_STENCIL: u32 = 2; +const TEXTURE_1D: u32 = 2; +const TEXTURE_3D: u32 = 4; + +/// The mode the console's library picks for a description: linear for 1D, +/// the XOR render and depth modes for targets, else 4 KiB standard +/// (`.ttpf` textures without a mode of their own use it). +/// +/// shortcut: the rule of the library's older optimal-mode function (any +/// size, 2D, 3D and cubes alike); `XGSuggestSwizzleMode` itself is newer +/// than every copy we could check. Revisit if streamed textures come out +/// scrambled. +fn suggested(desc: &ResourceDesc) -> Swizzle { + if desc.dimension == TEXTURE_1D { + Swizzle::LINEAR + } else if desc.flags & ALLOW_DEPTH_STENCIL != 0 { + Swizzle::SW_64KB_Z_X + } else if desc.flags & ALLOW_RENDER_TARGET != 0 { + Swizzle::SW_64KB_R_X + } else { + Swizzle::SW_4KB_S + } +} + +/// `(desc, flags, out layout)`; the title passes flags 0 and puts the +/// result in the description's layout field. +pub extern "system" fn XGSuggestSwizzleMode( + desc: *const ResourceDesc, + _flags: u32, + out: *mut u32, +) -> HRESULT { + // SAFETY: the title passes a description and room for the layout + // (either may be null). + match unsafe { (desc.as_ref(), out.as_mut()) } { + (Some(desc), Some(out)) => { + *out = SWIZZLED | suggested(desc).0; + S_OK + } + _ => E_INVALIDARG, + } +} + +#[repr(C)] +pub struct Computer { + vtable: &'static Vtable, + refs: AtomicU32, + desc: ResourceDesc, + mips: u32, + texture: Texture, +} + +type This = *mut Computer; + +fn computer<'a>(this: This) -> &'a Computer { + // SAFETY: called from computer methods only. + unsafe { &*this } +} + +pub extern "system" fn XGCreateTextureComputer( + desc: *const ResourceDesc, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description and room for a pointer. + let (Some(&desc), false) = (unsafe { desc.as_ref() }, out.is_null()) else { + return E_INVALIDARG; + }; + let Some(texture) = texture(&desc) else { + tracing::warn!(?desc, "no texture layout"); + return E_INVALIDARG; + }; + tracing::debug!( + width = desc.width, + height = desc.height, + format = desc.format, + layout = format_args!("{:#x}", desc.layout), + size = texture.size, + "texture computer" + ); + let mips = texture.planes[0].layout.mips.len() as u32; + let computer = Box::new(Computer { + vtable: &VTABLE, + refs: AtomicU32::new(1), + desc, + mips, + texture, + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(computer)) }; + S_OK +} + +fn texture(desc: &ResourceDesc) -> Option<Texture> { + let dimension = match desc.dimension { + TEXTURE_1D => Dimension::Tex1d, + 3 => Dimension::Tex2d, + TEXTURE_3D => Dimension::Tex3d, + _ => return None, + }; + let swizzle = match desc.layout { + 0 => suggested(desc), + ROW_MAJOR => Swizzle::LINEAR, + l if l & !0xff == SWIZZLED => Swizzle(l & 0xff), + _ => return None, + }; + let texture = Texture::new(&TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array), + mips: u32::from(desc.mips), + format: desc.format, + samples: desc.samples.max(1), + swizzle, + }) + .ok()?; + // The layout struct has room for 15 mips. + (texture.planes[0].layout.mips.len() <= MIPS).then_some(texture) +} + +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 +/// older public shape). +#[repr(C)] +#[derive(Debug, Default, Clone, Copy)] +pub struct MipOut { + pub size: u64, + pub offset: u64, + pub slice_size: u64, + pub pitch_texels: u32, + pub pitch_bytes: u32, + pub alignment: u32, + /// Width, height in elements, depth or array size. + pub padded: [u32; 3], + pub elements: [u32; 2], + pub texels: [u32; 2], + pub depth_or_array: u32, + pub samples: u32, + pub swizzle: u32, + pub bank_rotation: [u64; 2], + pub slice_depth: u32, + pub in_tail: u32, + /// Where a tail mip starts in elements: x bits 0-10, y 11-21. + pub tail_position: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PlaneOut { + /// 1 data, 7 depth, 8 stencil (metadata planes are not made). + pub usage: u32, + pub size: u64, + pub slice_size: u64, + pub offset: u64, + pub alignment: u64, + pub element_bytes: u32, + pub standard_mips: u32, + pub tail_mips: u32, + pub mips: [MipOut; MIPS], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct LayoutOut { + pub size: u64, + pub alignment: u64, + pub mips: u32, + pub planes: u32, + pub plane: [PlaneOut; 4], + pub dimension: u32, +} +const _: () = assert!(size_of::<MipOut>() == 0x70); +const _: () = assert!(size_of::<PlaneOut>() == 0x6c8); +const _: () = assert!(size_of::<LayoutOut>() == 0x1b40); + +/// The mode a tail mip is reported in: the 256-byte one of its kind (3 for +/// the render kind, which GFX10 lacks), the depth mode itself. +fn tail_swizzle(swizzle: Swizzle) -> u32 { + match swizzle.0 { + 2 | 6 | 10 | 18 | 22 | 26 => Swizzle::SW_256B_D.0, + 23 | 27 => 3, + 24 => swizzle.0, + _ => Swizzle::SW_256B_S.0, + } +} + +fn mip_out(desc: &ResourceDesc, l: &Layout, i: usize) -> MipOut { + let m = &l.mips[i]; + let bpe = u64::from(l.desc.element_bytes); + let block = l.desc.block; + let three_d = desc.dimension == TEXTURE_3D; + let array = u32::from(desc.depth_or_array).max(1); + let mut out = MipOut { + pitch_texels: m.pitch * block, + pitch_bytes: m.pitch * l.desc.element_bytes, + padded: [m.pitch, m.rows, if three_d { m.depth_pitch } else { array }], + elements: [m.width, m.height], + texels: [((desc.width >> i) as u32).max(1), (desc.height >> i).max(1)], + depth_or_array: if three_d { m.depth } else { array }, + samples: l.desc.samples, + slice_depth: l.block[2], + ..MipOut::default() + }; + let slice = u64::from(m.pitch) * u64::from(m.rows) * bpe; + let depth = u64::from(if three_d { m.depth_pitch } else { 1 }); + match m.tail { + None => { + out.offset = m.offset; + out.slice_size = slice * u64::from(l.desc.samples); + out.size = out.slice_size * depth; + out.alignment = l.alignment as u32; + out.swizzle = l.desc.swizzle.0; + } + Some(t) => { + out.in_tail = 1; + out.alignment = 256; + out.swizzle = tail_swizzle(l.desc.swizzle); + if l.thick { + // A 3D tail mip is placed by position, not by offset. + out.slice_size = l.alignment / u64::from(l.block[2]); + out.tail_position = t.x | t.y << 11; + } else { + out.offset = u64::from(t.offset); + out.slice_size = slice; + } + out.size = out.slice_size * depth; + } + } + out +} + +extern "system" fn add_ref(this: This) -> u32 { + computer(this).refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +extern "system" fn release(this: This) -> u32 { + let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: made by `Box::into_raw` in `XGCreateTextureComputer`; the + // last reference is gone. + drop(unsafe { Box::from_raw(this) }); + } + left +} + +extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let c = computer(this); + // SAFETY: the title passes room for the layout; every field is plain + // data, so zeroes are a valid start. + let out = unsafe { + out.write_bytes(0, 1); + &mut *out + }; + out.size = c.texture.size; + out.alignment = c.texture.alignment; + out.mips = c.mips; + out.planes = c.texture.planes.len() as u32; + out.dimension = c.desc.dimension; + // The library calls a depth plane "depth" only beside stencil or + // without mips. + let depth = + c.desc.flags & ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1); + for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) { + let l = &p.layout; + plane.usage = match (p.stencil, depth) { + (true, _) => 8, + (false, true) => 7, + (false, false) => 1, + }; + plane.size = l.size; + plane.slice_size = l.slice_size; + plane.offset = p.offset; + plane.alignment = l.alignment; + plane.element_bytes = l.desc.element_bytes; + plane.standard_mips = l.first_tail_mip; + plane.tail_mips = c.mips - l.first_tail_mip; + for (i, mip) in plane.mips.iter_mut().take(l.mips.len()).enumerate() { + *mip = mip_out(&c.desc, l, i); + } + } + S_OK +} + +/// The plane, its mip and array slice for a subresource index, and the +/// tiled bytes and the linear bytes the copy touches. +struct CopyArgs<'a> { + layout: &'a Layout, + mip: u32, + slice: u32, + tiled: usize, + linear: usize, +} + +fn copy_args( + c: &Computer, + plane: u32, + subresource: u32, + row: u32, + depth: u32, +) -> Option<CopyArgs<'_>> { + let p = c.texture.planes.get(plane as usize)?; + let l = &p.layout; + let (mip, slice) = (subresource % c.mips, subresource / c.mips); + let m = l.mips.get(mip as usize)?; + let bytes = m.width as usize * l.desc.element_bytes as usize; + let depths = l.subresource_depth(mip) as usize; + let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes; + Some(CopyArgs { + layout: l, + mip, + slice, + tiled: (p.offset + l.size) as usize, + linear, + }) +} + +fn result(r: Result<(), Error>) -> HRESULT { + match r { + Ok(()) => S_OK, + Err(Error::Unsupported) => E_NOTIMPL, + Err(_) => E_INVALIDARG, + } +} + +/// `(tiled base, plane, subresource, linear, row pitch, depth pitch)`. +extern "system" fn copy_into( + this: This, + tiled: *mut u8, + plane: u32, + subresource: u32, + linear: *const u8, + row: u32, + depth: u32, +) -> HRESULT { + let c = computer(this); + let Some(a) = copy_args(c, plane, subresource, row, depth) else { + return E_INVALIDARG; + }; + if tiled.is_null() || linear.is_null() { + return E_INVALIDARG; + } + let offset = c.texture.planes[plane as usize].offset as usize; + // SAFETY: the title's memory holds the whole texture and its rows. + let (tiled, linear) = unsafe { + ( + std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts(linear, a.linear), + ) + }; + let r = a + .layout + .tile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); + if r.is_err() { + tracing::warn!(?r, desc = ?c.desc, subresource, "copy into a texture failed"); + } + result(r) +} + +/// `(linear, plane, subresource, sample, tiled base, row pitch, depth +/// pitch)`. +#[allow(clippy::too_many_arguments)] +extern "system" fn copy_from( + this: This, + linear: *mut u8, + plane: u32, + subresource: u32, + _sample: u32, + tiled: *const u8, + row: u32, + depth: u32, +) -> HRESULT { + let c = computer(this); + let Some(a) = copy_args(c, plane, subresource, row, depth) else { + return E_INVALIDARG; + }; + if tiled.is_null() || linear.is_null() { + return E_INVALIDARG; + } + let offset = c.texture.planes[plane as usize].offset as usize; + // SAFETY: the title's memory holds the whole texture and its rows. + let (tiled, linear) = unsafe { + ( + std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts_mut(linear, a.linear), + ) + }; + let r = a + .layout + .detile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); + if r.is_err() { + tracing::warn!(?r, desc = ?c.desc, subresource, "copy out of a texture failed"); + } + result(r) +} + +#[repr(C)] +pub struct PackedMips { + pub standard: u8, + pub packed: u8, + pub tiles: u32, + pub start: u32, +} + +#[repr(C)] +pub struct SubresourceTiling { + pub width: u32, + pub height: u16, + pub depth: u16, + pub start: u32, +} + +const TILE: u64 = 64 << 10; + +/// `(total tiles, packed mips, tile shape in texels, in: room / out: +/// count, first, subresource tilings)`, in 64 KiB tiles of plane 0, for 2D +/// 64 KiB modes only (others fail, as on the console). The mip tail is the +/// packed part, tile 0 of each slice; tilings list the standard mips of +/// every slice in turn. With a tail the console's library lists two slices +/// at most and zeroes all but the first; so do we (the title reads slice 0 +/// only). +extern "system" fn tiling( + this: This, + tiles: *mut u32, + packed: *mut PackedMips, + shape: *mut [u32; 3], + count: *mut u32, + first: u32, + out: *mut SubresourceTiling, +) -> HRESULT { + let c = computer(this); + let l = &c.texture.planes[0].layout; + if l.alignment != TILE { + return E_FAIL; + } + if l.thick { + return E_NOTIMPL; + } + let standard = l.first_tail_mip; + let tail = standard < c.mips; + let tail_tiles = match standard { + 0 => l.slice_size / TILE, + s if s < c.mips => l.mips[s as usize - 1].offset / TILE, + _ => 0, + }; + let block = l.desc.block; + // SAFETY: each output is null or room for its value; `out` has room + // for `*count` entries. + unsafe { + if let Some(t) = tiles.as_mut() { + *t = (l.size / TILE) as u32; + } + if let Some(p) = packed.as_mut() { + *p = PackedMips { + standard: standard as u8, + packed: (c.mips - standard) as u8, + tiles: tail_tiles as u32, + start: 0, + }; + } + if let Some(s) = shape.as_mut() { + *s = [l.block[0] * block, l.block[1] * block, l.block[2]]; + } + if let Some(n) = count.as_mut() { + let slices = if tail { l.slices.min(2) } else { l.slices }; + let wanted = (standard * slices).saturating_sub(first).min(*n); + for i in 0..wanted { + let (slice, mip) = ((first + i) / standard, (first + i) % standard); + let m = &l.mips[mip as usize]; + let entry = if tail && slice > 0 { + SubresourceTiling { + width: 0, + height: 0, + depth: 0, + start: 0, + } + } else { + SubresourceTiling { + width: m.pitch / l.block[0], + height: (m.rows / l.block[1]) as u16, + depth: 1, + start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32, + } + }; + out.add(i as usize).write(entry); + } + *n = wanted; + } + } + S_OK +} + +/// 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 +/// 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( + this: This, + plane: u32, + mip: u32, + x: u64, + y: u32, + z: u32, + _sample: u32, + bit: *mut u32, +) -> u64 { + if !bit.is_null() { + // SAFETY: the caller passes room for the bit position or null. + unsafe { bit.write(0) }; + } + let Some(p) = computer(this).texture.planes.get(plane as usize) else { + return 0; + }; + let x = u32::try_from(x).unwrap_or(u32::MAX); + match p.layout.offset(mip, x, y, z) { + Ok(at) => p.offset + at, + Err(e) => { + tracing::warn!(?e, mip, x, y, z, "texel outside its texture"); + 0 + } + } +} + +/// Slots the title does not call: size, alignment, offsets, coordinates, +/// view descriptor, tiled-resource query. +extern "system" fn unused(this: This) -> HRESULT { + tracing::warn!(desc = ?computer(this).desc, "unimplemented texture computer method"); + E_NOTIMPL +} + +#[repr(C)] +struct Vtable([*const (); 13]); +// SAFETY: function addresses only. +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 + 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? +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xg", + dlls: &["xg_xs.dll"], + exports: vec![ + hle_export!(XGCreateTextureComputer), + hle_export!(XGSuggestSwizzleMode), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(width: u64, height: u32, mips: u16, format: u32, layout: u32) -> ResourceDesc { + ResourceDesc { + dimension: 3, + alignment: 0, + width, + height, + depth_or_array: 1, + mips, + format, + samples: 1, + quality: 0, + layout, + flags: 0, + } + } + + /// Method `index` of a computer, as the title calls it. + fn slot<T: Copy>(c: This, index: usize) -> T { + // SAFETY: the computer is live; T is the slot's function type. + unsafe { std::mem::transmute_copy(&(*c).vtable.0[index]) } + } + + fn create(d: &ResourceDesc) -> This { + let mut c = std::ptr::null_mut(); + assert_eq!(XGCreateTextureComputer(d, &mut c), S_OK); + c + } + + /// Element offsets: linear rows of 1 KiB (128 elements), 0 outside. + #[test] + fn element_offsets_follow_the_layout() { + type Offset = extern "system" fn(This, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let c = create(&desc(128, 4, 1, 11, 0x100)); + let offset: Offset = slot(c, 6); + let mut bit = 7; + assert_eq!(offset(c, 0, 0, 3, 1, 0, 0, &mut bit), (128 + 3) * 8); + assert_eq!(bit, 0); + assert_eq!(offset(c, 0, 0, 128, 0, 0, 0, std::ptr::null_mut()), 0); + slot::<extern "system" fn(This) -> u32>(c, 1)(c); + } + + #[test] + fn suggestions_follow_the_use() { + let mut out = 0; + let mut d = desc(256, 256, 1, 98, 0); + assert_eq!(XGSuggestSwizzleMode(&d, 0, &mut out), S_OK); + assert_eq!(out, 0x105); + d.flags = ALLOW_RENDER_TARGET; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x11b); + d.flags = ALLOW_DEPTH_STENCIL; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x118); + } + + /// The title's calls: layout, then a copy in and out of each mip. + #[test] + fn layout_and_copies_through_the_object() { + // 256x256 BC7, full chain, 64 KiB display mode. + let c = create(&desc(256, 256, 0, 98, 0x10a)); + // SAFETY: plain data, filled by the call. + let mut l: Box<LayoutOut> = Box::new(unsafe { std::mem::zeroed() }); + let get: extern "system" fn(This, *mut LayoutOut) -> HRESULT = slot(c, 2); + assert_eq!(get(c, &mut *l), S_OK); + assert_eq!( + (l.size, l.alignment, l.mips, l.planes), + (131072, 65536, 9, 1) + ); + let p = &l.plane[0]; + assert_eq!((p.standard_mips, p.tail_mips, p.element_bytes), (1, 8, 16)); + assert_eq!((p.mips[0].offset, p.mips[0].pitch_bytes), (65536, 1024)); + assert_eq!((p.mips[1].offset, p.mips[1].in_tail), (32768, 1)); + + type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; + type From = + extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT; + let (into, from): (Into, From) = (slot(c, 8), slot(c, 9)); + let mut tiled = vec![0u8; l.size as usize]; + for mip in 0..9u32 { + let m = &p.mips[mip as usize]; + let row = m.elements[0] * 16; + let rows: Vec<u8> = (0..row * m.elements[1]).map(|i| (i ^ mip) as u8).collect(); + assert_eq!( + into(c, tiled.as_mut_ptr(), 0, mip, rows.as_ptr(), row, 0), + S_OK + ); + let mut back = vec![0u8; rows.len()]; + assert_eq!( + from(c, back.as_mut_ptr(), 0, mip, 0, tiled.as_ptr(), row, 0), + S_OK + ); + assert_eq!(back, rows, "mip {mip}"); + } + // 0x50: one tile for the tail, one for mip 0. + type Tiling = extern "system" fn( + This, + *mut u32, + *mut PackedMips, + *mut [u32; 3], + *mut u32, + u32, + *mut SubresourceTiling, + ) -> HRESULT; + let tiling: Tiling = slot(c, 10); + let (mut tiles, mut shape, mut n) = (0, [0; 3], 4); + let mut packed = PackedMips { + standard: 0, + packed: 0, + tiles: 0, + start: 0, + }; + let mut subs: Vec<SubresourceTiling> = (0..4) + .map(|_| SubresourceTiling { + width: 0, + height: 0, + depth: 0, + start: 0, + }) + .collect(); + assert_eq!( + tiling( + c, + &mut tiles, + &mut packed, + &mut shape, + &mut n, + 0, + subs.as_mut_ptr() + ), + S_OK + ); + assert_eq!( + (tiles, packed.standard, packed.packed, packed.tiles), + (2, 1, 8, 1) + ); + assert_eq!((shape, n, subs[0].start), ([256, 256, 1], 1, 1)); + assert_eq!(release(c), 0); + + // 4 KiB modes have no 64 KiB tiling. + let null = std::ptr::null_mut::<u8>(); + let c = create(&desc(256, 256, 0, 98, 0x105)); + assert_eq!( + tiling( + c, + &mut tiles, + null.cast(), + null.cast(), + null.cast(), + 0, + null.cast() + ), + E_FAIL + ); + assert_eq!(release(c), 0); + } + + #[test] + fn bad_descriptions_fail() { + let mut c = std::ptr::null_mut(); + let bad = desc(256, 256, 1, 0, 0x10a); + assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); + let bad = desc(256, 256, 1, 28, 0x103); + assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); + assert!(module().exports.len() == 2); + } +} diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs new file mode 100644 index 000000000..c54f8378f --- /dev/null +++ b/crates/victory-hle/src/modules/xgame.rs @@ -0,0 +1,241 @@ +//! The title's own id (from its manifest), which runtime areas exist, and +//! game invites and events. Offline no invite arrives and events go +//! nowhere. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token, +}; +use crate::runtime; + +/// Title id and launching another title. +pub const TITLE_PROVIDER: Guid = Guid::new( + 0x973a_344e, + 0x24bf, + 0x4d0f, + [0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29], +); +/// As Minecraft (2022) asks for it. +pub const TITLE_IID: Guid = Guid::new( + 0x2549_f142, + 0x6419, + 0x4a06, + [0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34], +); +/// Feature checks; the interface id is the provider's, as for the next two. +pub const FEATURES: Guid = Guid::new( + 0x8836_fe87, + 0xedb9, + 0x4fe3, + [0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40], +); +pub const INVITES: Guid = Guid::new( + 0x0651_aae2, + 0x4012, + 0x4077, + [0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c], +); +pub const EVENTS: Guid = Guid::new( + 0xbbfb_dcc7, + 0xbfe7, + 0x409b, + [0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d], +); + +pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE); +pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE); +pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE); +pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT), + (FEATURES, FEATURES, &FEATURES_OBJECT), + (INVITES, INVITES, &INVITES_OBJECT), + (EVENTS, EVENTS, &EVENTS_OBJECT), +]; + +type This = *const Object; + +extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT { + put(out, runtime::title().id) +} + +/// 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 +/// 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). +extern "system" fn launch_new_game( + _: This, + exe: *const c_char, + args: *const c_char, + _user: *const c_void, +) { + 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); + super::lifecycle::end_title( + "XLaunchNewGame", + Box::new(move || super::lifecycle::relaunch(command)), + ); + loop { + std::thread::park(); + } +} + +/// Our own arguments for the relaunch: the title's executable replaced by +/// `exe`, earlier title arguments dropped, `args` after `--`. +fn relaunch_args( + ours: Vec<std::ffi::OsString>, + current: &std::ffi::OsStr, + exe: &str, + args: &str, +) -> Vec<std::ffi::OsString> { + let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect(); + if !exe.is_empty() + && let Some(slot) = out.iter_mut().find(|a| a.as_os_str() == current) + { + *slot = exe.into(); + } + if !args.trim().is_empty() { + out.push("--".into()); + out.extend(args.split_whitespace().map(Into::into)); + } + out +} + +/// Runtime areas by number, in the public feature list's order, that we +/// serve: accessibility (0), app capture (1), async calls and providers +/// (2, 3), display (4), game (5), invites (6), game saves (7), game UI (8), +/// launcher (9), networking (10), packages (11), persistent local storage +/// (12), speech synthesis (13), store (14), system (15), task queues (16), +/// users (18), error reports (19), game events (20). Not threads (17) or +/// game streaming (21). +const AVAILABLE: [u32; 20] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, +]; + +extern "system" fn is_feature_available(_: This, feature: u32) -> bool { + AVAILABLE.contains(&feature) +} + +/// Nothing raises these events offline, so the callback never runs. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +/// Accepted and dropped; the name goes to the debug log. +extern "system" fn write_event( + _: This, + _user: *const c_void, + _service_config: *const c_char, + _session: *const c_char, + name: *const c_char, + _dimensions: *const c_char, + _measurements: *const c_char, +) -> HRESULT { + if !name.is_null() { + // SAFETY: a non-null name is a NUL-terminated string. + let name = unsafe { CStr::from_ptr(name) }.to_string_lossy(); + tracing::debug!(%name, "game event dropped"); + } + S_OK +} + +static TITLE_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + title_id as *const (), // 0x18 + launch_new_game as *const (), // 0x20 +]); + +static FEATURES_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + is_feature_available as *const (), // 0x18 +]); + +static INVITES_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + register as *const (), // 0x18 + unregister as *const (), // 0x20 +]); + +static EVENTS_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + write_event as *const (), // 0x18 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn a_relaunch_keeps_our_options() { + let ours: Vec<std::ffi::OsString> = + ["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", "--"]; + assert_eq!(again[..6], expected.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"); + } + + #[test] + fn served_areas_are_available_others_not() { + type Check = extern "system" fn(This, u32) -> bool; + let check = method::<Check>(&FEATURES_OBJECT, 0x18); + assert!(check(&FEATURES_OBJECT, 18), "users"); + assert!(!check(&FEATURES_OBJECT, 21), "game streaming"); + + type Register = extern "system" fn( + This, + *const c_void, + *mut c_void, + *const c_void, + *mut u64, + ) -> HRESULT; + type Unregister = extern "system" fn(This, u64, bool) -> bool; + let null = std::ptr::null(); + let mut token = 0; + let register = method::<Register>(&INVITES_OBJECT, 0x18); + assert_eq!( + register(&INVITES_OBJECT, null, null as _, null, &mut token), + S_OK + ); + assert_ne!(token, 0); + assert!(method::<Unregister>(&INVITES_OBJECT, 0x20)( + &INVITES_OBJECT, + token, + true + )); + } +} diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs new file mode 100644 index 000000000..3201a90e1 --- /dev/null +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -0,0 +1,344 @@ +//! `xgameruntime.dll`: the console game runtime (XGame*, XUser*, XTaskQueue*...). +//! +//! Titles rarely import it. A stub linked into the title loads the DLL with +//! `LoadLibraryExA` (answered with a pseudo handle, see `kernel`), looks up +//! the `*ApiImpl` functions and `XErrorReport` with `GetProcAddress`, and +//! initialises. Each runtime API call then asks `QueryApiImpl` for a COM-style +//! object of its area (provider and interface GUIDs), calls one method and +//! releases it. Until an area is implemented its query fails, and the call +//! returns that error without touching the object. An area's interface id +//! changes when its method table does, so each object answers only the ids +//! whose slots we know. Implemented, as an offline retail console with one +//! signed-in user: task queues and async blocks (`xasync`), the user +//! (`xuser`), system information (`xsystem`), title id, feature checks, +//! invites and events (`xgame`), persistent local storage (`storage`), game +//! saves (`xgamesave`), networking (`xnetworking`), the package +//! (`xpackage`), the store (`xstore`), system dialogs (`xgameui`), speech +//! (`speech`), HDR, URIs, display deferrals and screenshots (`display`). +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_char, c_void}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::{ + display, speech, storage, xasync, xgame, xgamesave, xgameui, xnetworking, xpackage, xstore, + xsystem, xuser, +}; +use crate::{HleModule, hle_export}; + +pub type HRESULT = i32; +pub const S_OK: HRESULT = 0; +/// `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)`. +pub const NOT_SUPPORTED: HRESULT = 0x8007_0032_u32 as i32; + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Guid { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], +} + +impl Guid { + pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid { + Guid { + data1, + data2, + data3, + data4, + } + } +} + +impl std::fmt::Display for Guid { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let d = self.data4; + write!( + f, + "{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", + self.data1, self.data2, self.data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7] + ) + } +} + +/// A runtime object as title code calls it: its first word points at the +/// method table. Ours are static, so reference counting is a no-op. +#[repr(C)] +pub struct Object { + vtable: *const *const (), + /// Named in the log when a title calls a method we lack. + area: &'static str, +} + +// SAFETY: the table is a static array of function addresses. +unsafe impl Sync for Object {} + +impl Object { + pub const fn new<const N: usize>(area: &'static str, methods: &'static Methods<N>) -> Object { + Object { + vtable: methods.0.as_ptr(), + area, + } + } +} + +/// An object's method table, by slot (`QueryInterface`, `AddRef`, +/// `Release`, then the area's methods from offset 0x18). +pub struct Methods<const N: usize>(pub [*const (); N]); + +// SAFETY: function addresses only. +unsafe impl<const N: usize> Sync for Methods<N> {} + +/// A (provider, interface id) pair a title may ask for, and our object. +pub type Interface = (Guid, Guid, &'static Object); + +const AREAS: &[&[Interface]] = &[ + xasync::INTERFACES, + xuser::INTERFACES, + xsystem::INTERFACES, + xgame::INTERFACES, + storage::INTERFACES, + xnetworking::INTERFACES, + xpackage::INTERFACES, + display::INTERFACES, + xgamesave::INTERFACES, + xstore::INTERFACES, + xgameui::INTERFACES, + speech::INTERFACES, +]; + +/// `AddRef` and `Release`. +pub extern "system" fn add_ref(_: *const Object) -> u32 { + 1 +} + +/// A slot nobody has needed yet; logged with its area. Wrong for a slot +/// that returns `bool` or a value. +pub extern "system" fn missing<const SLOT: usize>(this: *const Object) -> HRESULT { + // SAFETY: title code calls methods on objects we handed out. + let area = unsafe { (*this).area }; + tracing::warn!( + area, + slot = format_args!("{:#x}", SLOT * 8), + "runtime method not implemented" + ); + xasync::E_NOTIMPL +} + +/// Writes `value` through `out` if it is non-null. +pub fn put<T>(out: *mut T, value: T) -> HRESULT { + if out.is_null() { + return xasync::E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes room for a `T`. + unsafe { out.write(value) }; + S_OK +} + +/// Copies `text` and a NUL into the title's `size`-byte buffer and reports +/// 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 { + return xasync::E_NOT_SUFFICIENT_BUFFER; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { + buffer.copy_from_nonoverlapping(text.as_ptr(), text.len()); + buffer.add(text.len()).write(0); + } + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(len) }; + } + S_OK +} + +/// The title's NUL-terminated string, if any. +pub fn text(s: *const c_char) -> Option<String> { + // SAFETY: the title passes a NUL-terminated string or null. + (!s.is_null()).then(|| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned()) +} + +/// A new registration token for callbacks we never call (events nobody +/// raises offline). +pub fn token() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + +/// Calls method `slot` (byte offset) of `object` as title code would. +#[cfg(test)] +pub(crate) fn method<F: Copy>(object: &Object, slot: usize) -> F { + // SAFETY: the caller names the slot's signature; tables cover the slots + // tests use. + unsafe { std::mem::transmute_copy(&*object.vtable.add(slot / 8)) } +} + +pub extern "system" fn XGameRuntimeInitialize() -> HRESULT { + tracing::info!("XGameRuntimeInitialize"); + S_OK +} + +pub extern "system" fn XGameRuntimeUninitialize() { + tracing::info!("XGameRuntimeUninitialize"); +} + +/// The arguments identify the title's build of the stub; not checked. +pub extern "system" fn InitializeApiImpl(version: u64, build: u64) -> HRESULT { + tracing::info!(version, build, "InitializeApiImpl"); + S_OK +} + +pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) -> HRESULT { + tracing::info!(version, build, flags, "InitializeApiImplEx"); + S_OK +} + +/// 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). +pub extern "system" fn InitializeApiImplEx2( + version: u64, + build: u64, + flags: u64, + options: *const c_void, +) -> HRESULT { + tracing::info!(version, build, flags, ?options, "InitializeApiImplEx2"); + S_OK +} + +pub extern "system" fn UninitializeApiImpl() { + tracing::info!("UninitializeApiImpl"); +} + +/// The object for an implemented (provider, interface id); others fail, +/// each pair logged once. +pub extern "system" fn QueryApiImpl( + provider: *const Guid, + iid: *const Guid, + out: *mut *mut c_void, +) -> HRESULT { + static QUERIED: Mutex<Vec<(Guid, Guid)>> = Mutex::new(Vec::new()); + // SAFETY: the title passes pointers to GUIDs (null is tolerated). + let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() }) + else { + return NOT_SUPPORTED; + }; + #[cfg(feature = "diagnostics")] + if tracing::enabled!(tracing::Level::DEBUG) { + // Each runtime call site once: which title code uses which area, when. + static CALLS: Mutex<Vec<String>> = Mutex::new(Vec::new()); + let from = super::kernel::callers(); + let mut calls = CALLS.lock().unwrap_or_else(|e| e.into_inner()); + if !calls.contains(&from) { + tracing::debug!(%provider, %iid, %from, "runtime call"); + calls.push(from); + } + } + let found = AREAS + .iter() + .flat_map(|area| area.iter()) + .find(|(p, i, _)| (*p, *i) == (provider, iid)); + 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; + } + let mut queried = QUERIED.lock().unwrap_or_else(|e| e.into_inner()); + if !queried.contains(&(provider, iid)) { + queried.push((provider, iid)); + tracing::warn!(%provider, %iid, "runtime API area not implemented"); + } + NOT_SUPPORTED +} + +pub extern "system" fn XErrorReport(hr: HRESULT, message: *const c_char) { + let message = if message.is_null() { + "".into() + } else { + // SAFETY: a non-null message is a NUL-terminated string. + unsafe { CStr::from_ptr(message) }.to_string_lossy() + }; + tracing::warn!(hr = format_args!("{:#010x}", hr as u32), %message, "XErrorReport"); +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xgameruntime", + dlls: &["xgameruntime.dll"], + exports: vec![ + hle_export!(XGameRuntimeInitialize), + hle_export!(XGameRuntimeUninitialize), + hle_export!(InitializeApiImpl), + hle_export!(InitializeApiImplEx), + hle_export!(InitializeApiImplEx2), + hle_export!(UninitializeApiImpl), + hle_export!(QueryApiImpl), + hle_export!(XErrorReport), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryExA}; + + #[test] + fn title_stub_loads_the_runtime_dynamically() { + let load = |name: &CStr| LoadLibraryExA(name.as_ptr().cast(), std::ptr::null_mut(), 0x800); + let runtime = load(c"xgameruntime.dll"); + assert!(!runtime.is_null()); + let proc = |name: &CStr| GetProcAddress(runtime, name.as_ptr().cast()); + for name in [ + c"InitializeApiImpl", + c"InitializeApiImplEx", + c"InitializeApiImplEx2", + c"QueryApiImpl", + c"UninitializeApiImpl", + c"XErrorReport", + ] { + assert!(!proc(name).is_null(), "{name:?}"); + } + assert!(proc(c"NotAnExport").is_null()); + let ordinal = std::ptr::without_provenance::<u8>(1); + assert!(GetProcAddress(runtime, ordinal).is_null()); + + type Init = extern "system" fn(u64, u64, u64) -> HRESULT; + type Query = extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> HRESULT; + // SAFETY: the addresses are our functions with these signatures. + let (init, query) = unsafe { + ( + std::mem::transmute::<*mut c_void, Init>(proc(c"InitializeApiImplEx")), + std::mem::transmute::<*mut c_void, Query>(proc(c"QueryApiImpl")), + ) + }; + assert_eq!(init(1, 2, 2), S_OK); + let guid = Guid { + data1: 1, + data2: 2, + data3: 3, + data4: [4; 8], + }; + let untouched = 0x1234 as *mut c_void; + let mut out = untouched; + assert!(query(&guid, &guid, &mut out) < 0); + assert_eq!(out, untouched); + assert_eq!(FreeLibrary(runtime), 1); + + #[cfg(windows)] + { + let kernel32 = load(c"kernel32.dll"); + assert!(!kernel32.is_null(), "host DLLs still load from the host"); + assert!(!GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()).is_null()); + } + } +} diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs new file mode 100644 index 000000000..d77ac8a70 --- /dev/null +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -0,0 +1,1355 @@ +//! XGameSave: the user's game saves, kept on the host under the title's +//! data directory, next to persistent local storage (`runtime::Title:: +//! saves`), never in the cache. A provider is a folder per user and +//! service configuration, a container a folder in it. +//! +//! An update is all or nothing, as documented: each one writes a complete +//! new version of the container (`v<N>.new/`, unchanged blobs hard-linked +//! from the previous version), flushed to disk, and one directory rename +//! commits it (`v<N>`); the highest committed version is the container. +//! A crash leaves the old version or the new one, never a mix; leftovers +//! are removed on sight. Deleting a container renames it away first. +//! +//! Names are exact: a version's `manifest` holds the container's name, its +//! display name and the blob names (blob `i` is the file `i`), so case, +//! characters the host forbids, reserved device names and length never +//! reach a file name. A container's folder is its name made safe (and +//! shortened) plus a hash of the exact name, so names differing only in +//! case get different folders. Offline there is no cloud copy, so nothing +//! ever needs a sync. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CString, c_char, c_void}; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use super::xasync::{self, AsyncBlock, E_INVALIDARG}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; +use super::{storage, xuser}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0x704c_3f58, + 0xe629, + 0x4cc2, + [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2], +); +/// As Grand Theft Auto VI (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( + 0x1bff_f3af, + 0xf14a, + 0x40a3, + [0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9], +); + +pub static OBJECT: Object = Object::new("game save", &VTABLE); +pub const INTERFACES: &[Interface] = + &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +// The public API's error codes. +pub const INVALID_CONTAINER_NAME: HRESULT = 0x8083_0001_u32 as i32; +pub const NO_ACCESS: HRESULT = 0x8083_0002_u32 as i32; +pub const OUT_OF_LOCAL_STORAGE: HRESULT = 0x8083_0003_u32 as i32; +pub const UPDATE_TOO_BIG: HRESULT = 0x8083_0005_u32 as i32; +pub const QUOTA_EXCEEDED: HRESULT = 0x8083_0006_u32 as i32; +pub const BUFFER_TOO_SMALL: HRESULT = 0x8083_0007_u32 as i32; +pub const BLOB_NOT_FOUND: HRESULT = 0x8083_0008_u32 as i32; + +/// Per user and title, as documented. +const QUOTA: u64 = 256 << 20; +/// What one update may write in all, as documented. +const MAX_UPDATE: usize = 16 << 20; +const MANIFEST: &str = "manifest"; +/// Readable part of a container's folder name, at most. +const READABLE: usize = 100; + +/// Every save operation, so none sees another's half-made version. +static SAVES: Mutex<()> = Mutex::new(()); + +fn saves_lock() -> std::sync::MutexGuard<'static, ()> { + SAVES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// `name` as a file name: letters, digits, `-` and `_` stay, every other +/// byte becomes `%XX`. The result never contains a dot. +fn file_name(name: &str) -> String { + name.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' => (b as char).to_string(), + _ => format!("%{b:02X}"), + }) + .collect() +} + +/// The name behind a file name from [`file_name`]; `None` for other files. +fn decode(file: &str) -> Option<String> { + if file.contains('.') { + return None; + } + let mut out = Vec::new(); + let mut bytes = file.bytes(); + while let Some(b) = bytes.next() { + if b == b'%' { + let hex = [bytes.next()?, bytes.next()?]; + out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?); + } else { + out.push(b); + } + } + String::from_utf8(out).ok() +} + +/// The container's folder: its name made safe, cut short, then `~` and a +/// hash of the exact name (64-bit FNV-1a, stable across builds). +fn container_dir(root: &Path, name: &str) -> PathBuf { + let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); + let mut readable = file_name(name); + readable.truncate(READABLE); // ASCII only + root.join(format!("{readable}~{hash:016x}")) +} + +/// Documented: the path part (up to the last `/`) letters, digits, `_` and +/// `/`; the file part letters, digits, `_`, `.` and `-`, not empty, not +/// ending in `.`, no `..`; 256 characters at most. +fn valid_container(name: &str) -> bool { + let (path, file) = name.rsplit_once('/').unwrap_or(("", name)); + name.len() <= 256 + && path + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/') + && !file.is_empty() + && !file.ends_with('.') + && !file.contains("..") + && file + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) +} + +/// A committed version of a container. +struct Version { + dir: PathBuf, + number: u64, + name: String, + display: String, + /// Blob names; blob `i` is the file `i`. + blobs: Vec<String>, +} + +impl Version { + fn blob(&self, i: usize) -> PathBuf { + self.dir.join(i.to_string()) + } + + fn sizes(&self) -> Vec<(String, u64)> { + let size = |i| std::fs::metadata(self.blob(i)).map_or(0, |m| m.len()); + let blobs = self.blobs.iter().enumerate(); + blobs.map(|(i, n)| (n.clone(), size(i))).collect() + } +} + +/// The manifest: length-prefixed strings (u32 LE): container name, display +/// name, then each blob name. +fn manifest(name: &str, display: &str, blobs: &[&str]) -> Vec<u8> { + let mut out = Vec::new(); + for s in [name, display].into_iter().chain(blobs.iter().copied()) { + out.extend_from_slice(&(s.len() as u32).to_le_bytes()); + out.extend_from_slice(s.as_bytes()); + } + out +} + +fn parse_manifest(bytes: &[u8]) -> Option<Vec<String>> { + let mut out = Vec::new(); + let mut rest = bytes; + while !rest.is_empty() { + let (len, tail) = rest.split_first_chunk::<4>()?; + let len = u32::from_le_bytes(*len) as usize; + out.push(String::from_utf8(tail.get(..len)?.to_vec()).ok()?); + rest = &tail[len..]; + } + (out.len() >= 2).then_some(out) +} + +/// The container's newest committed version, if any. Removes what a crash +/// left: unfinished versions and older ones. +fn current(dir: &Path) -> std::io::Result<Option<Version>> { + let mut committed = Vec::new(); + for entry in std::fs::read_dir(dir)?.flatten() { + let file = entry.file_name(); + let file = file.to_string_lossy(); + if file.ends_with(".new") { + std::fs::remove_dir_all(entry.path())?; + } else if let Some(n) = file.strip_prefix('v').and_then(|n| n.parse::<u64>().ok()) { + committed.push(n); + } + } + committed.sort_unstable(); + let Some(&number) = committed.last() else { + return Ok(None); + }; + for old in &committed[..committed.len() - 1] { + std::fs::remove_dir_all(dir.join(format!("v{old}")))?; + } + let version = dir.join(format!("v{number}")); + let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "bad save manifest"); + let mut names = parse_manifest(&std::fs::read(version.join(MANIFEST))?).ok_or_else(bad)?; + let blobs = names.split_off(2); + let [name, display] = <[String; 2]>::try_from(names).map_err(|_| bad())?; + Ok(Some(Version { + dir: version, + number, + name, + display, + blobs, + })) +} + +/// The version of container `name` in `dir`; none for a missing container +/// or another name that hashes alike. +fn current_named(dir: &Path, name: &str) -> std::io::Result<Option<Version>> { + match current(dir) { + Ok(v) => Ok(v.filter(|v| v.name == name)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// Where a crash test stops the process (test builds only). +fn step() { + #[cfg(test)] + tests::crash_point(); +} + +/// A blob of a new version: new data, or the previous version's file. +enum Source<'a> { + Data(&'a [u8]), + Kept(PathBuf), +} + +/// Writes version `number` of the container in `dir` and commits it. +fn commit( + dir: &Path, + number: u64, + name: &str, + display: &str, + blobs: &[(&str, Source<'_>)], +) -> std::io::Result<()> { + let staged = dir.join(format!("v{number}.new")); + if staged.exists() { + std::fs::remove_dir_all(&staged)?; + } + std::fs::create_dir_all(&staged)?; + let write = |path: PathBuf, data: &[u8]| -> std::io::Result<()> { + let mut file = std::fs::File::create(path)?; + file.write_all(data)?; + file.sync_all() + }; + for (i, (_, source)) in blobs.iter().enumerate() { + let path = staged.join(i.to_string()); + 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))?, + } + step(); + } + let names: Vec<&str> = blobs.iter().map(|(n, _)| *n).collect(); + write(staged.join(MANIFEST), &manifest(name, display, &names))?; + step(); + std::fs::rename(&staged, dir.join(format!("v{number}")))?; + step(); + Ok(()) +} + +/// The containers under a provider's root, by exact name; containers in +/// the old one-file-per-blob layout are converted first. +fn containers(root: &Path) -> Vec<(String, PathBuf)> { + let mut out = Vec::new(); + for entry in std::fs::read_dir(root).into_iter().flatten().flatten() { + let path = entry.path(); + let file = entry.file_name().to_string_lossy().into_owned(); + if !path.is_dir() { + continue; + } + if file.ends_with(".gone") { + let _ = std::fs::remove_dir_all(&path); + } else if file.contains('~') { + if let Ok(Some(v)) = current(&path) { + out.push((v.name, path)); + } + } else if let Some(name) = decode(&file) + && let Some(dir) = migrate(root, &name, &path) + { + out.push((name, dir)); + } + } + out.sort(); + out +} + +/// Moves a container of the old layout (blob files named by encoded name, +/// a `.display` file) into a committed version, then removes it. +fn migrate(root: &Path, name: &str, old: &Path) -> Option<PathBuf> { + let dir = container_dir(root, name); + let done = current_named(&dir, name).ok()?.is_some(); // a crash after the commit + if !done { + let display = std::fs::read_to_string(old.join(".display")).unwrap_or_default(); + let mut blobs: Vec<(String, Vec<u8>)> = std::fs::read_dir(old) + .ok()? + .flatten() + .filter_map(|e| { + let blob = decode(e.file_name().to_str()?)?; + Some((blob, std::fs::read(e.path()).ok()?)) + }) + .collect(); + blobs.sort(); + let sources: Vec<_> = blobs + .iter() + .map(|(n, d)| (n.as_str(), Source::Data(d))) + .collect(); + commit(&dir, 1, name, &display, &sources).ok()?; + } + std::fs::remove_dir_all(old).ok()?; + tracing::info!(container = name, "game save moved to the versioned layout"); + Some(dir) +} + +fn used_bytes(root: &Path) -> u64 { + containers(root) + .iter() + .filter_map(|(name, dir)| current_named(dir, name).ok().flatten()) + .map(|v| v.sizes().iter().map(|(_, size)| size).sum::<u64>()) + .sum() +} + +struct Provider { + root: PathBuf, +} +struct Container { + name: String, + dir: PathBuf, +} +struct Update { + name: String, + dir: PathBuf, + display: Option<String>, + /// Blob writes (`Some`) and deletions (`None`), in order. + changes: Vec<(String, Option<Vec<u8>>)>, +} + +/// A handle we gave out. +fn get<'a, T>(handle: *const T) -> Option<&'a T> { + // SAFETY: handles are boxes we created and the title has not closed. + unsafe { handle.as_ref() } +} +fn give<T>(value: T) -> *mut T { + Box::into_raw(Box::new(value)) +} +fn take<T>(handle: *mut T) { + if !handle.is_null() { + // SAFETY: as in `get`; closing ends the handle. + drop(unsafe { Box::from_raw(handle) }); + } +} + +impl Provider { + /// The provider for the only user and `config` (the service + /// configuration id), under `saves`. An empty id names no + /// configuration, like none: as a folder name it would be the user's + /// folder itself, where the other configurations' folders are. + fn open(saves: &Path, config: Option<&str>) -> Result<Provider, HRESULT> { + let config = config.filter(|c| !c.is_empty()).unwrap_or("default"); + let root = saves + .join(format!("{:016X}", xuser::XUID)) + .join(file_name(config)); + std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?; + let _saves = saves_lock(); + containers(&root); // converts old containers now + Ok(Provider { root }) + } + + fn remaining(&self) -> u64 { + let _saves = saves_lock(); + remaining(&self.root) + } + + fn container(&self, name: &str) -> Container { + Container { + name: name.to_owned(), + dir: container_dir(&self.root, name), + } + } +} + +/// Quota left under a provider's root, or less if the host disk is fuller. +fn remaining(root: &Path) -> u64 { + QUOTA + .saturating_sub(used_bytes(root)) + .min(storage::disk_free(root)) +} + +/// Why an update writing `written` bytes, `replaced` of them over blobs it +/// replaces, does not fit: past the per-user quota (`used` bytes kept), or +/// past the host disk's `free` bytes, which is not the user's quota (the +/// new version is written before the old one goes, so nothing it replaces +/// counts there). +fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option<HRESULT> { + if written > QUOTA.saturating_sub(used) + replaced { + Some(QUOTA_EXCEEDED) + } else if written > free { + Some(OUT_OF_LOCAL_STORAGE) + } else { + None + } +} + +fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT { + tracing::warn!(dir = %dir.display(), %e, "game save"); + if e.kind() == std::io::ErrorKind::StorageFull { + OUT_OF_LOCAL_STORAGE + } else { + NO_ACCESS + } +} + +impl Update { + /// Applies the update as one new version of the container. + fn submit(&self) -> HRESULT { + let _saves = saves_lock(); + let current = match current(&self.dir) { + Ok(v) => v, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return io_error(&self.dir, &e), + }; + if current.as_ref().is_some_and(|v| v.name != self.name) { + // Another container's name hashes alike: never mix the two. + return NO_ACCESS; + } + // The blobs after the update: name → new data or the kept file. + let mut blobs: Vec<(&str, Source<'_>)> = current + .iter() + .flat_map(|v| { + let kept = v.blobs.iter().enumerate(); + kept.map(|(i, n)| (n.as_str(), Source::Kept(v.blob(i)))) + }) + .collect(); + for (name, data) in &self.changes { + blobs.retain(|(n, _)| n != name); + if let Some(data) = data { + blobs.push((name, Source::Data(data))); + } + } + blobs.sort_by(|a, b| a.0.cmp(b.0)); + let written: usize = blobs + .iter() + .map(|(_, s)| match s { + Source::Data(d) => d.len(), + Source::Kept(_) => 0, + }) + .sum(); + if written > MAX_UPDATE { + return UPDATE_TOO_BIG; + } + 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)); + changed.map(|(_, size)| size).sum() + }); + let root = self.dir.parent().unwrap_or(&self.dir); + let free = storage::disk_free(root); + if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) { + return hr; + } + let display = self.display.as_deref(); + let display = display.or(current.as_ref().map(|v| v.display.as_str())); + let number = current.as_ref().map_or(1, |v| v.number + 1); + if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) { + return io_error(&self.dir, &e); + } + // The old version is garbage now; a crash here leaves it for later. + if let Some(old) = ¤t { + let _ = std::fs::remove_dir_all(&old.dir); + step(); + } + S_OK + } +} + +/// Deletes a container: renamed away (one step), then removed. +fn delete(root: &Path, name: &str) -> HRESULT { + let _saves = saves_lock(); + let dir = container_dir(root, name); + match current_named(&dir, name) { + Ok(Some(_)) => {} + Ok(None) => return S_OK, + Err(e) => return io_error(&dir, &e), + } + let gone = dir.with_extension("gone"); + let _ = std::fs::remove_dir_all(&gone); + step(); + if let Err(e) = std::fs::rename(&dir, &gone) { + return io_error(&dir, &e); + } + step(); + let _ = std::fs::remove_dir_all(&gone); + S_OK +} + +/// Reads the named blobs (all of them for `None`) of a container. +fn read(c: &Container, names: Option<Vec<String>>) -> Result<Vec<(String, Vec<u8>)>, HRESULT> { + let _saves = saves_lock(); + let version = current_named(&c.dir, &c.name) + .map_err(|e| io_error(&c.dir, &e))? + .ok_or(BLOB_NOT_FOUND)?; + let names = names.unwrap_or_else(|| version.blobs.clone()); + names + .into_iter() + .map(|name| { + let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?; + let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?; + Ok((name, data)) + }) + .collect() +} + +/// One blob as the public API lays it out: name, size, data. +const BLOB: usize = 24; + +/// Blobs laid out as the title reads them: the blob array, then each name +/// (NUL-terminated) and its data, with pointers `base` plus offset. +fn layout(blobs: &[(String, Vec<u8>)], base: usize) -> Vec<u8> { + let mut out = vec![0u8; blobs.len() * BLOB]; + for (i, (name, data)) in blobs.iter().enumerate() { + let name_at = base + out.len(); + out.extend_from_slice(name.as_bytes()); + out.push(0); + let data_at = base + out.len(); + out.extend_from_slice(data); + let entry = &mut out[i * BLOB..(i + 1) * BLOB]; + entry[..8].copy_from_slice(&name_at.to_le_bytes()); + entry[8..12].copy_from_slice(&(data.len() as u32).to_le_bytes()); + entry[16..].copy_from_slice(&data_at.to_le_bytes()); + } + out +} + +/// The names a title passes (`count` strings, or all blobs if null). +fn names(names: *const *const c_char, count: u32) -> Option<Vec<String>> { + if names.is_null() { + return None; + } + // SAFETY: the title passes `count` strings. + let names = unsafe { std::slice::from_raw_parts(names, count as usize) }; + Some(names.iter().map(|&n| text(n).unwrap_or_default()).collect()) +} + +type This = *const Object; +type ContainerCallback = extern "system" fn(*const ContainerInfo, *mut c_void) -> bool; +type BlobCallback = extern "system" fn(*const BlobInfo, *mut c_void) -> bool; + +#[repr(C)] +pub struct ContainerInfo { + pub name: *const c_char, + pub display_name: *const c_char, + pub blob_count: u32, + pub total_size: u64, + pub last_modified: i64, + pub needs_sync: bool, +} + +#[repr(C)] +pub struct BlobInfo { + pub name: *const c_char, + pub size: u32, +} + +/// Calls `callback` with the information of each container that passes +/// `keep` until it returns false; never under our lock (it may call us). +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) + .into_iter() + .filter(|(name, _)| keep(name)) + .filter_map(|(name, dir)| current_named(&dir, &name).ok().flatten()) + .map(|v| { + let modified = std::fs::metadata(v.dir.join(MANIFEST)) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs() as i64); + let size = v.sizes().iter().map(|(_, s)| s).sum(); + let count = v.blobs.len() as u32; + (cstring(&v.name), cstring(&v.display), count, size, modified) + }) + .collect() + }; + for (name, display, blob_count, total_size, last_modified) in &infos { + let info = ContainerInfo { + name: name.as_ptr(), + display_name: display.as_ptr(), + blob_count: *blob_count, + total_size: *total_size, + last_modified: *last_modified, + needs_sync: false, + }; + if !callback(&info, context) { + break; + } + } +} + +fn cstring(s: &str) -> CString { + CString::new(s.replace('\0', "")).unwrap_or_default() +} + +static INIT: u8 = 0; +static QUOTA_CALL: u8 = 0; +static DELETE: u8 = 0; +static READ: u8 = 0; +static SUBMIT: u8 = 0; + +extern "system" fn initialize_async( + _: This, + _user: *const c_void, + config: *const c_char, + _sync_on_demand: bool, + block: *mut AsyncBlock, +) -> HRESULT { + let saves = runtime::title().saves(); + let result = if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) { + Err(NO_ACCESS) + } else { + Provider::open(&saves, text(config).as_deref()).map(|p| xasync::bytes(give(p))) + }; + xasync::finished_with(block, (&raw const INIT).cast(), result) +} +extern "system" fn initialize_result( + _: This, + block: *mut AsyncBlock, + out: *mut *mut Provider, +) -> HRESULT { + xasync::result(block, (&raw const INIT).cast(), out) +} +extern "system" fn close_provider(_: This, provider: *mut Provider) { + take(provider); +} + +extern "system" fn quota_async( + _: This, + provider: *const Provider, + block: *mut AsyncBlock, +) -> HRESULT { + let result = get(provider) + .ok_or(E_INVALIDARG) + .map(|p| xasync::bytes(p.remaining() as i64)); + xasync::finished_with(block, (&raw const QUOTA_CALL).cast(), result) +} +extern "system" fn quota_result(_: This, block: *mut AsyncBlock, out: *mut i64) -> HRESULT { + xasync::result(block, (&raw const QUOTA_CALL).cast(), out) +} + +extern "system" fn delete_async( + _: This, + provider: *const Provider, + name: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + let hr = match (get(provider), text(name)) { + (Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name), + (Some(_), Some(_)) => INVALID_CONTAINER_NAME, + _ => E_INVALIDARG, + }; + xasync::finished(block, (&raw const DELETE).cast(), hr) +} +extern "system" fn delete_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const DELETE).cast(), 0, none, none.cast()) +} + +/// Reports the container if it exists; a missing one is no error, the +/// callback just does not run. +extern "system" fn container_info( + _: This, + provider: *const Provider, + name: *const c_char, + context: *mut c_void, + callback: Option<ContainerCallback>, +) -> HRESULT { + let (Some(p), Some(name), Some(callback)) = (get(provider), text(name), callback) else { + return E_INVALIDARG; + }; + if !valid_container(&name) { + return INVALID_CONTAINER_NAME; + } + report(&p.root, |n| n == name, context, callback); + S_OK +} + +extern "system" fn enumerate_containers( + _: This, + provider: *const Provider, + context: *mut c_void, + callback: Option<ContainerCallback>, +) -> HRESULT { + let (Some(p), Some(callback)) = (get(provider), callback) else { + return E_INVALIDARG; + }; + report(&p.root, |_| true, context, callback); + S_OK +} + +/// The container exists once an update to it is submitted. +extern "system" fn create_container( + _: This, + provider: *const Provider, + name: *const c_char, + out: *mut *mut Container, +) -> HRESULT { + let (Some(p), Some(name)) = (get(provider), text(name)) else { + return E_INVALIDARG; + }; + if !valid_container(&name) { + return INVALID_CONTAINER_NAME; + } + put(out, give(p.container(&name))) +} +extern "system" fn close_container(_: This, container: *mut Container) { + take(container); +} + +extern "system" fn enumerate_blobs( + _: This, + container: *const Container, + prefix: *const c_char, + context: *mut c_void, + callback: Option<BlobCallback>, +) -> HRESULT { + let (Some(c), Some(callback)) = (get(container), callback) else { + return E_INVALIDARG; + }; + let prefix = text(prefix).unwrap_or_default(); + let blobs = { + let _saves = saves_lock(); + let version = current_named(&c.dir, &c.name).ok().flatten(); + version.map(|v| v.sizes()).unwrap_or_default() + }; + for (name, size) in blobs.into_iter().filter(|(n, _)| n.starts_with(&prefix)) { + let name = cstring(&name); + let info = BlobInfo { + name: name.as_ptr(), + size: size as u32, + }; + if !callback(&info, context) { + break; + } + } + S_OK +} + +extern "system" fn read_blobs( + _: This, + container: *const Container, + blob_names: *const *const c_char, + count: *mut u32, + size: usize, + out: *mut u8, +) -> HRESULT { + let Some(c) = get(container) else { + return E_INVALIDARG; + }; + // SAFETY: the title passes its count. + let wanted = unsafe { count.as_ref() }.copied().unwrap_or(0); + let blobs = match read(c, names(blob_names, wanted)) { + Ok(blobs) => blobs, + Err(hr) => return hr, + }; + let bytes = layout(&blobs, out as usize); + if out.is_null() || size < bytes.len() { + return BUFFER_TOO_SMALL; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { out.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len()) }; + put(count, blobs.len() as u32) +} + +/// Read at once; the result holds the layout with pointers relative to the +/// title's buffer, fixed up when the title takes it. +extern "system" fn read_async( + _: This, + container: *const Container, + blob_names: *const *const c_char, + count: u32, + block: *mut AsyncBlock, +) -> HRESULT { + let result = match get(container) { + Some(c) => read(c, names(blob_names, count)).map(|blobs| layout(&blobs, 0)), + None => Err(E_INVALIDARG), + }; + xasync::finished_with(block, (&raw const READ).cast(), result) +} +extern "system" fn read_result( + _: This, + block: *mut AsyncBlock, + size: usize, + out: *mut u8, + count: *mut u32, +) -> HRESULT { + let mut used = 0; + let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used); + // The documented error for a small buffer; the result stays for a + // retry with a larger one. + if hr == xasync::E_NOT_SUFFICIENT_BUFFER { + return BUFFER_TOO_SMALL; + } + if hr < 0 { + return hr; + } + // The first name follows the blob array, so its offset gives the count. + let blobs = if used == 0 { + 0 + } else { + // SAFETY: the result holds at least one blob entry. + unsafe { out.cast::<usize>().read_unaligned() / BLOB } + }; + for i in 0..blobs { + for field in [0, 16] { + // SAFETY: within the blob array just written. + unsafe { + let p = out.add(i * BLOB + field).cast::<usize>(); + p.write_unaligned(p.read_unaligned() + out as usize); + } + } + } + put(count, blobs as u32) +} + +extern "system" fn create_update( + _: This, + container: *const Container, + display: *const c_char, + out: *mut *mut Update, +) -> HRESULT { + let Some(c) = get(container) else { + return E_INVALIDARG; + }; + put( + out, + give(Update { + name: c.name.clone(), + dir: c.dir.clone(), + display: text(display), + changes: Vec::new(), + }), + ) +} +extern "system" fn close_update(_: This, update: *mut Update) { + take(update); +} + +extern "system" fn write_blob( + _: This, + update: *mut Update, + name: *const c_char, + data: *const u8, + size: usize, +) -> HRESULT { + // SAFETY: a handle we gave out; the title does not use it concurrently. + let (Some(update), Some(name)) = (unsafe { update.as_mut() }, text(name)) else { + return E_INVALIDARG; + }; + if name.is_empty() || (data.is_null() && size > 0) { + return E_INVALIDARG; + } + if size > MAX_UPDATE { + return UPDATE_TOO_BIG; + } + let data = if size == 0 { + Vec::new() + } else { + // SAFETY: the title passes `size` bytes. + unsafe { std::slice::from_raw_parts(data, size) }.to_vec() + }; + update.changes.push((name, Some(data))); + S_OK +} + +extern "system" fn delete_blob(_: This, update: *mut Update, name: *const c_char) -> HRESULT { + // SAFETY: as in `write_blob`. + match (unsafe { update.as_mut() }, text(name)) { + (Some(update), Some(name)) if !name.is_empty() => { + update.changes.push((name, None)); + S_OK + } + _ => E_INVALIDARG, + } +} + +extern "system" fn submit_async(_: This, update: *const Update, block: *mut AsyncBlock) -> HRESULT { + let hr = get(update).map_or(E_INVALIDARG, Update::submit); + xasync::finished(block, (&raw const SUBMIT).cast(), hr) +} +extern "system" fn submit_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const SUBMIT).cast(), 0, none, none.cast()) +} + +static VTABLE: Methods<30> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 initialize (blocking) + initialize_async as *const (), // 0x20 + initialize_result as *const (), // 0x28 + close_provider as *const (), // 0x30 + missing::<7> as *const (), // 0x38 remaining quota (blocking) + quota_async as *const (), // 0x40 + quota_result as *const (), // 0x48 + missing::<10> as *const (), // 0x50 delete (blocking) + delete_async as *const (), // 0x58 + delete_result as *const (), // 0x60 + container_info as *const (), // 0x68 + enumerate_containers as *const (), // 0x70 + missing::<15> as *const (), // 0x78 by name prefix + create_container as *const (), // 0x80 + close_container as *const (), // 0x88 + missing::<18> as *const (), // 0x90 all blob info + enumerate_blobs as *const (), // 0x98 by name prefix + read_blobs as *const (), // 0xa0 + read_async as *const (), // 0xa8 + read_result as *const (), // 0xb0 + create_update as *const (), // 0xb8 + close_update as *const (), // 0xc0 + write_blob as *const (), // 0xc8 + delete_blob as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 submit (blocking) + submit_async as *const (), // 0xe0 + submit_result as *const (), // 0xe8 +]); + +#[cfg(test)] +mod tests { + use std::io::BufRead; + use std::sync::atomic::{AtomicU32, Ordering}; + + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + static STEPS: AtomicU32 = AtomicU32::new(0); + + /// In a child process of the crash test, stops for good at the step + /// `VICTORY_SAVE_STOP` names and says so. + pub(super) fn crash_point() { + let Ok(stop) = std::env::var("VICTORY_SAVE_STOP") else { + return; + }; + if stop.parse() == Ok(STEPS.fetch_add(1, Ordering::SeqCst) + 1) { + println!("STOPPED"); + let _ = std::io::stdout().flush(); + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } + } + + /// The per-user quota and the host disk fail with their own errors. + #[test] + 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)); + // 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); + } + + fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT { + Update { + name: "Slot".into(), + dir: container_dir(root, "Slot"), + display: Some(display.into()), + changes: changes + .iter() + .map(|(n, d)| (n.to_string(), d.map(|d| d.as_bytes().to_vec()))) + .collect(), + } + .submit() + } + + /// The container `Slot`: display name and blobs. + fn state(root: &Path) -> Option<(String, Vec<(String, String)>)> { + let c = Provider { root: root.into() }.container("Slot"); + let display = current_named(&c.dir, "Slot").unwrap()?.display; + let blobs = read(&c, None).unwrap(); + let text = |(n, d): (String, Vec<u8>)| (n, String::from_utf8(d).unwrap()); + Some((display, blobs.into_iter().map(text).collect())) + } + + fn old_state() -> Option<(String, Vec<(String, String)>)> { + 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 { + return; + }; + let root = PathBuf::from(root); + let hr = if op == "update" { + update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))]) + } else { + delete(&root, "Slot") + }; + assert_eq!(hr, S_OK); + println!("FINISHED"); + } + + /// Kills a process in the middle of an update (and of a deletion) at + /// every step: what is left is the whole old container or the whole + /// 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())])); + 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); + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"]) + .args(["--test-threads=1"]) + .env("VICTORY_SAVE_CHILD", root) + .env("VICTORY_SAVE_OP", op) + .env("VICTORY_SAVE_STOP", stop.to_string()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let out = std::io::BufReader::new(child.stdout.take().unwrap()); + let mut finished = false; + for line in out.lines() { + let line = line.unwrap(); + if line.contains("STOPPED") { + break; + } + finished |= line.contains("FINISHED"); + } + let _ = child.kill(); + child.wait().unwrap(); + let left = state(root); + if left == old_state() { + seen.0 += 1; + } else { + assert_eq!(left, after, "{op}, killed at step {stop}"); + seen.1 += 1; + } + if finished { + break; + } + } + assert!(seen.0 > 0 && seen.1 > 1, "{op}: {seen:?}"); + } + } + + #[test] + fn names_are_exact() { + for name in ["Save_1", "slot/2", "a.b c%", "\u{e9}t\u{e9}"] { + let file = file_name(name); + assert!(!file.contains(['.', '/', ' ']), "{file}"); + assert_eq!(decode(&file).as_deref(), Some(name)); + } + assert_eq!(decode("x.new"), None); + 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)] { + 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 long = "n".repeat(300); + 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 { + name: c.name.clone(), + dir: c.dir.clone(), + display: None, + changes: blobs + .iter() + .map(|b| (b.to_string(), Some(format!("{container}:{b}").into_bytes()))) + .collect(), + }; + assert_eq!(u.submit(), S_OK, "{container}"); + } + let _saves = saves_lock(); + let names: Vec<String> = containers(dir.path()).into_iter().map(|c| c.0).collect(); + drop(_saves); + assert_eq!(names, ["SAVE/CON.x", "Save", "save"]); + for container in ["Save", "save", "SAVE/CON.x"] { + let read = read(&p.container(container), None).unwrap(); + let mut expected: Vec<_> = blobs + .iter() + .map(|b| (b.to_string(), format!("{container}:{b}").into_bytes())) + .collect(); + expected.sort(); + assert_eq!(read, expected, "{container}"); + } + } + + #[test] + fn the_old_layout_moves_over() { + let saves = tempfile::tempdir().unwrap(); + 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(); + std::fs::write(old.join("Save%20Game%20Header"), b"header").unwrap(); + std::fs::write(old.join("Save%20Game%20Data.new"), b"half").unwrap(); + std::fs::write(old.join(".display"), b"Chapter 1").unwrap(); + let p = Provider::open(saves.path(), Some("scid")).unwrap(); + assert!(!old.exists()); + let c = p.container("Player"); + let blobs = read(&c, None).unwrap(); + assert_eq!( + blobs, + [ + ("Save Game Data".into(), b"data".to_vec()), + ("Save Game Header".into(), b"header".to_vec()) + ] + ); + let v = current_named(&c.dir, "Player").unwrap().unwrap(); + assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1")); + } + + /// An empty configuration id names none. As a folder name it would be + /// the folder every configuration lives in, whose folders then look + /// like containers of the old layout and are converted away. + #[test] + fn an_empty_configuration_id_is_the_default_one() { + let saves = tempfile::tempdir().unwrap(); + let scid = Provider::open(saves.path(), Some("scid")).unwrap(); + assert_eq!(update(&scid.root, "one", &[("a", Some("kept"))]), S_OK); + let kept = Some(("one".into(), vec![("a".into(), "kept".into())])); + assert_eq!(state(&scid.root), kept); + + let empty = Provider::open(saves.path(), Some("")).unwrap(); + assert!(scid.root.is_dir(), "another configuration's saves are gone"); + assert_eq!(state(&scid.root), kept); + let default = Provider::open(saves.path(), None).unwrap(); + assert_eq!(empty.root, default.root); + + // Named configurations stay apart, from it and from each other. + assert_ne!(empty.root, scid.root); + assert_eq!(state(&empty.root), None); + let other = Provider::open(saves.path(), Some("other")).unwrap(); + assert_eq!(state(&other.root), None); + assert_eq!(state(&scid.root), kept); + } + + #[test] + fn saves_persist_across_providers() { + let this: This = &OBJECT; + let saves = tempfile::tempdir().unwrap(); + let provider = give(Provider::open(saves.path(), Some("scid")).unwrap()); + + // Write two blobs through an update. + let mut container = std::ptr::null_mut(); + type Create = extern "system" fn( + This, + *const Provider, + *const c_char, + *mut *mut Container, + ) -> HRESULT; + let create = method::<Create>(&OBJECT, 0x80); + assert_eq!( + create(this, provider, c"bad name".as_ptr(), &mut container), + INVALID_CONTAINER_NAME + ); + assert_eq!( + create(this, provider, c"Slot_1".as_ptr(), &mut container), + S_OK + ); + let mut update = std::ptr::null_mut(); + type Update_ = + extern "system" fn(This, *const Container, *const c_char, *mut *mut Update) -> HRESULT; + assert_eq!( + method::<Update_>(&OBJECT, 0xb8)(this, container, c"Chapter 1".as_ptr(), &mut update), + S_OK + ); + type Write = + extern "system" fn(This, *mut Update, *const c_char, *const u8, usize) -> HRESULT; + let write = method::<Write>(&OBJECT, 0xc8); + assert_eq!( + write(this, update, c"world".as_ptr(), b"hello".as_ptr(), 5), + S_OK + ); + assert_eq!( + write(this, update, c"player.dat".as_ptr(), b"xy".as_ptr(), 2), + S_OK + ); + assert_eq!( + write(this, update, c"gone".as_ptr(), b"z".as_ptr(), 1), + S_OK + ); + type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT; + assert_eq!(method::<Delete>(&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::<Submit>(&OBJECT, 0xe0)(this, update, &mut b), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + close_update(this, update); + close_container(this, container); + close_provider(this, provider); + + // A new provider sees the container and reads both blobs back. + let provider = give(Provider::open(saves.path(), Some("scid")).unwrap()); + extern "system" fn seen(info: *const ContainerInfo, context: *mut c_void) -> bool { + // SAFETY: valid during the callback; the context is the test's vector. + let (info, out) = unsafe { + ( + &*info, + &mut *context.cast::<Vec<(String, String, u32, u64)>>(), + ) + }; + out.push(( + text(info.name).unwrap(), + text(info.display_name).unwrap(), + info.blob_count, + info.total_size, + )); + true + } + let mut found: Vec<(String, String, u32, u64)> = Vec::new(); + let context = (&raw mut found).cast(); + assert_eq!( + enumerate_containers(this, provider, context, Some(seen)), + S_OK + ); + assert_eq!(found, [("Slot_1".into(), "Chapter 1".into(), 2, 7)]); + + let mut container = std::ptr::null_mut(); + assert_eq!( + create_container(this, provider, c"Slot_1".as_ptr(), &mut container), + S_OK + ); + let mut b = block(); + let wanted = [c"world".as_ptr(), c"player.dat".as_ptr()]; + assert_eq!( + read_async(this, container, wanted.as_ptr(), 2, &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut size = 0; + assert_eq!(xasync::XAsyncGetResultSize(&mut b, &mut size), S_OK); + assert_eq!( + size, + 2 * BLOB + "world\0hello".len() + "player.dat\0xy".len() + ); + let mut buffer = vec![0u64; size.div_ceil(8)]; + let mut count = 0; + assert_eq!( + read_result(this, &mut b, 8, buffer.as_mut_ptr().cast(), &mut count), + BUFFER_TOO_SMALL + ); + assert_eq!( + read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count), + S_OK + ); + assert_eq!(count, 2); + let blob = |i: usize| { + // SAFETY: the layout the call wrote. + unsafe { + let entry = buffer.as_ptr().cast::<u8>().add(i * BLOB); + let name = text(entry.cast::<*const c_char>().read_unaligned()).unwrap(); + let len = entry.add(8).cast::<u32>().read_unaligned() as usize; + let data = std::slice::from_raw_parts( + entry.add(16).cast::<*const u8>().read_unaligned(), + len, + ); + (name, data.to_vec()) + } + }; + assert_eq!(blob(0), ("world".into(), b"hello".to_vec())); + assert_eq!(blob(1), ("player.dat".into(), b"xy".to_vec())); + + let missing = [c"nothing".as_ptr()]; + let mut one = 1; + let mut small = [0u8; 8]; + let read_now = method::< + extern "system" fn( + This, + *const Container, + *const *const c_char, + *mut u32, + usize, + *mut u8, + ) -> HRESULT, + >(&OBJECT, 0xa0); + assert_eq!( + read_now( + this, + container, + missing.as_ptr(), + &mut one, + 8, + small.as_mut_ptr() + ), + BLOB_NOT_FOUND + ); + assert_eq!( + read_now( + this, + container, + wanted.as_ptr(), + &mut 2, + 8, + small.as_mut_ptr() + ), + BUFFER_TOO_SMALL + ); + + // Quota counts the blobs; deleting the container frees it. + let mut b = block(); + assert_eq!(quota_async(this, provider, &mut b), S_OK); + let mut left = 0i64; + assert_eq!(quota_result(this, &mut b, &mut left), S_OK); + assert!(left as u64 <= QUOTA - 7); + let mut b = block(); + assert_eq!( + delete_async(this, provider, c"Slot_1".as_ptr(), &mut b), + S_OK + ); + assert_eq!(delete_result(this, &mut b), S_OK); + found.clear(); + let context = (&raw mut found).cast(); + assert_eq!( + enumerate_containers(this, provider, context, Some(seen)), + S_OK + ); + assert!(found.is_empty()); + close_container(this, container); + close_provider(this, provider); + } +} diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs new file mode 100644 index 000000000..ab2d9e009 --- /dev/null +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -0,0 +1,321 @@ +//! System dialogs a title opens (XGameUi). A profile card has nothing to +//! show and closes at once. Text entry opens a small host dialog (title, +//! description, default text, the length limit) on a thread of its own and +//! completes the call with what the user typed, or as cancelled (`E_ABORT`) +//! when the dialog is dismissed or cannot open. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, E_ABORT}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; + +pub const PROVIDER: Guid = Guid::new( + 0xdfcd_4649, + 0x4ff8, + 0x4043, + [0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0], +); +/// As Grand Theft Auto VI (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, + 0x5542, + 0x4590, + [0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc], +); + +pub static OBJECT: Object = Object::new("game ui", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; + +type This = *const Object; + +static PROFILE: u8 = 0; +static TEXT: u8 = 0; + +extern "system" fn profile_card_async( + _: This, + block: *mut AsyncBlock, + _user: *const c_void, + xuid: u64, +) -> HRESULT { + tracing::info!(xuid, "profile card: nothing to show"); + xasync::finished(block, (&raw const PROFILE).cast(), S_OK) +} +extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast()) +} + +/// Grand Theft Auto VI treats `E_ABORT` as cancelled and goes on; any +/// other failure as an error. +extern "system" fn text_entry_async( + _: This, + block: *mut AsyncBlock, + title: *const c_char, + description: *const c_char, + default: *const c_char, + _scope: u32, + max_length: u32, +) -> HRESULT { + 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) { + Some(typed) => { + tracing::info!(length = typed.chars().count(), "text entry: done"); + let mut bytes = limit(&typed, max_length).into_bytes(); + bytes.push(0); + Ok(bytes) + } + None => { + tracing::info!("text entry: cancelled"); + Err(E_ABORT) + } + } + }) +} +/// Bytes of the result, its NUL included. +extern "system" fn text_entry_size(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT { + let mut size = 0; + let hr = xasync::XAsyncGetResultSize(block, &mut size); + if hr < 0 { + return hr; + } + put(out, size as u32) +} +extern "system" fn text_entry_result( + _: This, + block: *mut AsyncBlock, + size: u32, + buffer: *mut c_char, + used: *mut u32, +) -> HRESULT { + let mut written = 0; + let identity = (&raw const TEXT).cast(); + let hr = xasync::XAsyncGetResult(block, identity, size as usize, buffer.cast(), &mut written); + if hr < 0 || used.is_null() { + return hr; + } + put(used, written as u32) +} + +/// At most `max` characters (0: no limit). +fn limit(typed: &str, max: u32) -> String { + match max { + 0 => typed.to_owned(), + max => typed.chars().take(max as usize).collect(), + } +} + +/// Asks the user in a modal host dialog; `None` if dismissed. +#[cfg(not(test))] +fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> { + dialog::ask(title, description, default, max) +} + +/// Tests answer for the user: "typed" for a title starting with "Type", +/// cancelled otherwise. +#[cfg(test)] +fn ask(title: &str, _: &str, default: &str, _: u32) -> Option<String> { + title.starts_with("Type").then(|| format!("{default}typed")) +} + +mod dialog { + use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus; + use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE}; + + const EDIT: i32 = 100; + // Edit control messages (the controls headers). + const EM_SETSEL: u32 = 0xb1; + const EM_LIMITTEXT: u32 = 0xc5; + + /// The dialog's state, behind its user data while it runs. + struct Entry { + max: u32, + typed: Option<String>, + } + + /// The description, an edit box with the default text, OK and Cancel, + /// from an in-memory template (dialog units, the system font); Enter + /// accepts, Esc cancels. + #[allow(dead_code)] // unused in test builds + pub(super) fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> { + let mut t: Vec<u16> = Vec::new(); + fn dword(t: &mut Vec<u16>, v: u32) { + t.extend([v as u16, (v >> 16) as u16]); + } + fn text(t: &mut Vec<u16>, s: &str) { + t.extend(s.encode_utf16().filter(|&c| c != 0)); + t.push(0); + } + let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU; + let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32; + dword(&mut t, style | flags); + dword(&mut t, wm::WS_EX_TOPMOST); + t.extend([4, 0, 0, 240, 62, 0, 0]); // items, x, y, cx, cy, no menu, default class + text(&mut t, title); + let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| { + if t.len() % 2 == 1 { + t.push(0); // items start on a DWORD + } + dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style); + dword(&mut t, 0); + t.extend(rect); + t.extend([id, 0xffff, class]); + text(&mut t, caption); + t.push(0); // no creation data + }; + let (button, edit, label) = (0x80, 0x81, 0x82); + let tab = wm::WS_TABSTOP; + item(0, [7, 7, 226, 10], 0xffff, label, description); + let edit_style = wm::WS_BORDER | tab | wm::ES_AUTOHSCROLL as u32; + item(edit_style, [7, 20, 226, 12], EDIT as u16, edit, default); + 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"); + // The template must start on a DWORD. + let template: Vec<u32> = t + .chunks(2) + .map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16) + .collect(); + let mut entry = Entry { max, typed: None }; + // SAFETY: a complete template and our dialog procedure; `entry` + // outlives the modal dialog. + unsafe { + wm::DialogBoxIndirectParamW( + GetModuleHandleW(std::ptr::null()), + template.as_ptr().cast::<DLGTEMPLATE>(), + std::ptr::null_mut(), + Some(procedure), + (&raw mut entry) as LPARAM, + ); + } + entry.typed + } + + 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 { + let edit = wm::GetDlgItem(dialog, EDIT); + match message { + wm::WM_INITDIALOG => { + wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam); + let entry = &*(lparam as *const Entry); + wm::SendMessageW(edit, EM_LIMITTEXT, entry.max as WPARAM, 0); + wm::SendMessageW(edit, EM_SETSEL, 0, -1); + SetFocus(edit); + 0 // focus set here + } + wm::WM_COMMAND => { + 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])); + wm::EndDialog(dialog, 1); + } + wm::IDCANCEL => { + wm::EndDialog(dialog, 0); + } + _ => return 0, + } + 1 + } + _ => 0, + } + } + } +} + +static VTABLE: Methods<20> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 message dialog + missing::<4> as *const (), // 0x20 + missing::<5> as *const (), // 0x28 send invite + missing::<6> as *const (), // 0x30 + profile_card_async as *const (), // 0x38 + profile_card_result as *const (), // 0x40 + missing::<9> as *const (), // 0x48 achievements + missing::<10> as *const (), // 0x50 + missing::<11> as *const (), // 0x58 player picker + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 + missing::<14> as *const (), // 0x70 error dialog + missing::<15> as *const (), // 0x78 + missing::<16> as *const (), // 0x80 notification position + text_entry_async as *const (), // 0x88 + text_entry_size as *const (), // 0x90 + text_entry_result as *const (), // 0x98 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn dialogs_end_with_what_was_typed() { + let this: This = &OBJECT; + let mut b = block(); + type Card = extern "system" fn(This, *mut AsyncBlock, *const c_void, u64) -> HRESULT; + type Done = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + assert_eq!( + method::<Card>(&OBJECT, 0x38)(this, &mut b, std::ptr::null(), 1), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(method::<Done>(&OBJECT, 0x40)(this, &mut b), S_OK); + + type Entry = extern "system" fn( + This, + *mut AsyncBlock, + *const c_char, + *const c_char, + *const c_char, + u32, + 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; + let null = std::ptr::null(); + let entry = method::<Entry>(&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!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); + let mut size = 0; + assert_eq!(method::<Size>(&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!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); + assert_eq!(size, 7); + let mut out = [0 as c_char; 7]; + let mut used = 0; + let result = method::<Result_>(&OBJECT, 0x98); + assert_eq!(result(this, &mut b, 7, out.as_mut_ptr(), &mut used), S_OK); + assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7)); + assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}"); + } +} diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs new file mode 100644 index 000000000..a9ea084cb --- /dev/null +++ b/crates/victory-hle/src/modules/xmem.rs @@ -0,0 +1,1324 @@ +//! `xmem.dll`: console memory, served from host memory. The GPU side works +//! from CPU addresses (unified memory), so memory types and bandwidth +//! classes change nothing here; what constrains addresses (alignment, +//! 2 MiB pages, address-bit limits) is honoured. +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::{Layout, alloc, dealloc}; +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE, +}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, + MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3, + MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT, + SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, +}; +use windows_sys::Win32::System::ProcessStatus::{ + K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, + PROCESS_MEMORY_COUNTERS, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; +use windows_sys::core::BOOL; + +use crate::{HleModule, hle_export}; + +const MIB: usize = 1 << 20; + +/// Whether we run under Wine (its ntdll exports `wine_get_version`). +pub(crate) fn on_wine() -> bool { + static WINE: LazyLock<bool> = LazyLock::new(|| { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + // SAFETY: plain lookups in ntdll, always loaded. + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + } + }); + *WINE +} + +/// Standard memory the title has handed to the system. +static TRANSFERRED: AtomicUsize = AtomicUsize::new(0); + +// Console additions to the host's flags. +/// 2 MiB pages; the host reads this bit as large pages, which need a +/// privilege. +const PAGES_2M: u32 = 0x2000_0000; +/// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory. +const PAGES_64K_BIT: u32 = 0x40_0000; +const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT; +/// The host's protection constants and `PAGE_GUARD`. Above them the console +/// adds GPU access bits (0x800-0x40000). Write-combining and uncached are +/// dropped too: our GPU side reads this memory through the CPU. +const HOST_PROTECTION: u32 = 0x1ff; +/// XMem flags of memory both processors reach: all of ours. +const GRAPHICS: u64 = 3; +/// XMem flag bit of 32-bit graphics memory. +const ADDRESS_32BIT: u64 = 4; +/// The host's write watching (not in windows-sys' memory module). +const MEM_WRITE_WATCH: u32 = 0x20_0000; + +/// 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 +/// with no field). Decision 0001. +fn address_range(flags: u64) -> (usize, usize) { + let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) { + (0, 0) => 40, + (0, field) => 47 - field, + _ => return (0, u32::MAX as usize), + }; + (1 << 32, (1 << bits) - 1) +} + +pub extern "system" fn XMemVirtualAlloc( + base: *mut c_void, + size: usize, + kind: u32, + flags: u64, + protect: u32, +) -> *mut c_void { + let (lowest, highest) = address_range(flags); + let mut requirements = MEM_ADDRESS_REQUIREMENTS { + LowestStartingAddress: lowest as *mut c_void, + HighestEndingAddress: highest as *mut c_void, + Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M { + 2 * MIB + } else { + 0 + }, + }; + let mut protect = match protect & HOST_PROTECTION { + 0 => PAGE_NOACCESS, + p => p, + }; + // 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 + // placeholder then. + let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0; + if placeholder { + if kind & MEM_REPLACE_PLACEHOLDER != 0 { + // Part of a placeholder the title split: it stays one. + return base; + } + protect = PAGE_NOACCESS; + } + let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT); + if placeholder { + kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER; + } + let mut parameter = MEM_EXTENDED_PARAMETER::default(); + parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; + parameter.Anonymous2.Pointer = (&raw mut requirements).cast(); + // Address requirements apply to reservations at an address of our choice. + let constrained = base.is_null(); + if constrained { + kind |= MEM_RESERVE; + // The GPU side copies only the pages the title wrote since its last + // copy (`victory_gpu`, decision 0007); placeholders cannot be + // watched (their physical-page views are copied whole). + if kind & MEM_RESERVE_PLACEHOLDER == 0 { + kind |= MEM_WRITE_WATCH; + } + } + // SAFETY: the title's own arguments, cleaned of console bits; the + // parameter points at `requirements`, which outlives the call. + let at = unsafe { + VirtualAlloc2( + GetCurrentProcess(), + base, + size, + kind, + protect, + if constrained { + &mut parameter + } else { + std::ptr::null_mut() + }, + constrained.into(), + ) + }; + if base.is_null() { + tracing::debug!( + size, + kind = format_args!("{kind:#x}"), + flags = format_args!("{flags:#x}"), + at = format_args!("{at:p}"), + "XMemVirtualAlloc" + ); + } + at +} + +/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the +/// same), then the XMem flags and tag. +#[repr(C)] +pub struct BasicInformation { + host: MEMORY_BASIC_INFORMATION, + flags: u64, + tag_code: u32, + tag: [u8; 4], +} + +// 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 +// only caller, wants graphics memory); remember the flags of +// `XMemVirtualAlloc` regions if a title tells CPU-only memory apart. +pub extern "system" fn XMemVirtualQuery( + process: HANDLE, + address: *const c_void, + out: *mut BasicInformation, +) -> BOOL { + let size = size_of::<MEMORY_BASIC_INFORMATION>(); + // SAFETY: the title passes room for the whole structure; the host + // fails on a null one. + unsafe { + if VirtualQueryEx(process, address, out.cast(), size) == 0 { + return 0; + } + let info = &mut *out; + info.flags = if info.host.State == MEM_COMMIT { + GRAPHICS + } else { + 0 + }; + info.tag_code = 0; + info.tag = [0; 4]; + } + 1 +} + +// `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up +// from 2), then the memory type, then bit 33: a 32-bit address. +const ALIGNMENT_SHIFT: u64 = 24; +const ALLOC_32BIT: u64 = 1 << 33; +/// Our block header: the block's size and alignment, just below the +/// pointer handed out. +const HEADER: usize = 2 * size_of::<usize>(); + +fn layout(size: usize, attributes: u64) -> Option<Layout> { + // An alignment of at least 16 leaves room for the header. + let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4); + Layout::from_size_align(size.checked_add(align)?, align).ok() +} + +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 +/// `XMemFree` call them, for the title's own calls and its middleware's; +/// the `…Default` exports do not. +fn hooks() -> [usize; 2] { + static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + let at = match AT.get() { + Some(&at) => at, + // Looked up once the title is mapped, which is before it runs. + None => match crate::runtime::main_image() { + Some(base) => *AT.get_or_init(|| { + use windows_sys::Win32::System::LibraryLoader::GetProcAddress; + // SAFETY: a mapped image and a NUL-terminated name. + let at = unsafe { + GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast()) + } + .map_or(0, |f| f as usize); + tracing::info!(found = at != 0, "xmem allocation hooks"); + at + }), + None => 0, + }, + }; + if at == 0 { + return [0; 2]; + } + // SAFETY: the export is two routine pointers. + unsafe { (at as *const [usize; 2]).read() } +} + +/// The title's general allocator, for middleware too: its hook if it has +/// one, else [`XMemAllocDefault`]. +pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void { + match hooks()[0] { + 0 => XMemAllocDefault(size, attributes), + hook => { + // SAFETY: the title's own routine of this type. + let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) }; + alloc(size, attributes) + } + } +} + +/// See [`XMemAlloc`]. +pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { + match hooks()[1] { + 0 => XMemFreeDefault(address, attributes), + hook => { + // SAFETY: the title's own routine of this type. + let free: FreeRoutine = unsafe { std::mem::transmute(hook) }; + free(address, attributes) + } + } +} + +/// The system allocator behind [`XMemAlloc`]. +pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void { + if attributes & ALLOC_32BIT != 0 { + return XMemVirtualAlloc( + std::ptr::null_mut(), + size, + MEM_RESERVE | MEM_COMMIT, + GRAPHICS | ADDRESS_32BIT, + PAGE_READWRITE, + ); + } + let Some(layout) = layout(size, attributes) else { + return std::ptr::null_mut(); + }; + // 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 + // reservation below 2^40 if one does. + // SAFETY: the layout has a non-zero size. + let block = unsafe { alloc(layout) }; + if block.is_null() { + return block.cast(); + } + // SAFETY: the block holds the alignment (at least the header) and then + // `size` bytes. + unsafe { + let user = block.add(layout.align()); + user.sub(HEADER) + .cast::<[usize; 2]>() + .write([layout.size(), layout.align()]); + user.cast() + } +} + +/// Frees what [`XMemAllocDefault`] returned, given the same attributes. +pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { + if address.is_null() { + return; + } + // SAFETY: the address came from `XMemAlloc` with these attributes: a + // whole reservation, or a header-prefixed block. + unsafe { + if attributes & ALLOC_32BIT != 0 { + VirtualFree(address, 0, MEM_RELEASE); + return; + } + let user = address.cast::<u8>(); + let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read(); + dealloc( + user.sub(align), + Layout::from_size_align_unchecked(size, align), + ); + } +} + +/// A retail console has no tools memory. +pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { + 0 +} + +// Physical pages: on the console, 64 KiB frames a title maps into its own +// reservations, at more than one address if it likes. Here each allocation +// is a pagefile-backed section, its pages are 64 KiB slices of it, and a +// mapping is a view of consecutive slices in place of a host placeholder. + +const PAGE: usize = 64 << 10; + +struct Section(HANDLE); + +// SAFETY: a section handle may be used from any thread. +unsafe impl Send for Section {} +// SAFETY: as above. +unsafe impl Sync for Section {} + +impl Drop for Section { + fn drop(&mut self) { + // SAFETY: our handle; views keep the section alive on their own. + unsafe { CloseHandle(self.0) }; + } +} + +/// Where a page lives, or what a view starts with: a section and a page +/// index in it. +#[derive(Clone)] +struct Slice { + section: Arc<Section>, + index: usize, +} + +#[derive(Default)] +struct Physical { + next_page: usize, + pages: HashMap<usize, Slice>, + /// Mapped views by address: their length and what they show. + views: BTreeMap<usize, (usize, Slice)>, +} + +static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| { + Mutex::new(Physical { + // Page numbers are opaque to titles; 0 stays unused. + next_page: 0x10_0000, + ..Default::default() + }) +}); + +fn physical() -> MutexGuard<'static, Physical> { + PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// `count` is in and out (pages wanted, pages given); all or nothing here. +pub extern "system" fn XMemAllocatePhysicalPages( + flags: u64, + count: *mut usize, + pages: *mut usize, +) -> BOOL { + if count.is_null() || pages.is_null() { + return 0; + } + // SAFETY: checked non-null. + let n = unsafe { *count }; + let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else { + return 0; + }; + // A pagefile-backed section of `size` bytes, its pages committed when + // first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1 + // GiB at once, which a busy host often cannot commit (error 1450). + // SAFETY: plain section creation. + let handle = unsafe { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + // Under Wine a committed section is a sparse file, free until + // touched, and committing a reserved one page by page costs a + // wineserver request each that scans every range committed so + // far: commit it whole there. + PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }, + (size as u64 >> 32) as u32, + size as u32, + std::ptr::null(), + ) + }; + if handle.is_null() { + let error = std::io::Error::last_os_error(); + tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed"); + // SAFETY: checked non-null. + unsafe { count.write(0) }; + return 0; + } + tracing::debug!( + n, + flags = format_args!("{flags:#x}"), + "XMemAllocatePhysicalPages" + ); + // For the GPU side's in-place census: only a committed section can be + // opened as a host heap. + victory_gpu::title_memory_section(handle as usize, size as u64, on_wine()); + let section = Arc::new(Section(handle)); + let mut physical = physical(); + let first = physical.next_page; + physical.next_page += n * FRAMES; + for index in 0..n { + let slice = Slice { + section: section.clone(), + index, + }; + let number = first + index * FRAMES; + physical.pages.insert(number, slice); + // SAFETY: the title passes room for `n` page numbers. + unsafe { pages.add(index).write(number) }; + } + 1 +} + +/// 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 +/// them with `<< 4` (128 GiB of pages at most). +const FRAMES: usize = PAGE >> 12; + +/// Pages still mapped stay readable through their views until unmapped. +pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL { + if pages.is_null() { + return 0; + } + let mut physical = physical(); + for i in 0..n { + // SAFETY: the title passes `n` page numbers. + physical.pages.remove(&unsafe { *pages.add(i) }); + } + 1 +} + +/// A view of our own on consecutive slices of one section, committed and +/// writable, unmapped when dropped. +struct View { + at: MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, +} + +impl View { + /// Maps `n` slices from `slice` on. + fn map(slice: &Slice, n: usize) -> Option<View> { + use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile}; + let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE); + // SAFETY: slices of a section we own; the view is ours until dropped. + let at = unsafe { + MapViewOfFile( + slice.section.0, + FILE_MAP_WRITE, + (offset >> 32) as u32, + offset as u32, + len, + ) + }; + if at.Value.is_null() { + return None; + } + let view = View { at, len }; + commit(at.Value as usize, len).then_some(view) + } + + fn bytes(&mut self) -> &mut [u8] { + // SAFETY: the view holds `len` committed read-write bytes, ours + // alone while `self` lives (other views of the slices only alias + // them, as the console's do). + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for View { + fn drop(&mut self) { + use windows_sys::Win32::System::Memory::UnmapViewOfFile; + // SAFETY: our view. + unsafe { UnmapViewOfFile(self.at) }; + } +} + +/// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB +/// each), as runs of consecutive slices of one section: each run's first +/// slice and its length in pages. One look at the page table, which the +/// title's own mapping calls share with every DirectStorage worker. `None` +/// if a page is unknown or `pages` ends early. +fn runs(pages: &[usize], offset: usize, len: usize) -> Option<Vec<(Slice, usize)>> { + let end = offset.checked_add(len)?; + let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?; + let physical = physical(); + let mut runs: Vec<(Slice, usize)> = Vec::new(); + for page in pages { + let slice = physical.pages.get(page)?; + match runs.last_mut() { + Some((first, n)) + if Arc::ptr_eq(&first.section, &slice.section) + && slice.index == first.index + *n => + { + *n += 1; + } + _ => runs.push((slice.clone(), 1)), + } + } + Some(runs) +} + +/// 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 +/// costs a map, a commit and an unmap (which flushes every core's TLB). +/// False if a page is unknown or the host fails. +pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool { + let Some(runs) = runs(pages, offset, data.len()) else { + return false; + }; + let (mut within, mut done) = (offset % PAGE, 0); + for (slice, n) in &runs { + let Some(mut view) = View::map(slice, *n) else { + return false; + }; + let k = (n * PAGE - within).min(data.len() - done); + view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); + (within, done) = (0, done + k); + } + true +} + +/// Bytes `[offset, offset + len)` of physical pages, writable in place +/// until dropped: DirectStorage decodes into it instead of a buffer it +/// would then copy. +pub(crate) struct PageWindow { + view: View, + within: usize, + len: usize, +} + +impl PageWindow { + pub(crate) fn bytes(&mut self) -> &mut [u8] { + let (within, len) = (self.within, self.len); + &mut self.view.bytes()[within..within + len] + } +} + +/// A window on bytes `[offset, offset + len)` of `pages` when they are +/// consecutive pages of one allocation (how titles usually hand them out); +/// `None` otherwise (pages of several allocations, out of order, or +/// unknown, or a host failure), which `write_physical` then handles or +/// reports. +pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option<PageWindow> { + let runs = runs(pages, offset, len)?; + let [(slice, n)] = runs.as_slice() else { + return None; + }; + Some(PageWindow { + view: View::map(slice, *n)?, + within: offset % PAGE, + len, + }) +} + +/// Maps `n` pages at `address`, in place of what is mapped there; null +/// `pages` unmaps. Returns `address`, or null if a page or the host fails. +pub extern "system" fn XMemMapPhysicalPages( + address: *mut c_void, + n: usize, + pages: *const usize, +) -> *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; + } + // SAFETY: the title passes `n` page numbers. + let pages = unsafe { std::slice::from_raw_parts(pages, n) }; + let mut i = 0; + while i < n { + let Some(first) = physical.pages.get(&pages[i]).cloned() else { + tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page"); + return std::ptr::null_mut(); + }; + // One view per run of consecutive slices of one section. + let run = 1 + pages[i + 1..] + .iter() + .zip(1..) + .take_while(|&(page, k)| { + physical.pages.get(page).is_some_and(|s| { + Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k + }) + }) + .count(); + if !map(&mut physical, base + i * PAGE, run * PAGE, first) { + return std::ptr::null_mut(); + } + i += run; + } + address +} + +/// One page at each address; null `pages`, or a page number 0, unmaps +/// (Grand Theft Auto VI passes 0 for addresses to clear). +pub extern "system" fn XMemMapPhysicalPagesScatter( + addresses: *const *mut c_void, + n: usize, + pages: *const usize, +) -> BOOL { + if addresses.is_null() { + return 0; + } + for i in 0..n { + // SAFETY: the title passes `n` addresses and, unless null, `n` pages. + let (address, page) = unsafe { + ( + *addresses.add(i), + if pages.is_null() || *pages.add(i) == 0 { + std::ptr::null() + } else { + pages.add(i) + }, + ) + }; + if XMemMapPhysicalPages(address, 1, page).is_null() { + return 0; + } + } + 1 +} + +/// 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. 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); + 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; + }; + if !map(&mut physical, to + k, PAGE, slice) { + return false; + } + } + true +} + +/// 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 { + // 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. + let view = unsafe { + VirtualFree( + base as *mut c_void, + len, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + slice.section.0, + GetCurrentProcess(), + base as *const c_void, + (slice.index * PAGE) as u64, + len, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + if view.Value as usize != base { + tracing::warn!( + address = format_args!("{base:#x}"), + len, + error = %std::io::Error::last_os_error(), + "mapping physical pages failed (not a placeholder?)" + ); + return false; + } + if !commit(base, len) { + // SAFETY: the view just mapped, back to a placeholder. + unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; + return false; + } + // New contents, read-write: the GPU side's copies no longer guard it. + victory_gpu::title_memory_remapped(base, len); + // What the range shows now, for the GPU side's in-place census. + victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); + physical.views.insert(base, (len, slice)); + true +} + +/// Commits the section pages a view shows (once per page, whichever view). +fn commit(base: usize, len: usize) -> bool { + if on_wine() { + return true; // sections are committed whole there + } + // SAFETY: `[base, base + len)` is a view of a reserved section. + if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() { + return true; + } + let error = std::io::Error::last_os_error(); + if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) { + let mut info = PERFORMANCE_INFORMATION { + cb: size_of::<PERFORMANCE_INFORMATION>() as u32, + ..Default::default() + }; + // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION. + let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; + victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info))); + } else { + tracing::warn!(len, %error, "committing physical pages failed"); + } + false +} + +fn commit_limit_message( + len: usize, + error: &std::io::Error, + info: Option<&PERFORMANCE_INFORMATION>, +) -> String { + let mut message = format!( + "VIctory: Windows commit limit reached while committing {len} bytes of physical pages: {error}.\n" + ); + if let Some(info) = info { + use std::fmt::Write; + + let committed = info.CommitTotal * info.PageSize / MIB; + let limit = info.CommitLimit * info.PageSize / MIB; + let _ = writeln!( + message, + "System commit: {committed} MiB of {limit} MiB in use." + ); + } + message.push_str( + "Close other applications or increase the Windows paging file size, then retry.\n", + ); + message +} + +/// Returns `[base, base + len)` to placeholders; views reaching past it +/// are mapped again outside it. +fn unmap(physical: &mut Physical, base: usize, len: usize) { + // No bytes: no view to return. The search below would still find the + // view holding `base` and cut it in two there, and its range of views + // starting inside would run backwards (which `BTreeMap` panics on). + if len == 0 { + return; + } + let end = base + len; + // 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) + .next_back() + .filter(|(at, (size, _))| *at + size > base) + .map(|(at, _)| *at); + let hit: Vec<usize> = first + .into_iter() + .chain(physical.views.range(base + 1..end).map(|(at, _)| *at)) + .collect(); + for at in hit { + let Some((size, slice)) = physical.views.remove(&at) else { + continue; + }; + victory_gpu::title_memory_remapped(at, size); + // SAFETY: a view we mapped; it becomes a placeholder again. + unsafe { + UnmapViewOfFile2( + GetCurrentProcess(), + MEMORY_MAPPED_VIEW_ADDRESS { + Value: at as *mut c_void, + }, + MEM_PRESERVE_PLACEHOLDER, + ) + }; + if at < base { + map(physical, at, base - at, slice.clone()); + } + if at + size > end { + let index = slice.index + (end - at) / PAGE; + map(physical, end, at + size - end, Slice { index, ..slice }); + } + } +} + +/// The oldest layout we know; newer titles pass other flag values (Minecraft +/// 0x20000001) and read the same leading fields. +#[repr(C)] +#[derive(Debug, Default)] +pub struct WorkingSet { + pub title_limit: usize, + pub title_used: usize, + pub tools_limit: usize, + pub tools_used: usize, + pub stack_used: u32, + pub physical_pages: u32, + pub gpu_optimal_limit: usize, + pub gpu_optimal_used: usize, + pub tools_gpu_optimal_limit: usize, + pub tools_gpu_optimal_used: usize, + pub kernel_pool_used: u32, + pub kernel_pool_limit: u32, +} + +/// The title's budget and our process's commit as what it uses. No tools +/// memory: a retail console. +// shortcut: all fields are filled whatever the flags ask for, and use is +// not split by bandwidth class (GPU-optimal use reads 0); track +// allocations per class if a title budgets from that field. +pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL { + if out.is_null() { + return 0; + } + let mut counters = PROCESS_MEMORY_COUNTERS { + cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) }; + let (gpu_optimal, standard) = victory_gpu::console::current().title_memory(); + let stats = WorkingSet { + title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed), + title_used: counters.PagefileUsage, + 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 +} + +/// Hands title memory (standard, in 2 MiB pages) to the system. The other +/// transfers involve tools memory, which a retail console has none of. +pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { + const TITLE_TO_SYSTEM: u32 = 0; + tracing::info!(kind, size, "XMemTransferMemory"); + if size == 0 { + return 1; + } + let Some(size) = size.checked_next_multiple_of(2 * MIB) else { + return 0; + }; + let standard = victory_gpu::console::current().title_memory().1; + let moved = kind == TITLE_TO_SYSTEM + && TRANSFERRED + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| { + t.checked_add(size).filter(|&t| t <= standard) + }) + .is_ok(); + moved.into() +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xmem", + dlls: &["xmem.dll"], + exports: vec![ + hle_export!(XMemAlloc), + hle_export!(XMemFree), + hle_export!(XMemAllocDefault), + hle_export!(XMemFreeDefault), + hle_export!(XMemIsToolsMemAvailable), + hle_export!(XMemAllocatePhysicalPages), + hle_export!(XMemFreePhysicalPages), + hle_export!(XMemMapPhysicalPages), + hle_export!(XMemMapPhysicalPagesScatter), + hle_export!(XMemVirtualAlloc), + hle_export!(XMemVirtualQuery), + hle_export!(XMemGetWorkingSetStatistics), + hle_export!(XMemTransferMemory), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn query(address: *const c_void) -> BasicInformation { + // SAFETY: plain data; zero is a valid value. + let mut info: BasicInformation = unsafe { std::mem::zeroed() }; + // SAFETY: a pseudo handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + assert_eq!(XMemVirtualQuery(process, address, &mut info), 1); + info + } + + #[test] + fn alloc_honours_alignment_and_frees() { + for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] { + let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type + let p = XMemAlloc(100, attributes); + assert!(!p.is_null()); + assert_eq!(p as usize % align, 0, "field {field:#x}"); + // SAFETY: 100 bytes were allocated. + unsafe { p.cast::<u8>().write_bytes(0xab, 100) }; + XMemFree(p, attributes); + } + let p = XMemAlloc(4096, ALLOC_32BIT); + assert!(!p.is_null() && (p as usize) < 1 << 32); + XMemFree(p, ALLOC_32BIT); + } + + #[test] + fn virtual_alloc_meets_console_constraints() { + const GPU_READ_WRITE: u32 = 0x2000; + let p = XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * MIB, + PAGES_2M | MEM_RESERVE | MEM_COMMIT, + GRAPHICS | 7 << 12, // 40-bit addresses + PAGE_READWRITE | GPU_READ_WRITE, + ); + assert!(!p.is_null()); + assert_eq!(p as usize % (2 * MIB), 0); + assert!((p as usize) < 1 << 40); + let info = query(p); + assert_eq!(info.host.State, MEM_COMMIT); + assert_eq!(info.host.Protect, PAGE_READWRITE); + assert_eq!(info.flags & GRAPHICS, GRAPHICS); + // Write-watched, for the GPU side's copies. + let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0); + // SAFETY: room for `count` addresses. + let watched = unsafe { + windows_sys::Win32::System::Memory::GetWriteWatch( + 0, + p, + 4 * MIB, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + }; + assert_eq!(watched, 0); + // SAFETY: our own reservation. + assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); + assert_eq!(query(p).flags, 0); + // No address field: above the 32-bit range and below 2^40, where + // the console keeps it. + let p = XMemVirtualAlloc( + std::ptr::null_mut(), + 16 << 30, + MEM_RESERVE, + GRAPHICS, + PAGE_NOACCESS, + ); + assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}"); + assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}"); + // SAFETY: our own reservation. + assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); + } + + #[test] + fn transfers_shrink_the_title_budget() { + let mut before = WorkingSet::default(); + assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1); + assert!(before.title_used > 0); + assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1); + assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory"); + let standard = victory_gpu::console::current().title_memory().1; + assert_eq!(XMemTransferMemory(0, standard), 0, "over budget"); + let mut after = WorkingSet::default(); + XMemGetWorkingSetStatistics(0x2000_0001, &mut after); + assert_eq!(before.title_limit - after.title_limit, 128 * MIB); + } + + #[test] + fn statistics_have_the_console_layout() { + assert_eq!(size_of::<WorkingSet>(), 0x50); + assert_eq!(size_of::<BasicInformation>(), 0x40); + assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28); + } + + #[test] + fn commit_limit_report_includes_request_and_system_commit() { + let error = std::io::Error::from_raw_os_error(ERROR_COMMITMENT_LIMIT as i32); + let info = PERFORMANCE_INFORMATION { + CommitTotal: 512, + CommitLimit: 768, + PageSize: 4096, + ..Default::default() + }; + let report = commit_limit_message(4 * MIB, &error, Some(&info)); + assert!(report.contains("4194304 bytes")); + assert!(report.contains("2 MiB of 3 MiB in use")); + let fallback = commit_limit_message(4 * MIB, &error, None); + for report in [&report, &fallback] { + assert!(report.contains("os error 1455")); + assert!(report.contains("Windows paging file size")); + } + assert!(!fallback.contains("System commit:")); + } + + #[test] + fn physical_pages_map_alias_and_unmap() { + let mut pages = [0usize; 3]; + let mut n = 3; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + assert_eq!(n, 3); + // Packed into 21 bits as `number >> 4`, as the title keeps them. + for p in pages { + assert_eq!((p >> 4 & 0x1f_ffff) << 4, p); + } + // Reservations of 64 KiB pages, as titles make them for mapping. + let reserve = || { + XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ) + }; + let (a, b) = (reserve(), reserve()); + assert!(!a.is_null() && !b.is_null()); + let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + + // The same page at a second address shows the same bytes. + assert_eq!( + XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()), + at(b, 1) + ); + // SAFETY: both pages are mapped read-write. + unsafe { + at(a, 2).cast::<u8>().write(7); + assert_eq!(at(b, 1).cast::<u8>().read(), 7); + a.cast::<u8>().write(1); + } + // Writes into pages (DirectStorage's) show through their views. + assert!(write_physical(&pages[2..], 1, &[9])); + // SAFETY: mapped read-write. + assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9); + + // Unmapping the middle page keeps its neighbours. + assert_eq!( + XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()), + at(a, 1) + ); + assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT); + // SAFETY: still mapped. + assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7); + + // A scattered page lands in the hole. + let addresses = [at(a, 1)]; + assert_eq!( + XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()), + 1 + ); + // SAFETY: page 0 is now mapped at both `a` and `a + PAGE`. + assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1); + // Page number 0 unmaps. + assert_eq!( + XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()), + 1 + ); + assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE); + // The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`. + assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64)); + // SAFETY: mapped read-write. + assert_eq!(unsafe { b.cast::<u8>().read() }, 7); + assert!(map_alias(b as u64, 0, PAGE as u64)); + assert_eq!(query(b).host.State, MEM_RESERVE); + assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64)); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + 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 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, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + // SAFETY: mapped read-write. + unsafe { a.cast::<u8>().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); + } + 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] + fn mapping_no_pages_changes_nothing() { + let pages = allocate(2); + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a); + // SAFETY: both pages are mapped read-write. + unsafe { a.cast::<u8>().write(5) }; + let second = a.wrapping_byte_add(PAGE); + + // A count of 0 at the start of a view, inside it and past it: with + // pages, without (an unmap), and as the GPU's page-mapping copy. + for at in [a, second, a.wrapping_byte_add(2 * PAGE)] { + assert_eq!(XMemMapPhysicalPages(at, 0, pages.as_ptr()), at); + assert_eq!(XMemMapPhysicalPages(at, 0, std::ptr::null()), at); + assert!(map_alias(at as u64, a as u64, 0)); + assert!(map_alias(at as u64, 0, 0)); + } + + // The view is still the one view it was. + let view = physical().views.get(&(a as usize)).map(|v| v.0); + assert_eq!(view, Some(2 * PAGE)); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(query(second).host.State, MEM_COMMIT); + // SAFETY: still mapped. + assert_eq!(unsafe { a.cast::<u8>().read() }, 5); + + // A count of 1 still unmaps that page alone. + assert_eq!(XMemMapPhysicalPages(second, 1, std::ptr::null()), second); + assert_eq!(query(second).host.State, MEM_RESERVE); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1); + } + + /// `n` pages of one new allocation. + fn allocate(n: usize) -> Vec<usize> { + let (mut pages, mut given) = (vec![0; n], n); + assert_eq!( + XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + assert_eq!(given, n); + pages + } + + /// The bytes of one page, through a view of our own. + fn page_bytes(page: usize) -> Vec<u8> { + let slice = physical().pages.get(&page).cloned().expect("known page"); + View::map(&slice, 1).expect("mapped").bytes().to_vec() + } + + #[test] + fn runs_group_consecutive_pages_of_one_allocation() { + let (a, b) = (allocate(3), allocate(1)); + let lengths = |pages: &[usize], offset, len| { + runs(pages, offset, len).map(|r| r.iter().map(|&(_, n)| n).collect::<Vec<_>>()) + }; + assert_eq!(lengths(&a, 0, 3 * PAGE), Some(vec![3])); + // Only the pages the bytes reach. + assert_eq!(lengths(&a, PAGE + 5, 10), Some(vec![1])); + assert_eq!(lengths(&a, PAGE - 1, 2), Some(vec![2])); + assert_eq!(lengths(&a, 0, 0), Some(vec![])); + // Out of order, or across allocations: one run each. + assert_eq!( + lengths(&[a[0], a[2], a[1]], 0, 3 * PAGE), + Some(vec![1, 1, 1]) + ); + assert_eq!(lengths(&[a[1], a[2], b[0]], 0, 3 * PAGE), Some(vec![2, 1])); + // A slice that follows on in another section starts a run. + assert_eq!(lengths(&[b[0], a[1]], 0, 2 * PAGE), Some(vec![1, 1])); + // Too few pages for the bytes, or an unknown one. + assert_eq!(lengths(&a, 0, 3 * PAGE + 1), None); + assert_eq!(lengths(&[a[0], 0x10], 0, 2 * PAGE), None); + assert_eq!(lengths(&a, usize::MAX, 2), None); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn writes_cross_runs_and_allocations() { + let (a, b) = (allocate(2), allocate(1)); + let pages = [a[0], a[1], b[0]]; + let data: Vec<u8> = (0..2 * PAGE + 64).map(|i| (i * 7 % 251) as u8).collect(); + let offset = PAGE - 32; + // Past the third page: the second run is too short. + assert!(!write_physical(&pages, offset, &data)); + assert!(write_physical(&pages, offset, &data[..2 * PAGE])); + let seen: Vec<u8> = pages.iter().flat_map(|&p| page_bytes(p)).collect(); + assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset"); + assert_eq!(seen[offset..offset + 2 * PAGE], data[..2 * PAGE]); + assert!(seen[offset + 2 * PAGE..].iter().all(|&b| b == 0), "after"); + assert!( + !write_physical(&[a[0], 0x10], 0, &data[..PAGE + 1]), + "unknown page" + ); + assert_eq!(XMemFreePhysicalPages(2, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn page_windows_cover_one_run_in_place() { + let (a, b) = (allocate(3), allocate(1)); + let mut window = page_window(&a, PAGE + 3, PAGE).expect("one run"); + assert_eq!(window.bytes().len(), PAGE); + window.bytes().fill(0x5a); + drop(window); + let (second, third) = (page_bytes(a[1]), page_bytes(a[2])); + assert!(second[..3].iter().all(|&b| b == 0)); + assert!(second[3..].iter().all(|&b| b == 0x5a)); + assert!(third[..3].iter().all(|&b| b == 0x5a)); + assert!(third[3..].iter().all(|&b| b == 0)); + // Several runs, or an unknown page: no window. + assert!(page_window(&[a[0], b[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[a[1], a[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[0x10], 0, 1).is_none()); + // One page of several is still one run. + assert!(page_window(&[a[0], b[0]], 0, PAGE).is_some()); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } +} diff --git a/crates/victory-hle/src/modules/xnetworking.rs b/crates/victory-hle/src/modules/xnetworking.rs new file mode 100644 index 000000000..8670ff292 --- /dev/null +++ b/crates/victory-hle/src/modules/xnetworking.rs @@ -0,0 +1,210 @@ +//! XNetworking as an offline console answers it: the network stack is up +//! (titles wait for that before anything else) but reaches nothing, the +//! connectivity hint never changes, and the title's security allow list, +//! which comes from the service, cannot be fetched. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put, text, token, +}; + +pub const PROVIDER: Guid = Guid::new( + 0x37e5_6907, + 0x2f10, + 0x41e8, + [0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a], +); + +/// As Grand Theft Auto VI (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, + 0x39af, + 0x4658, + [0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3], +); + +pub static OBJECT: Object = Object::new("networking", &VTABLE); +pub const INTERFACES: &[Interface] = + &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +/// `HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)`: what needs the service. +pub const UNREACHABLE: HRESULT = 0x8007_04CF_u32 as i32; + +/// The documented default for the preferred local UDP multiplayer port. +const UDP_PORT: u16 = 3074; + +/// The connectivity hint: level, cost, interface type, then four flags. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ConnectivityHint { + pub level: u32, + pub cost: u32, + pub interface_type: u32, + pub initialized: bool, + pub approaching_data_limit: bool, + pub over_data_limit: bool, + pub roaming: bool, +} + +/// Initialized, no connectivity (level 1), cost unknown (0). +const OFFLINE: ConnectivityHint = ConnectivityHint { + level: 1, + cost: 0, + interface_type: 0, + initialized: true, + approaching_data_limit: false, + over_data_limit: false, + roaming: false, +}; + +type This = *const Object; + +extern "system" fn udp_port(_: This, out: *mut u16) -> HRESULT { + put(out, UDP_PORT) +} + +/// Tells our port queries apart from other calls on the same block. +static PORT: u8 = 0; + +extern "system" fn udp_port_async(_: This, block: *mut AsyncBlock) -> HRESULT { + xasync::finished_with(block, (&raw const PORT).cast(), Ok(xasync::bytes(UDP_PORT))) +} +extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u16) -> HRESULT { + xasync::result(block, (&raw const PORT).cast(), out) +} + +static SECURITY: u8 = 0; + +/// The allow list comes from the service: unreachable offline. +extern "system" fn security_info_async( + _: This, + url: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::debug!( + url = text(url).unwrap_or_default(), + "security information: offline" + ); + xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE) +} +extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + xasync::XAsyncGetResultSize(block, out) +} +extern "system" fn security_info_result( + _: This, + block: *mut AsyncBlock, + size: usize, + used: *mut usize, + buffer: *mut u8, + _info: *mut *const c_void, +) -> HRESULT { + xasync::XAsyncGetResult( + block, + (&raw const SECURITY).cast(), + size, + buffer.cast(), + used, + ) +} + +/// No security information can exist offline, so no certificate passes. +extern "system" fn verify_certificate( + _: This, + _request: *mut c_void, + _info: *const c_void, +) -> HRESULT { + UNREACHABLE +} + +extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRESULT { + put(out, OFFLINE) +} + +/// The hint never changes offline, so the callback never runs. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +static VTABLE: Methods<18> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + udp_port as *const (), // 0x18 + udp_port_async as *const (), // 0x20 + udp_port_result as *const (), // 0x28 + missing::<6> as *const (), // 0x30 port changed + missing::<7> as *const (), // 0x38 + security_info_async as *const (), // 0x40 + security_info_size as *const (), // 0x48 + security_info_result as *const (), // 0x50 + missing::<11> as *const (), // 0x58 the same for UTF-16 URLs + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 + verify_certificate as *const (), // 0x70 + connectivity_hint as *const (), // 0x78 + register as *const (), // 0x80 hint changed (never) + unregister as *const (), // 0x88 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn offline_but_initialized() { + let this: This = &OBJECT; + type Hint = extern "system" fn(This, *mut ConnectivityHint) -> HRESULT; + let mut hint = OFFLINE; + hint.initialized = false; + assert_eq!(method::<Hint>(&OBJECT, 0x78)(this, &mut hint), S_OK); + assert!(hint.initialized && hint.level == 1); + assert_eq!(size_of::<ConnectivityHint>(), 16); + + type Begin = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + type Port = extern "system" fn(This, *mut AsyncBlock, *mut u16) -> HRESULT; + let mut b = block(); + assert_eq!(method::<Begin>(&OBJECT, 0x20)(this, &mut b), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut port = 0; + assert_eq!(method::<Port>(&OBJECT, 0x28)(this, &mut b, &mut port), S_OK); + assert_eq!(port, 3074); + + type Url = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT; + type Size = extern "system" fn(This, *mut AsyncBlock, *mut usize) -> HRESULT; + let mut b = block(); + let url = c"https://example.invalid/"; + assert_eq!( + method::<Url>(&OBJECT, 0x40)(this, url.as_ptr(), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), UNREACHABLE); + let mut size = 0; + assert_eq!( + method::<Size>(&OBJECT, 0x48)(this, &mut b, &mut size), + UNREACHABLE + ); + } +} diff --git a/crates/victory-hle/src/modules/xpackage.rs b/crates/victory-hle/src/modules/xpackage.rs new file mode 100644 index 000000000..4f0363590 --- /dev/null +++ b/crates/victory-hle/src/modules/xpackage.rs @@ -0,0 +1,371 @@ +//! XPackage: the title's own installation, complete and launchable, with +//! every chunk ready; no other package (content, add-ons) is installed. +//! The package is the folder of the title's executable (`G:` to the title). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; +use std::path::Path; +use std::sync::OnceLock; + +use super::xasync::{self, AsyncBlock}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0xaf40_6016, + 0xe850, + 0x4aa8, + [0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e], +); + +/// As Grand Theft Auto VI (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( + 0x0b9d_556e, + 0xab70, + 0x43f4, + [0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40], +); + +pub static OBJECT: Object = Object::new("package", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; + +/// The documented "could not resolve an identifier for the package". +pub const NO_PACKAGE: HRESULT = 0x8924_5208_u32 as i32; + +/// Our installation's identifier: the title id in hex (titles keep it in 33 +/// bytes and hand it back to us). +pub fn identifier() -> String { + format!("{:08X}", runtime::title().id) +} + +fn is_ours(id: *const c_char) -> bool { + text(id).is_some_and(|id| id == identifier()) +} + +/// Bytes in the package folder, counted once. +fn package_bytes() -> u64 { + fn size(dir: &Path) -> u64 { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| match e.metadata() { + Ok(m) if m.is_dir() => size(&e.path()), + Ok(m) => m.len(), + Err(_) => 0, + }) + .sum() + } + static BYTES: OnceLock<u64> = OnceLock::new(); + *BYTES.get_or_init(|| { + let exe = runtime::main_image().and_then(runtime::image_path); + exe.as_deref().and_then(Path::parent).map_or(0, size) + }) +} + +type This = *const Object; + +extern "system" fn current_identifier(_: This, size: usize, buffer: *mut u8) -> HRESULT { + put_string(&identifier(), size, buffer, std::ptr::null_mut()) +} + +extern "system" fn is_packaged(_: This) -> bool { + true +} + +/// Installation monitors all watch the same finished installation, so the +/// handle is a fixed address. +static MONITOR: u8 = 0; +fn monitor() -> *const c_void { + (&raw const MONITOR).cast() +} + +extern "system" fn create_monitor( + _: This, + id: *const c_char, + _selector_count: u32, + _selectors: *const c_void, + _interval_ms: u32, + _queue: *const c_void, + out: *mut *const c_void, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + put(out, monitor()) +} +extern "system" fn close_monitor(_: This, _: *const c_void) {} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Progress { + pub total_bytes: u64, + pub installed_bytes: u64, + pub launch_bytes: u64, + pub launchable: bool, + pub completed: bool, +} + +extern "system" fn progress(_: This, _: *const c_void, out: *mut Progress) { + let bytes = package_bytes(); + put( + out, + Progress { + total_bytes: bytes, + installed_bytes: bytes, + launch_bytes: bytes, + launchable: true, + completed: true, + }, + ); +} + +/// The installation is complete, so progress never changes. +extern "system" fn register_progress( + _: This, + _monitor: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} + +/// 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 +// chunks, which a full install has. +extern "system" fn find_availability( + _: This, + id: *const c_char, + _selector_count: u32, + _selectors: *const c_void, + out: *mut u32, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + put(out, 0) +} + +extern "system" fn change_order( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, +) -> HRESULT { + if is_ours(id) { S_OK } else { NO_PACKAGE } +} + +static INSTALL: u8 = 0; + +/// Everything is installed: done at once, the result is a monitor. +extern "system" fn install_chunks_async( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, + _interval_ms: u32, + _suppress_confirmation: bool, + block: *mut AsyncBlock, +) -> HRESULT { + let result = if is_ours(id) { + Ok(xasync::bytes(monitor())) + } else { + Err(NO_PACKAGE) + }; + xasync::finished_with(block, (&raw const INSTALL).cast(), result) +} +extern "system" fn install_chunks_result( + _: This, + block: *mut AsyncBlock, + out: *mut *const c_void, +) -> HRESULT { + xasync::result(block, (&raw const INSTALL).cast(), out) +} + +/// Nothing to download. +extern "system" fn estimate_download( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, + bytes: *mut u64, + confirm: *mut bool, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + if !confirm.is_null() { + // SAFETY: checked non-null. + unsafe { confirm.write(false) }; + } + put(bytes, 0) +} + +// 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 +// (title+0x293b4b0, its chunk manager) would then see them still installed. +extern "system" fn uninstall_chunks( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, +) -> HRESULT { + if is_ours(id) { S_OK } else { NO_PACKAGE } +} + +/// Mount handles only come from mounting another package, and there is +/// none. +extern "system" fn mount_path(_: This, _: *const c_void, _: usize, _: *mut u8) -> HRESULT { + xasync::E_INVALIDARG +} +extern "system" fn close_mount(_: This, _: *const c_void) {} + +/// Only other packages are uninstalled this way, and none is installed. +extern "system" fn uninstall_package(_: This, id: *const c_char) -> bool { + tracing::info!( + id = text(id).unwrap_or_default(), + "package uninstall refused" + ); + false +} + +static MOUNT: u8 = 0; + +extern "system" fn mount_async(_: This, id: *const c_char, block: *mut AsyncBlock) -> HRESULT { + tracing::info!( + id = text(id).unwrap_or_default(), + "package mount: not installed" + ); + xasync::finished(block, (&raw const MOUNT).cast(), NO_PACKAGE) +} +extern "system" fn mount_result( + _: This, + block: *mut AsyncBlock, + out: *mut *const c_void, +) -> HRESULT { + xasync::result(block, (&raw const MOUNT).cast(), out) +} + +/// 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). +extern "system" fn enumerate( + _: This, + kind: u32, + _scope: u32, + _context: *mut c_void, + _callback: *const c_void, +) -> HRESULT { + tracing::debug!(kind, "packages enumerated: none"); + S_OK +} + +static VTABLE: Methods<40> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + current_identifier as *const (), // 0x18 + is_packaged as *const (), // 0x20 + create_monitor as *const (), // 0x28 + close_monitor as *const (), // 0x30 + progress as *const (), // 0x38 + missing::<8> as *const (), // 0x40 update a monitor + register_progress as *const (), // 0x48 + missing::<10> as *const (), // 0x50 unregister it + missing::<11> as *const (), // 0x58 user locale + find_availability as *const (), // 0x60 + missing::<13> as *const (), // 0x68 enumerate chunk availability + change_order as *const (), // 0x70 + missing::<15> as *const (), // 0x78 install chunks + install_chunks_async as *const (), // 0x80 + install_chunks_result as *const (), // 0x88 + estimate_download as *const (), // 0x90 + uninstall_chunks as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + missing::<21> as *const (), // 0xa8 + missing::<22> as *const (), // 0xb0 + missing::<23> as *const (), // 0xb8 mount (deprecated) + missing::<24> as *const (), // 0xc0 mount path size + mount_path as *const (), // 0xc8 + close_mount as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 + missing::<28> as *const (), // 0xe0 enumerate packages (older) + missing::<29> as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 + missing::<31> as *const (), // 0xf8 + missing::<32> as *const (), // 0x100 + missing::<33> as *const (), // 0x108 + uninstall_package as *const (), // 0x110 + missing::<35> as *const (), // 0x118 + missing::<36> as *const (), // 0x120 + mount_async as *const (), // 0x128 + mount_result as *const (), // 0x130 + enumerate as *const (), // 0x138 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn the_installation_is_complete_and_alone() { + let this: This = &OBJECT; + type Id = extern "system" fn(This, usize, *mut u8) -> HRESULT; + let mut id = [0u8; 33]; + assert_eq!(method::<Id>(&OBJECT, 0x18)(this, 33, id.as_mut_ptr()), S_OK); + let len = id.iter().position(|&b| b == 0).unwrap(); + assert_eq!(std::str::from_utf8(&id[..len]).unwrap(), identifier()); + assert!(method::<extern "system" fn(This) -> bool>(&OBJECT, 0x20)( + this + )); + + type Find = + extern "system" fn(This, *const c_char, u32, *const c_void, *mut u32) -> HRESULT; + let mut availability = 9; + let ours = format!("{}\0", identifier()); + let find = method::<Find>(&OBJECT, 0x60); + let none = std::ptr::null(); + assert_eq!( + find(this, ours.as_ptr().cast(), 0, none, &mut availability), + S_OK + ); + assert_eq!(availability, 0, "ready"); + assert_eq!( + find(this, c"dlc".as_ptr(), 0, none, &mut availability), + NO_PACKAGE + ); + + type Progress_ = extern "system" fn(This, *const c_void, *mut Progress); + let mut p = Progress { + total_bytes: 1, + installed_bytes: 0, + launch_bytes: 0, + launchable: false, + completed: false, + }; + method::<Progress_>(&OBJECT, 0x38)(this, monitor(), &mut p); + assert!(p.completed && p.launchable && p.installed_bytes == p.total_bytes); + + type Mount = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT; + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!( + method::<Mount>(&OBJECT, 0x128)(this, c"dlc".as_ptr(), &mut block), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), NO_PACKAGE); + } +} diff --git a/crates/victory-hle/src/modules/xstore.rs b/crates/victory-hle/src/modules/xstore.rs new file mode 100644 index 000000000..3e294222d --- /dev/null +++ b/crates/victory-hle/src/modules/xstore.rs @@ -0,0 +1,479 @@ +//! XStore as an offline console answers it: the game's own licence is +//! local and active (a full, owned game); the user owns no add-ons; what +//! needs the store service (catalog, consumables, purchase and update +//! pages, collection ids, update checks) fails with the documented store +//! network error. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; +use super::xpackage; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0x0dd1_12ac, + 0x7c24, + 0x448c, + [0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c], +); +/// As Grand Theft Auto VI (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, + 0x2414, + 0x4a05, + [0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44], +); +/// The same table extended by durables licensing (0x238, 0x240). +pub const DURABLES_IID: Guid = Guid::new( + 0x2d42_fea5, + 0xe71d, + 0x4b76, + [0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d], +); + +pub static OBJECT: Object = Object::new("store", &VTABLE); +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID_2026, &OBJECT), + (PROVIDER, DURABLES_IID, &OBJECT), +]; + +/// The documented "failed to communicate with the store network". +pub const NETWORK_ERROR: HRESULT = 0x8924_5301_u32 as i32; + +type This = *const Object; +type Handle = *const c_void; + +/// Contexts and product queries hold nothing (queries are always empty), +/// so their handles are fixed addresses. A licence handle says whether it +/// is valid by which address it is. +static CONTEXT: u8 = 0; +static QUERY: u8 = 0; +static VALID: u8 = 0; +static INVALID: u8 = 0; +fn handle(of: &'static u8) -> Handle { + (of as *const u8).cast() +} + +/// Identifies our calls on a block: one per result shape. +static FAILED: u8 = 0; +static QUERY_CALL: u8 = 0; +static LICENSE_CALL: u8 = 0; +static GAME_LICENSE: u8 = 0; + +fn offline(block: *mut AsyncBlock, what: &str) -> HRESULT { + tracing::info!(what, "store call: offline"); + xasync::finished(block, (&raw const FAILED).cast(), NETWORK_ERROR) +} +/// The result functions of calls that failed: their status. +extern "system" fn status(_: This, block: *mut AsyncBlock) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} + +extern "system" fn create_context(_: This, _user: *const c_void, out: *mut Handle) -> HRESULT { + put(out, handle(&CONTEXT)) +} +extern "system" fn close(_: This, _: Handle) {} + +extern "system" fn associated_products_async( + _: This, + _: Handle, + _kinds: u32, + _per_page: u32, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "associated products") +} + +/// The user owns no add-ons: an empty query. +extern "system" fn entitled_products_async( + _: This, + _: Handle, + _kinds: u32, + _per_page: u32, + block: *mut AsyncBlock, +) -> HRESULT { + xasync::finished_with( + block, + (&raw const QUERY_CALL).cast(), + Ok(xasync::bytes(handle(&QUERY))), + ) +} +extern "system" fn query_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::result(block, (&raw const QUERY_CALL).cast(), out) +} +/// Empty, so the callback never runs. +extern "system" fn enumerate_products( + _: This, + _: Handle, + _: *mut c_void, + _: *const c_void, +) -> HRESULT { + S_OK +} +extern "system" fn has_more_pages(_: This, _: Handle) -> bool { + false +} +/// There is no next page to ask for. +extern "system" fn next_page_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + xasync::finished(block, (&raw const QUERY_CALL).cast(), E_ILLEGAL_METHOD_CALL) +} + +fn license_for(owned: bool, block: *mut AsyncBlock) -> HRESULT { + let license = handle(if owned { &VALID } else { &INVALID }); + xasync::finished_with( + block, + (&raw const LICENSE_CALL).cast(), + Ok(xasync::bytes(license)), + ) +} +/// Only the game's own package is installed, so only its licence is valid. +extern "system" fn license_for_package_async( + _: This, + _: Handle, + package: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + let ours = text(package).is_some_and(|p| p == xpackage::identifier()); + license_for(ours, block) +} +/// The user owns no durables: their licences are not valid. +extern "system" fn license_for_durables_async( + _: This, + _: Handle, + store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::debug!( + store_id = text(store_id).unwrap_or_default(), + "durable not owned" + ); + license_for(false, block) +} +extern "system" fn license_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::result(block, (&raw const LICENSE_CALL).cast(), out) +} +extern "system" fn is_license_valid(_: This, license: Handle) -> bool { + license == handle(&VALID) +} + +/// The game licence, as the public API lays it out. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct GameLicense { + pub sku_store_id: [u8; 18], + pub is_active: bool, + pub is_trial_owned_by_this_user: bool, + pub is_disc_license: bool, + pub is_trial: bool, + pub trial_seconds_remaining: u32, + pub trial_unique_id: [u8; 64], + pub expiration: i64, +} + +/// A full, active licence for the game's SKU (`<store id>/0010`, the +/// store's first SKU), not a trial, without expiry. +fn game_license() -> GameLicense { + let mut sku = [0u8; 18]; + let id = format!("{}/0010", runtime::title().store_id); + let len = id.len().min(sku.len() - 1); + sku[..len].copy_from_slice(&id.as_bytes()[..len]); + GameLicense { + sku_store_id: sku, + is_active: true, + is_trial_owned_by_this_user: false, + is_disc_license: false, + is_trial: false, + trial_seconds_remaining: 0, + trial_unique_id: [0; 64], + expiration: 0, + } +} + +extern "system" fn game_license_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + let license = xasync::bytes(game_license()); + xasync::finished_with(block, (&raw const GAME_LICENSE).cast(), Ok(license)) +} +extern "system" fn game_license_result( + _: This, + block: *mut AsyncBlock, + out: *mut GameLicense, +) -> HRESULT { + xasync::result(block, (&raw const GAME_LICENSE).cast(), out) +} + +extern "system" fn consumable_balance_async( + _: This, + _: Handle, + _store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "consumable balance") +} +extern "system" fn report_fulfillment_async( + _: This, + _: Handle, + _store_id: *const c_char, + _quantity: u32, + _tracking_id: *const c_void, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "consumable fulfillment") +} +/// Collections and purchase ids alike. +extern "system" fn user_id_async( + _: This, + _: Handle, + _ticket: *const c_char, + _publisher_user_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "user store id") +} +extern "system" fn size_status(_: This, block: *mut AsyncBlock, _out: *mut usize) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn string_status( + _: This, + block: *mut AsyncBlock, + _: usize, + _: *mut c_char, +) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn count_status(_: This, block: *mut AsyncBlock, _out: *mut u32) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn array_status( + _: This, + block: *mut AsyncBlock, + _: u32, + _: *mut c_void, +) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} + +extern "system" fn purchase_ui_async( + _: This, + _: Handle, + _store_id: *const c_char, + _name: *const c_char, + _json: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "purchase page") +} +extern "system" fn product_page_ui_async( + _: This, + _: Handle, + _store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "product page") +} +extern "system" fn redeem_ui_async( + _: This, + _: Handle, + _token: *const c_char, + _allowed: *const *const c_char, + _allowed_count: usize, + _disallow_csv: bool, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "redeem page") +} +extern "system" fn updates_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + offline(block, "update check") +} +/// Installing updates or packages by id alike. +extern "system" fn install_async( + _: This, + _: Handle, + _ids: *const *const c_char, + _count: usize, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "package download") +} + +/// The game's own store id maps to its installation; nothing else is +/// installed. +extern "system" fn package_identifier( + _: This, + store_id: *const c_char, + size: usize, + buffer: *mut u8, +) -> HRESULT { + let title = runtime::title(); + match text(store_id) { + Some(id) if !title.store_id.is_empty() && id == title.store_id => { + put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut()) + } + _ => xpackage::NO_PACKAGE, + } +} + +/// Licences never change offline, so these callbacks never run. +extern "system" fn register( + _: This, + _: Handle, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> bool { + true +} + +static VTABLE: Methods<76> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + create_context as *const (), // 0x18 + close as *const (), // 0x20 + associated_products_async as *const (), // 0x28 + query_result as *const (), // 0x30 + missing::<7> as *const (), // 0x38 products by id + missing::<8> as *const (), // 0x40 + entitled_products_async as *const (), // 0x48 + query_result as *const (), // 0x50 + missing::<11> as *const (), // 0x58 product for the game + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 product for a package + missing::<14> as *const (), // 0x70 + enumerate_products as *const (), // 0x78 + has_more_pages as *const (), // 0x80 + next_page_async as *const (), // 0x88 + query_result as *const (), // 0x90 + close as *const (), // 0x98 a product query + license_for_package_async as *const (), // 0xa0 + license_result as *const (), // 0xa8 + is_license_valid as *const (), // 0xb0 + close as *const (), // 0xb8 a licence + missing::<24> as *const (), // 0xc0 can acquire for store id + missing::<25> as *const (), // 0xc8 + missing::<26> as *const (), // 0xd0 can acquire for package + missing::<27> as *const (), // 0xd8 + game_license_async as *const (), // 0xe0 + game_license_result as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 add-on licences + missing::<31> as *const (), // 0xf8 + missing::<32> as *const (), // 0x100 + consumable_balance_async as *const (), // 0x108 + status as *const (), // 0x110 + report_fulfillment_async as *const (), // 0x118 + missing::<36> as *const (), // 0x120 + user_id_async as *const (), // 0x128 collections id + size_status as *const (), // 0x130 + string_status as *const (), // 0x138 + user_id_async as *const (), // 0x140 purchase id + size_status as *const (), // 0x148 + string_status as *const (), // 0x150 + missing::<43> as *const (), // 0x158 licence token + missing::<44> as *const (), // 0x160 + missing::<45> as *const (), // 0x168 + missing::<46> as *const (), // 0x170 + missing::<47> as *const (), // 0x178 + missing::<48> as *const (), // 0x180 + purchase_ui_async as *const (), // 0x188 + missing::<50> as *const (), // 0x190 + missing::<51> as *const (), // 0x198 rate and review + missing::<52> as *const (), // 0x1a0 + redeem_ui_async as *const (), // 0x1a8 + missing::<54> as *const (), // 0x1b0 + updates_async as *const (), // 0x1b8 + count_status as *const (), // 0x1c0 + array_status as *const (), // 0x1c8 + missing::<58> as *const (), // 0x1d0 download updates + missing::<59> as *const (), // 0x1d8 + install_async as *const (), // 0x1e0 updates + status as *const (), // 0x1e8 + install_async as *const (), // 0x1f0 packages by store id + count_status as *const (), // 0x1f8 + array_status as *const (), // 0x200 + package_identifier as *const (), // 0x208 + register as *const (), // 0x210 game licence changed + unregister as *const (), // 0x218 + register as *const (), // 0x220 package licence lost + unregister as *const (), // 0x228 + missing::<70> as *const (), // 0x230 + license_for_durables_async as *const (), // 0x238 + license_result as *const (), // 0x240 + missing::<73> as *const (), // 0x248 associated products page + missing::<74> as *const (), // 0x250 + product_page_ui_async as *const (), // 0x258 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn the_game_is_licensed_and_the_store_is_offline() { + let this: This = &OBJECT; + assert_eq!(size_of::<GameLicense>(), 104); + type Begin = extern "system" fn(This, Handle, *mut AsyncBlock) -> HRESULT; + type Result = extern "system" fn(This, *mut AsyncBlock, *mut GameLicense) -> HRESULT; + let mut b = block(); + assert_eq!( + method::<Begin>(&OBJECT, 0xe0)(this, handle(&CONTEXT), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut license = std::mem::MaybeUninit::<GameLicense>::zeroed(); + assert_eq!( + method::<Result>(&OBJECT, 0xe8)(this, &mut b, license.as_mut_ptr()), + S_OK + ); + // SAFETY: written by the call. + let license = unsafe { license.assume_init() }; + assert!(license.is_active && !license.is_trial); + + let mut b = block(); + assert_eq!( + method::<Begin>(&OBJECT, 0x1b8)(this, handle(&CONTEXT), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + type Count = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + assert_eq!( + method::<Count>(&OBJECT, 0x1c0)(this, &mut b, &mut 0), + NETWORK_ERROR + ); + + type Durable = extern "system" fn(This, Handle, *const c_char, *mut AsyncBlock) -> HRESULT; + type License = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT; + let mut b = block(); + let durable = method::<Durable>(&OBJECT, 0x238); + assert_eq!( + durable(this, handle(&CONTEXT), c"9XYZ".as_ptr(), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut l = std::ptr::null(); + assert_eq!( + method::<License>(&OBJECT, 0x240)(this, &mut b, &mut l), + S_OK + ); + assert!(!method::<extern "system" fn(This, Handle) -> bool>( + &OBJECT, 0xb0 + )(this, l)); + } +} diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs new file mode 100644 index 000000000..a3a1d626e --- /dev/null +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -0,0 +1,400 @@ +//! XSystem: the console's identity and sandbox, and how analytics describe +//! the device. Fixed values: one offline retail console, the model the user +//! chose ([`victory_gpu::console`]). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put_string, +}; + +pub const PROVIDER: Guid = Guid::new( + 0xe349_bd1a, + 0xfc20, + 0x4e40, + [0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f], +); + +/// The interface as Minecraft (2022) asks for it; an older table +/// ended before the device id. +pub const IID: Guid = Guid::new( + 0x6fd7_1f09, + 0x7513, + 0x49f0, + [0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52], +); + +/// Analytics information; its interface id is the provider's. +pub const ANALYTICS: Guid = Guid::new( + 0xb884_675d, + 0xb738, + 0x4a9c, + [0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b], +); + +/// 38 characters (39 bytes with the NUL). +const CONSOLE_ID: &str = "00000000000000000000000000000000000001"; +/// The retail sandbox. +const SANDBOX: &str = "RETAIL"; +/// Base64 of 32 bytes: 44 characters (45 bytes with the NUL). +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 +/// same three slots (0x18, 0x20, 0x28) with the same arguments. +pub const IID_2026: Guid = Guid::new( + 0x1861_cf2e, + 0xe18b, + 0x4834, + [0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf], +); + +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID, &OBJECT), + (PROVIDER, IID_2026, &OBJECT), + (ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT), +]; + +type This = *const Object; + +extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(CONSOLE_ID, size, buffer, used) +} +extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(SANDBOX, size, buffer, used) +} +/// The device id this title sees (titles see different ones). +extern "system" fn device_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(DEVICE_ID, size, buffer, used) +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Version { + pub major: u16, + pub minor: u16, + pub build: u16, + pub revision: u16, +} + +#[repr(C)] +pub struct AnalyticsInfo { + pub os: Version, + pub hosting_os: Version, + /// NUL-terminated. + pub family: [u8; 64], + pub form: [u8; 64], +} + +const OS: Version = Version { + major: 10, + minor: 0, + build: 22000, + revision: 0, +}; + +fn text(s: &str) -> [u8; 64] { + let mut out = [0; 64]; + out[..s.len()].copy_from_slice(s.as_bytes()); + out +} + +/// A struct this large comes back through the caller's buffer, whose +/// address is also the return value. +extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo { + let info = AnalyticsInfo { + os: OS, + hosting_os: OS, + family: text("Xbox"), + form: text(victory_gpu::console::current().name()), + }; + // SAFETY: the caller passes room for the struct. + unsafe { out.write(info) }; + out +} + +static VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + console_id as *const (), // 0x18, by the older table; titles seen do not call it + sandbox_id as *const (), // 0x20 + device_id as *const (), // 0x28 +]); + +static ANALYTICS_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + analytics_info as *const (), // 0x18 +]); + +/// The device type is not a runtime call: code linked into the title reads +/// `ConsoleMode` from this key (`RegOpenKeyW`, `RegQueryValueExW`) and +/// takes a missing value for a PC. +#[cfg(windows)] +mod device_type { + #![allow(non_snake_case)] + + use std::ffi::c_void; + + use victory_gpu::console::{self, Console}; + + use crate::modules::files::host; + use crate::{HleModule, hle_export}; + + type Key = *mut c_void; + const LOCAL_MACHINE: Key = 0xffff_ffff_8000_0002_u64 as Key; + const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\OEM"; + const VALUE: &str = "ConsoleMode"; + const SUCCESS: u32 = 0; + const FILE_NOT_FOUND: u32 = 2; + const INVALID_PARAMETER: u32 = 87; + const MORE_DATA: u32 = 234; + const DWORD: u32 = 4; + + /// Stands for the key; never a host handle value. + static OEM: u8 = 0; + fn oem() -> Key { + (&raw const OEM).cast_mut().cast() + } + + /// What the title's code maps to each model's device type. + pub(super) fn console_mode(console: Console) -> u32 { + match console { + Console::SeriesX => 0x64, + Console::SeriesS => 0x60, + } + } + + fn is(text: *const u16, expected: &str) -> bool { + if text.is_null() { + return false; + } + // SAFETY: the title passes a NUL-terminated string. + let text = unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }; + text.eq_ignore_ascii_case(expected) + } + + /// Opens our key for its path; the key has no subkeys. `None`: not + /// ours, ask the host. + fn open(root: Key, sub: *const u16, out: *mut Key) -> Option<u32> { + if root == oem() { + return Some(FILE_NOT_FOUND); + } + if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() { + // SAFETY: checked non-null; the title passes room for a key. + unsafe { out.write(oem()) }; + return Some(SUCCESS); + } + None + } + + // Our titles import only these registry functions (and `RegOpenKeyExW` + // below), so no other call can reach the host with our key. + pub extern "system" fn RegOpenKeyW(root: Key, sub: *const u16, out: *mut Key) -> u32 { + open(root, sub, out).unwrap_or_else(|| { + host!("advapi32.dll", "RegOpenKeyW": extern "system" fn(Key, *const u16, *mut Key) -> u32)( + root, sub, out, + ) + }) + } + + pub extern "system" fn RegOpenKeyExW( + root: Key, + sub: *const u16, + options: u32, + access: u32, + out: *mut Key, + ) -> u32 { + open(root, sub, out).unwrap_or_else(|| { + host!("advapi32.dll", "RegOpenKeyExW": extern "system" fn( + Key, *const u16, u32, u32, *mut Key, + ) -> u32)(root, sub, options, access, out) + }) + } + + pub extern "system" fn RegQueryValueExW( + key: Key, + name: *const u16, + reserved: *mut u32, + kind: *mut u32, + data: *mut u8, + size: *mut u32, + ) -> u32 { + if key != oem() { + return host!("advapi32.dll", "RegQueryValueExW": extern "system" fn( + Key, *const u16, *mut u32, *mut u32, *mut u8, *mut u32, + ) -> u32)(key, name, reserved, kind, data, size); + } + if !is(name, VALUE) { + return FILE_NOT_FOUND; + } + if !data.is_null() && size.is_null() { + return INVALID_PARAMETER; + } + // SAFETY: the title passes valid or null pointers, sized by `size`. + unsafe { + if !kind.is_null() { + kind.write(DWORD); + } + if size.is_null() { + return SUCCESS; + } + let room = size.read(); + size.write(4); + if data.is_null() { + return SUCCESS; + } + if room < 4 { + return MORE_DATA; + } + data.cast::<u32>() + .write_unaligned(console_mode(console::current())); + } + tracing::debug!(console = console::current().name(), "device type read"); + SUCCESS + } + + pub extern "system" fn RegCloseKey(key: Key) -> u32 { + if key == oem() { + return SUCCESS; + } + host!("advapi32.dll", "RegCloseKey": extern "system" fn(Key) -> u32)(key) + } + + pub(crate) fn module() -> HleModule { + HleModule { + name: "device type", + dlls: &["advapi32.dll", "api-ms-win-core-registry-*"], + exports: vec![ + hle_export!(RegOpenKeyW), + hle_export!(RegOpenKeyExW), + hle_export!(RegQueryValueExW), + hle_export!(RegCloseKey), + ], + } + } + + #[cfg(test)] + mod tests { + use super::*; + + fn w(s: &str) -> Vec<u16> { + s.encode_utf16().chain([0]).collect() + } + + #[test] + fn titles_read_the_chosen_model() { + assert_eq!(console_mode(Console::SeriesX), 0x64); + assert_eq!(console_mode(Console::SeriesS), 0x60); + let mut key = std::ptr::null_mut(); + let path = w(&KEY.to_ascii_lowercase()); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + let (mut kind, mut value, mut size) = (0, 0u32, 4); + let name = w(VALUE); + let query = |data: *mut u32, size: *mut u32, kind: *mut u32| { + RegQueryValueExW( + key, + name.as_ptr(), + std::ptr::null_mut(), + kind, + data.cast(), + size, + ) + }; + assert_eq!(query(&mut value, &mut size, &mut kind), SUCCESS); + assert_eq!((kind, size), (DWORD, 4)); + assert_eq!(value, console_mode(console::current())); + let mut small = 2; + assert_eq!(query(&mut value, &mut small, &mut kind), MORE_DATA); + assert_eq!(small, 4); + let other = w("Other"); + assert_eq!( + RegQueryValueExW( + key, + other.as_ptr(), + std::ptr::null_mut(), + &mut kind, + std::ptr::null_mut(), + &mut size + ), + FILE_NOT_FOUND + ); + let mut sub = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(key, other.as_ptr(), 0, 1, &mut sub), + FILE_NOT_FOUND + ); + assert_eq!(RegCloseKey(key), SUCCESS); + let mut again = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(LOCAL_MACHINE, path.as_ptr(), 0, 1, &mut again), + SUCCESS + ); + assert_eq!(again, oem()); + } + + #[test] + fn other_keys_reach_the_host() { + let mut key = std::ptr::null_mut(); + let path = w(r"Software\Microsoft\Windows NT\CurrentVersion"); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + assert_ne!(key, oem()); + let (mut size, name) = (0, w("ProductName")); + assert_eq!( + RegQueryValueExW( + key, + name.as_ptr(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut size + ), + SUCCESS + ); + assert!(size > 0); + assert_eq!(RegCloseKey(key), SUCCESS); + } + } +} +#[cfg(windows)] +pub(crate) use device_type::module; + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + #[test] + fn identity_strings_fit_the_documented_sizes() { + type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let mut buffer = [0u8; 64]; + let mut used = 0; + for (slot, size) in [(0x18, 39), (0x20, 16), (0x28, 45)] { + let get = method::<Get>(&OBJECT, slot); + assert_eq!(get(this, size, buffer.as_mut_ptr(), &mut used), S_OK); + assert!(used <= size && buffer[used - 1] == 0, "slot {slot:#x}"); + } + assert_eq!(&buffer[..7], b"VkljdG9"); + } + + #[test] + fn analytics_info_comes_back_through_the_buffer() { + type Get = extern "system" fn(This, *mut AnalyticsInfo) -> *mut AnalyticsInfo; + let mut info = std::mem::MaybeUninit::<AnalyticsInfo>::uninit(); + let get = method::<Get>(&ANALYTICS_OBJECT, 0x18); + let back = get(&ANALYTICS_OBJECT, info.as_mut_ptr()); + assert_eq!(back, info.as_mut_ptr()); + // SAFETY: written by the call. + let info = unsafe { info.assume_init() }; + assert_eq!(size_of::<AnalyticsInfo>(), 0x90); + assert_eq!(info.os.build, 22000); + assert_eq!(&info.form[..14], b"Xbox Series X\0"); + } +} diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs new file mode 100644 index 000000000..8b48dfc0d --- /dev/null +++ b/crates/victory-hle/src/modules/xuser.rs @@ -0,0 +1,425 @@ +//! XUser: one offline local user, signed in, never a guest, with every +//! privilege. Served as the user provider's objects from `QueryApiImpl`; +//! adding a user completes through `xasync` like any other async call. No +//! input device is associated with the user (there are none, `gameinput`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, ProviderData}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; + +/// The user provider. +pub const PROVIDER: Guid = Guid { + data1: 0x01ac_d177, + data2: 0x91f9, + data3: 0x4763, + data4: [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0], +}; + +/// Its main interface. +pub const IID: Guid = Guid { + data1: 0xeb9b_f948, + data2: 0x18dc, + data3: 0x4d82, + data4: [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0], +}; + +/// The interface titles ask for to read a gamertag. +pub const GAMERTAG_IID: Guid = Guid { + data1: 0xcef4_fac0, + data2: 0x7676, + data3: 0x4a94, + data4: [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74], +}; + +/// The user's devices and audio endpoints. +pub const DEVICE_PROVIDER: Guid = Guid::new( + 0x7d82_4997, + 0x10dc, + 0x45ab, + [0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1], +); + +/// The device interface as Minecraft (2022) asks for it. +pub const DEVICE_IID: Guid = Guid::new( + 0x0cc6_a956, + 0xe7e1, + 0x4fdf, + [0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8], +); + +/// The documented "no such user" error. +pub const USER_NOT_FOUND: HRESULT = 0x8924_5104_u32 as i32; + +pub const XUID: u64 = 0x0009_0000_0000_0001; +pub const LOCAL_ID: u64 = 1; +const GAMERTAG: &str = "Player"; + +/// The only user; a handle is its address, duplicating and closing are free. +pub struct User; +static USER: User = User; +type Handle = *const User; + +fn user() -> Handle { + &USER +} + +fn found(found: bool, out: *mut Handle) -> HRESULT { + if found { + put(out, user()) + } else { + USER_NOT_FOUND + } +} + +pub static OBJECT: Object = Object::new("user", &VTABLE); +pub static GAMERTAG_OBJECT: Object = Object::new("user gamertag", &GAMERTAG_VTABLE); +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 same slots with the same arguments (0x108/0x110 change events). + (PROVIDER, PROVIDER, &OBJECT), + (PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT), + (DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT), +]; + +type This = *const Object; +extern "system" fn duplicate(_: This, _: Handle, out: *mut Handle) -> HRESULT { + put(out, user()) +} +extern "system" fn close(_: This, _: Handle) {} +extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 { + i32::from(a != b) +} + +/// The async provider for adding a user: done at once, the result is a +/// handle. +extern "system" fn add_provider(op: u32, data: *const ProviderData) -> HRESULT { + const BEGIN: u32 = 0; + const GET_RESULT: u32 = 2; + // SAFETY: the async runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + BEGIN => xasync::XAsyncComplete(data.block, S_OK, size_of::<Handle>()), + GET_RESULT => return put(data.buffer.cast::<Handle>(), user()), + _ => {} + } + S_OK +} + +/// Tells our add calls apart from other async calls on the same block. +static ADD: u8 = 0; + +/// Any options add the one user, silently. +extern "system" fn add_async(_: This, options: u32, block: *mut AsyncBlock) -> HRESULT { + tracing::info!(options, "XUserAddAsync: the offline local user"); + xasync::XAsyncBegin( + block, + std::ptr::null_mut(), + (&raw const ADD).cast(), + std::ptr::null(), + Some(add_provider), + ) +} +extern "system" fn add_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::XAsyncGetResult( + block, + (&raw const ADD).cast(), + size_of::<Handle>(), + out.cast(), + std::ptr::null_mut(), + ) +} +extern "system" fn get_local_id(_: This, _: Handle, out: *mut u64) -> HRESULT { + put(out, LOCAL_ID) +} +extern "system" fn find_by_local_id(_: This, id: u64, out: *mut Handle) -> HRESULT { + found(id == LOCAL_ID, out) +} +extern "system" fn get_id(_: This, _: Handle, out: *mut u64) -> HRESULT { + put(out, XUID) +} +extern "system" fn find_by_id(_: This, id: u64, out: *mut Handle) -> HRESULT { + found(id == XUID, out) +} +extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT { + put(out, false) +} +/// 0: signed in. +extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT { + put(out, 0) +} +/// The user's gamertag as the component asked for (`XUserGamertagComponent`): +/// it has no suffix, so the modern suffix is empty and every other component +/// (classic, modern, unique modern) is the name itself. +extern "system" fn get_gamertag( + _: This, + _: Handle, + component: u32, + size: usize, + buffer: *mut u8, + used: *mut usize, +) -> HRESULT { + const MODERN_SUFFIX: u32 = 2; + let text = match component { + MODERN_SUFFIX => "", + _ => GAMERTAG, + }; + put_string(text, size, buffer, used) +} +/// Granted; deny reason 0 (none). +extern "system" fn check_privilege( + _: This, + _: Handle, + _options: u32, + _privilege: u32, + has: *mut bool, + reason: *mut u32, +) -> HRESULT { + if !reason.is_null() { + // SAFETY: checked non-null. + unsafe { reason.write(0) }; + } + put(has, true) +} + +/// 3: adult. +extern "system" fn get_age_group(_: This, _: Handle, out: *mut u32) -> HRESULT { + put(out, 3) +} + +static RESOLVE: u8 = 0; +static TOKEN: u8 = 0; + +/// Every privilege is granted, so there is nothing to resolve. +extern "system" fn resolve_privilege_async( + _: This, + _: Handle, + _options: u32, + _privilege: u32, + block: *mut AsyncBlock, +) -> HRESULT { + xasync::finished(block, (&raw const RESOLVE).cast(), S_OK) +} +extern "system" fn resolve_privilege_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const RESOLVE).cast(), 0, none, none.cast()) +} + +/// The documented "failed to get token": tokens come from the service. +pub const FAILED_TO_GET_TOKEN: HRESULT = 0x8924_5111_u32 as i32; + +#[allow(clippy::too_many_arguments)] +extern "system" fn token_async( + _: This, + _: Handle, + _options: u32, + _method: *const c_char, + url: *const c_char, + _header_count: usize, + _headers: *const c_void, + _body_size: usize, + _body: *const c_void, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::info!( + url = text(url).unwrap_or_default(), + "token and signature: offline" + ); + xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN) +} +extern "system" fn token_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + xasync::XAsyncGetResultSize(block, out) +} +extern "system" fn token_result( + _: This, + block: *mut AsyncBlock, + size: usize, + buffer: *mut c_void, + _data: *mut *const c_void, + used: *mut usize, +) -> HRESULT { + xasync::XAsyncGetResult(block, (&raw const TOKEN).cast(), size, buffer, used) +} + +/// The user never changes and no device is ever associated, so these +/// callbacks are never called. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +/// No input device belongs to a user. +extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Handle) -> HRESULT { + USER_NOT_FOUND +} + +// Unset slots (no title seen calls them): maximum users, gamer pictures, +// the UTF-16 token calls, issue resolution. +static VTABLE: Methods<35> = Methods([ + missing::<0> as *const (), // 0x00 QueryInterface + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + duplicate as *const (), // 0x18 + close as *const (), // 0x20 + compare as *const (), // 0x28 + missing::<6> as *const (), // 0x30 maximum users + add_async as *const (), // 0x38 + add_result as *const (), // 0x40 + get_local_id as *const (), // 0x48 + find_by_local_id as *const (), // 0x50 + get_id as *const (), // 0x58 + find_by_id as *const (), // 0x60 + get_is_guest as *const (), // 0x68 + get_state as *const (), // 0x70 + get_gamertag as *const (), // 0x78 older gamertag slot + missing::<16> as *const (), // 0x80 gamer picture: begin + missing::<17> as *const (), // 0x88 result size + missing::<18> as *const (), // 0x90 result + get_age_group as *const (), // 0x98 + check_privilege as *const (), // 0xa0 + resolve_privilege_async as *const (), // 0xa8 with UI + resolve_privilege_result as *const (), // 0xb0 + token_async as *const (), // 0xb8 token and signature + token_size as *const (), // 0xc0 + token_result as *const (), // 0xc8 + missing::<26> as *const (), // 0xd0 the same, UTF-16: begin + missing::<27> as *const (), // 0xd8 result size + missing::<28> as *const (), // 0xe0 result + missing::<29> as *const (), // 0xe8 resolve issue with UI: begin + missing::<30> as *const (), // 0xf0 result + missing::<31> as *const (), // 0xf8 the same, UTF-16: begin + missing::<32> as *const (), // 0x100 result + register as *const (), // 0x108 change event + unregister as *const (), // 0x110 +]); + +static GAMERTAG_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + get_gamertag as *const (), // 0x18 +]); + +static DEVICE_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + find_for_device as *const (), // 0x18 + register as *const (), // 0x20 device association changed + unregister as *const (), // 0x28 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xasync::E_NOT_SUFFICIENT_BUFFER; + use crate::modules::xgameruntime::method as slot; + + #[test] + fn a_gamertag_without_a_suffix_has_an_empty_modern_suffix() { + type Gamertag = + extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let user = std::ptr::null(); + // Classic, modern, modern suffix, unique modern; through both slots. + let expected: [&[u8]; 4] = [b"Player\0", b"Player\0", b"\0", b"Player\0"]; + for (object, at) in [(&GAMERTAG_OBJECT, 0x18), (&OBJECT, 0x78)] { + let get = slot::<Gamertag>(object, at); + for (component, expected) in (0..).zip(expected) { + let (mut name, mut used) = ([0xff_u8; 16], 0); + let hr = get(this, user, component, 16, name.as_mut_ptr(), &mut used); + assert_eq!(hr, S_OK); + assert_eq!(&name[..used], expected, "component {component}"); + } + } + } + + #[test] + fn startup_adds_the_user_and_reads_its_id() { + type Add = extern "system" fn(This, u32, *mut AsyncBlock) -> HRESULT; + type AddResult = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT; + type GetId = extern "system" fn(This, Handle, *mut u64) -> HRESULT; + type Gamertag = + extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!(slot::<Add>(&OBJECT, 0x38)(this, 1, &mut block), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), S_OK); + let mut handle = std::ptr::null(); + assert_eq!( + slot::<AddResult>(&OBJECT, 0x40)(this, &mut block, &mut handle), + S_OK + ); + assert!(!handle.is_null()); + let mut xuid = 0; + assert_eq!(slot::<GetId>(&OBJECT, 0x58)(this, handle, &mut xuid), S_OK); + assert_eq!(xuid, XUID); + + let mut name = [0u8; 16]; + let mut used = 0; + let get = slot::<Gamertag>(&GAMERTAG_OBJECT, 0x18); + assert_eq!(get(this, handle, 0, 16, name.as_mut_ptr(), &mut used), S_OK); + assert_eq!(&name[..used], b"Player\0"); + assert_eq!( + get(this, handle, 0, 2, name.as_mut_ptr(), &mut used), + E_NOT_SUFFICIENT_BUFFER + ); + + type Age = extern "system" fn(This, Handle, *mut u32) -> HRESULT; + let mut age = 0; + assert_eq!(slot::<Age>(&OBJECT, 0x98)(this, handle, &mut age), S_OK); + assert_eq!(age, 3, "adult"); + type Token = extern "system" fn( + This, + Handle, + u32, + *const c_char, + *const c_char, + usize, + *const c_void, + usize, + *const c_void, + *mut AsyncBlock, + ) -> HRESULT; + let (null, url) = (std::ptr::null(), c"https://example.invalid/"); + let token = slot::<Token>(&OBJECT, 0xb8); + assert_eq!( + token( + this, + handle, + 0, + c"GET".as_ptr(), + url.as_ptr(), + 0, + null, + 0, + null, + &mut block + ), + S_OK + ); + assert_eq!( + xasync::XAsyncGetStatus(&mut block, true), + FAILED_TO_GET_TOKEN + ); + } +} diff --git a/crates/victory-hle/src/registry.rs b/crates/victory-hle/src/registry.rs new file mode 100644 index 000000000..e8744b48e --- /dev/null +++ b/crates/victory-hle/src/registry.rs @@ -0,0 +1,95 @@ +//! The table of everything we implement. + +use std::sync::LazyLock; + +use crate::modules; + +/// One function we implement, under the name the title imports (`#n` for an +/// ordinal). +#[derive(Debug, Clone, Copy)] +pub struct HleExport { + pub name: &'static str, + pub address: usize, +} + +/// A group of implementations and the DLL names they answer for. +#[derive(Debug)] +pub struct HleModule { + /// Human-readable name, e.g. "kernel". + pub name: &'static str, + /// Lower-case DLL names served. A trailing `*` matches a prefix, which + /// covers versioned API sets (`api-ms-win-core-libraryloader-l1-2-0.dll`). + pub dlls: &'static [&'static str], + pub exports: Vec<HleExport>, +} + +impl HleModule { + pub fn serves(&self, dll: &str) -> bool { + let dll = dll.to_ascii_lowercase(); + self.dlls + .iter() + .any(|pattern| match pattern.strip_suffix('*') { + Some(prefix) => dll.starts_with(prefix), + None => dll == *pattern, + }) + } +} + +/// Declares an export whose Rust name equals the imported name. +#[macro_export] +macro_rules! hle_export { + ($f:ident) => { + $crate::HleExport { + name: stringify!($f), + address: $f as *const () as usize, + } + }; +} + +static REGISTRY: LazyLock<Vec<HleModule>> = LazyLock::new(modules::all); + +/// All modules we implement. +pub fn registry() -> &'static [HleModule] { + ®ISTRY +} + +pub(crate) fn lookup(dll: &str, name: &str) -> Option<usize> { + registry() + .iter() + .filter(|m| m.serves(dll)) + .flat_map(|m| m.exports.iter()) + .find(|e| e.name == name) + .map(|e| e.address) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn export_names_are_unique_per_dll_pattern() { + for module in registry() { + let mut names: Vec<_> = module.exports.iter().map(|e| e.name).collect(); + names.sort_unstable(); + let before = names.len(); + names.dedup(); + assert_eq!( + before, + names.len(), + "duplicate export in module {}", + module.name + ); + } + } + + #[test] + fn api_set_prefix_matching() { + let m = HleModule { + name: "t", + dlls: &["api-ms-win-core-libraryloader-*"], + exports: vec![], + }; + assert!(m.serves("API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.dll")); + assert!(!m.serves("api-ms-win-core-file-l1-1-0.dll")); + } +} diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs new file mode 100644 index 000000000..c8479c5e2 --- /dev/null +++ b/crates/victory-hle/src/runtime.rs @@ -0,0 +1,226 @@ +//! Process-wide state the implementations need. + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0); + +/// Records where the title's main image is mapped. The title expects +/// `GetModuleHandle(NULL)` and friends to return this, not our own exe. +pub fn set_main_image(base: usize) { + MAIN_IMAGE_BASE.store(base, Ordering::Release); +} + +pub fn main_image() -> Option<usize> { + match MAIN_IMAGE_BASE.load(Ordering::Acquire) { + 0 => None, + base => Some(base), + } +} + +/// Original file of each title image we mapped, by base address. +static IMAGE_PATHS: Mutex<Vec<(usize, PathBuf)>> = Mutex::new(Vec::new()); + +/// Records the file a title image was mapped from: the title asks for its +/// 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 = 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)); +} + +/// 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()); + paths.retain(|(b, _)| *b != base); +} + +pub fn image_path(base: usize) -> Option<PathBuf> { + let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths + .iter() + .find(|(b, _)| *b == base) + .map(|(_, p)| p.clone()) +} + +/// The title image whose original file is called `file` (any case). +pub fn image_named(file: &str) -> Option<usize> { + let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths + .iter() + .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file))) + .map(|(b, _)| *b) +} + +/// 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<dyn Fn(&str) -> Result<Option<usize>, String> + Send + Sync>; + +static TITLE_DLL_LOADER: std::sync::OnceLock<TitleDllLoader> = std::sync::OnceLock::new(); + +/// Set once, by whoever mapped the title (it knows the folders and the +/// resolver); later calls are ignored. +pub fn set_title_dll_loader(loader: TitleDllLoader) { + let _ = TITLE_DLL_LOADER.set(loader); +} + +pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> { + TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file)) +} + +/// What the title's manifest (`MicrosoftGame.config` beside its executable) +/// says about it, and where its persistent local storage lives. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Title { + pub id: u32, + /// The store's product id (empty if the manifest has none). + pub store_id: String, + /// Persistent local storage: our folder for it and the title's quota. + /// Game saves live beside it ([`Title::saves`]). + pub storage: PathBuf, + pub storage_bytes: u64, +} + +impl Title { + /// Id, store id and storage quota from the manifest (zero or empty + /// where it has none); the storage folder is left for the caller. + pub fn from_manifest(text: &str) -> Title { + let elements = elements(text); + let get = |path: &str| { + elements + .iter() + .find(|(p, _)| p == path) + .map(|(_, text)| text.as_str()) + }; + let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); + let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok()); + Title { + id: id.unwrap_or(0), + store_id: get("Game/StoreId").unwrap_or_default().to_owned(), + storage: PathBuf::new(), + storage_bytes: storage_mb.unwrap_or(0) << 20, + } + } + + /// Where game saves live: next to persistent local storage, under the + /// data directory, never the cache. + pub fn saves(&self) -> PathBuf { + self.storage.with_file_name("saves") + } +} + +/// Each element of an XML text as its path from the root (`Game/TitleId`) +/// and its trimmed text up to the first child, the predefined entities +/// decoded; comments, CDATA sections, declarations and attributes are +/// skipped. +fn elements(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut path: Vec<&str> = Vec::new(); + let mut rest = text; + while let Some(open) = rest.find('<') { + rest = &rest[open..]; + let end = if rest.starts_with("<!--") { + rest.find("-->").map(|e| e + 3) + } else if rest.starts_with("<![CDATA[") { + rest.find("]]>").map(|e| e + 3) + } else { + rest.find('>').map(|e| e + 1) + }; + let Some(end) = end else { break }; + let tag = &rest[1..end - 1]; + rest = &rest[end..]; + if tag.starts_with(['!', '?']) { + continue; + } + if let Some(name) = tag.strip_prefix('/') { + if let Some(at) = path.iter().rposition(|n| *n == name.trim()) { + path.truncate(at); + } + continue; + } + let closed = tag.ends_with('/'); + let name = tag + .trim_end_matches('/') + .split_whitespace() + .next() + .unwrap_or(""); + path.push(name); + let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] + .iter() + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + out.push((path.join("/"), body)); + if closed { + path.pop(); + } + } + out +} + +static TITLE: Mutex<Option<Title>> = Mutex::new(None); + +pub fn set_title(title: Title) { + *TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title); +} + +/// The running title; the default (id 0, no storage) until set. +pub fn title() -> Title { + TITLE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .unwrap_or_default() +} + +/// Gives the process the console's millisecond timers. Titles pace +/// themselves with short waits (Grand Theft Auto VI'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 +/// process opts out. Process-wide, for the whole run. +#[cfg(windows)] +pub fn use_console_timers() { + use windows_sys::Win32::Media::timeBeginPeriod; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, + ProcessPowerThrottling, SetProcessInformation, + }; + let keep = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + StateMask: 0, + }; + // SAFETY: plain process settings; `keep` outlives the call. + unsafe { + SetProcessInformation( + GetCurrentProcess(), + ProcessPowerThrottling, + (&raw const keep).cast(), + size_of_val(&keep) as u32, + ); + timeBeginPeriod(1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_title_id_store_id_and_storage_quota() { + let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\ + <!-- <TitleId>00000000</TitleId> -->\ + <Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\ + <![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&C</StoreId><Other><SizeMB>7</SizeMB></Other>\ + <PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\ + </PersistentLocalStorage></Game>"; + let t = Title::from_manifest(text); + assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20)); + assert_eq!(t.store_id, "9&C"); + assert_eq!(Title::from_manifest("").storage_bytes, 0); + } +} diff --git a/crates/victory-hle/tests/no_dll_planting.rs b/crates/victory-hle/tests/no_dll_planting.rs new file mode 100644 index 000000000..4018ee314 --- /dev/null +++ b/crates/victory-hle/tests/no_dll_planting.rs @@ -0,0 +1,29 @@ +//! Host pass-through must only load DLLs from System32, never from the +//! current folder (e.g. a title's folder shipping its own `msvcp140_*.dll`). +#![cfg(windows)] + +use victory_hle::{HleResolver, HostPolicy}; +use victory_pe::ImportSymbol; + +#[test] +fn ignores_dlls_in_current_folder() { + let name = "msvcp140_victorytest.dll"; + assert!( + HostPolicy::default().allows(name), + "test needs an allow-listed name" + ); + assert!(HostPolicy::default().allows("vcruntime140_1.dll")); + + let dir = tempfile::tempdir().unwrap(); + // Any loadable DLL will do. + std::fs::copy(r"C:\Windows\System32\version.dll", dir.path().join(name)).unwrap(); + std::env::set_current_dir(dir.path()).unwrap(); + + let symbol = ImportSymbol::Name { + hint: 0, + name: "GetFileVersionInfoSizeW".into(), + }; + let found = HleResolver::default().classify(name, &symbol); + std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")).unwrap(); + assert_eq!(found, None, "DLL was loaded from the current folder"); +} diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml new file mode 100644 index 000000000..0f3497b00 --- /dev/null +++ b/crates/victory-loader/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "victory-loader" +description = "Runs an Xbox title's original x86-64 image natively inside our process." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-core.workspace = true +victory-pe.workspace = true +anyhow.workspace = true +thiserror.workspace = true +tracing.workspace = true +blake3.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Wdk_System_Threading", + "Win32_Foundation", + "Win32_System_Diagnostics_Debug", + "Win32_System_Diagnostics_ToolHelp", + "Win32_System_Kernel", + "Win32_System_LibraryLoader", + "Win32_System_Memory", + "Win32_System_Performance", + "Win32_System_Threading", +] } + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Debugging switches (scheduled stack dumps and the like). +diagnostics = [] + +[lints] +workspace = true diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs new file mode 100644 index 000000000..3791b18f9 --- /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 (GTA VI 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<bool> = 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<usize> { + 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<Vec<std::mem::Discriminant<ConsoleOnly>>> = 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 000000000..08142f8b7 --- /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, <reg>; 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<u8>, 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<usize> { + 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, <reg> ([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 new file mode 100644 index 000000000..3f77a8846 --- /dev/null +++ b/crates/victory-loader/src/crash.rs @@ -0,0 +1,1000 @@ +//! Names the faulting code when title code crashes. +//! +//! A vectored handler sees every exception first, so it only prints the +//! kinds that end a process (access violations and the like, and +//! breakpoints: titles assert with `int3`, fatal without a debugger) as +//! first-chance, since a handler may still take them (ntdll's loader does +//! with its own probes). What nobody handles, of any kind (an uncaught C++ +//! exception too), is reported from the unhandled-exception filter +//! (`report_unhandled`, which the runtime calls ahead of the title's own) +//! and appended to the crash log, with the title's last debug output, which +//! often states the reason. Panics of ours go to the crash log too. + +use std::ptr::null_mut; +use windows_sys::Win32::Foundation::{ + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_ILLEGAL_INSTRUCTION, + EXCEPTION_INT_DIVIDE_BY_ZERO, EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE, +}; + +use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, M128A, RtlLookupFunctionEntry, + RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER, +}; +use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleFileNameW, GetModuleHandleExW, +}; +use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits; + +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; +/// Frames listed per report. +pub(crate) const MAX_FRAMES: usize = 40; + +/// Memory saved to files when a crash is reported: (address, length, file). +#[cfg(feature = "diagnostics")] +static SAVE: std::sync::OnceLock<Vec<(usize, usize, std::path::PathBuf)>> = + std::sync::OnceLock::new(); + +/// Debugging aid: on a reported crash, also write each `[address, address +/// + len)` (readable title memory, e.g. an engine table) to its file. +#[cfg(feature = "diagnostics")] +pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) { + let _ = SAVE.set(ranges); +} + +/// The file crash reports are appended to, besides being printed. +static LOG: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new(); + +/// Also appends every unhandled-exception report and panic to `file`, so a +/// crash can be read after the console is gone. +pub fn log_crashes_to(file: std::path::PathBuf) { + if LOG.set(file).is_ok() { + let print = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + print(info); + append_to_log(&format!( + "VIctory: panic on thread {:?}: {info}\n{}", + std::thread::current().name().unwrap_or("?"), + title_output() + )); + })); + } +} + +/// 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()); + eprint!("{text}"); + append_to_log(&text); +} + +fn append_to_log(text: &str) { + use std::io::Write; + let Some(file) = LOG.get() else { return }; + 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); + if let Ok(mut f) = opened { + let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id()); + } +} + +/// The title's last lines of debug output, kept for crash reports. +static SAID: std::sync::Mutex<std::collections::VecDeque<String>> = + std::sync::Mutex::new(std::collections::VecDeque::new()); +const SAID_LINES: usize = 8; + +/// Keeps a line of the title's debug output for the next crash report. +pub fn note_title_output(line: &str) { + if line.is_empty() { + return; + } + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if said.len() == SAID_LINES { + said.pop_front(); + } + said.push_back(line.to_owned()); +} + +/// The kept lines, one per report line; nothing if another thread holds +/// them (it may be the one that faulted). +fn title_output() -> String { + let Ok(said) = SAID.try_lock() else { + return String::new(); + }; + said.iter().map(|l| format!(" title said: {l}\n")).collect() +} + +/// Installs the handlers; call once before running title code. +pub fn report_crashes() { + unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched. + unsafe { report_unhandled(info) }; + EXCEPTION_CONTINUE_SEARCH + } + // SAFETY: registers handlers that only read the exception they are + // given; the title's own filter, once it sets one, takes the place of + // ours and calls `report_unhandled` first. + unsafe { + AddVectoredExceptionHandler(0, Some(handler)); + SetUnhandledExceptionFilter(Some(filter)); + } +} + +/// What the vectored handler reports as it happens. +const FATAL: [i32; 6] = [ + EXCEPTION_ACCESS_VIOLATION, + EXCEPTION_ILLEGAL_INSTRUCTION, + EXCEPTION_PRIV_INSTRUCTION, + EXCEPTION_INT_DIVIDE_BY_ZERO, + EXCEPTION_STACK_OVERFLOW, + EXCEPTION_BREAKPOINT, +]; + +/// Console CPUs are Zen 2: titles use AMD-only instructions Intel CPUs +/// lack. Does their job instead: `clzero` (`0f 01 fc`) zeroes the 64-byte +/// line at `rax`; `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so +/// a spin loop around them works with mwaitx as a yield. +unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { + // SAFETY: the system passes valid exception pointers; the faulting + // instruction's bytes are readable, as the CPU just fetched them. + unsafe { + let record = &*(*info).ExceptionRecord; + let context = &mut *(*info).ContextRecord; + if record.ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION { + return false; + } + let code = context.Rip as *const u8; + match code.cast::<[u8; 3]>().read_unaligned() { + [0x0f, 0x01, 0xfc] => ((context.Rax & !63) as *mut u8).write_bytes(0, 64), + [0x0f, 0x01, 0xfa] => {} + [0x0f, 0x01, 0xfb] => std::thread::yield_now(), + _ => { + // Only bytes inside the faulting instruction's page are read: the next page may + // not be mapped. + let room = 0x1000 - (context.Rip as usize & 0xfff); + let mut bytes = [0u8; 32]; + let n = room.min(bytes.len()); + std::ptr::copy_nonoverlapping(code, bytes.as_mut_ptr(), n); + if let Some(pass) = clwb_loop(&bytes[..n]) { + // A whole write-back loop in one exception (see `clwb_loop`). + let limit = *gpr(context, pass.limit); + let base = gpr(context, pass.base); + *base = if *base <= limit { + base.wrapping_add(((limit - *base) / 64 + 1) * 64) + } else { + base.wrapping_add(64) + }; + let flags = cmp_flags(*base, limit); + context.EFlags = context.EFlags & !CMP_FLAGS | flags; + context.Rip += pass.len as u64; + return true; + } + if n >= 15 + && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15])) + { + // A write-back hint: the PC's memory is coherent, so it has nothing to do. + context.Rip += len as u64; + return true; + } + let Some(len) = sse4a(code, &mut context.Anonymous.FltSave.XmmRegisters) else { + return false; + }; + context.Rip += len as u64; + return true; + } + } + context.Rip += 3; + } + true +} + +/// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before +/// Ice Lake lack: its length, or `None` for any other instruction. +fn clwb_len(code: [u8; 15]) -> Option<usize> { + let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 }; + if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae { + return None; + } + let modrm = code[at + 2]; + let (mode, rm) = (modrm >> 6, modrm & 7); + if mode == 3 || (modrm >> 3) & 7 != 6 { + return None; + } + let mut len = at + 3; + let mut base = rm; + if rm == 4 { + base = code[len] & 7; + len += 1; + } + len += match mode { + 0 if rm == 5 || (rm == 4 && base == 5) => 4, + 1 => 1, + 2 => 4, + _ => 0, + }; + Some(len) +} + +/// A `clwb` write-back loop as the title's compilers build it, one cache line a +/// pass (`base` and `limit` any registers): +/// +/// ```text +/// top: clwb [base] +/// add base, 0x40 +/// cmp base, limit +/// jbe top +/// ``` +/// +/// An exception costs about a microsecond and the title writes back whole +/// buffers this way while it loads, so the loop is done in one: `clwb` has +/// nothing to do on the PC, `base` ends past `limit` as the last pass leaves it. +struct ClwbLoop { + base: u8, + limit: u8, + /// Bytes from `clwb` to the instruction after `jbe`. + len: usize, +} + +fn clwb_loop(code: &[u8]) -> Option<ClwbLoop> { + // clwb [base]: 66 [40|41] 0f ae, ModRM mod 00, reg 6, no SIB or displacement. + let (rex, at) = match code.get(1)? { + 0x40 | 0x41 => (code[1], 2), + _ => (0, 1), + }; + if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] { + return None; + } + let modrm = *code.get(at + 2)?; + let rm = modrm & 7; + if modrm >> 6 != 0 || (modrm >> 3) & 7 != 6 || rm == 4 || rm == 5 { + return None; + } + let base = rm | (rex & 1) << 3; + // add base, 0x40: REX.W(+B) 83 /0 ib. + let add = at + 3; + if *code.get(add..add + 4)? != [0x48 | base >> 3, 0x83, 0xc0 | (base & 7), 0x40] { + return None; + } + // cmp base, limit: REX.W 39 /r with base in r/m. + let cmp = add + 4; + let &[cmp_rex @ 0x48..=0x4f, 0x39, cmp_modrm] = code.get(cmp..cmp + 3)? else { + return None; + }; + if cmp_modrm >> 6 != 3 || (cmp_modrm & 7 | (cmp_rex & 1) << 3) != base { + return None; + } + let limit = (cmp_modrm >> 3) & 7 | (cmp_rex & 4) << 1; + // jbe top. + let jump = cmp + 3; + let len = jump + 2; + if *code.get(jump)? != 0x76 || i64::from(*code.get(jump + 1)? as i8) != -(len as i64) { + return None; + } + (limit != base).then_some(ClwbLoop { base, limit, len }) +} + +/// The general register numbered `n` as instructions encode it. +fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 { + match n & 15 { + 0 => &mut context.Rax, + 1 => &mut context.Rcx, + 2 => &mut context.Rdx, + 3 => &mut context.Rbx, + 4 => &mut context.Rsp, + 5 => &mut context.Rbp, + 6 => &mut context.Rsi, + 7 => &mut context.Rdi, + 8 => &mut context.R8, + 9 => &mut context.R9, + 10 => &mut context.R10, + 11 => &mut context.R11, + 12 => &mut context.R12, + 13 => &mut context.R13, + 14 => &mut context.R14, + _ => &mut context.R15, + } +} + +/// The status flags `cmp a, b` leaves (CF, PF, AF, ZF, SF, OF) as `EFLAGS` bits. +fn cmp_flags(a: u64, b: u64) -> u32 { + let r = a.wrapping_sub(b); + u32::from(a < b) + | u32::from((r as u8).count_ones().is_multiple_of(2)) << 2 + | (((a ^ b ^ r) >> 4) as u32 & 1) << 4 + | u32::from(r == 0) << 6 + | ((r >> 63) as u32) << 7 + | ((((a ^ b) & (a ^ r)) >> 63) as u32) << 11 +} +const CMP_FLAGS: u32 = 0x8d5; + +/// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on +/// the saved XMM registers; returns the instruction's length. +unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> { + // SAFETY: the caller's code bytes are readable up to the instruction's end. + let b = |i: usize| unsafe { code.add(i).read() }; + let prefix = b(0); + let (rex, at) = if b(1) & 0xf0 == 0x40 { + (b(1), 2) + } else { + (0, 1) + }; + if !matches!(prefix, 0x66 | 0xf2) || b(at) != 0x0f || !matches!(b(at + 1), 0x78 | 0x79) { + return None; + } + let modrm = b(at + 2); + if modrm >> 6 != 3 { + return None; + } + let dst = usize::from((modrm >> 3) & 7 | (rex & 4) << 1); + let src = usize::from(modrm & 7 | (rex & 1) << 3); + let immediate = b(at + 1) == 0x78; + let (fields, len) = if immediate { + ((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 }; + ((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 }; + if prefix == 0x66 { + // extrq: register form takes its fields from src, works on dst. + if immediate && (modrm >> 3) & 7 != 0 { + return None; + } + let target = if immediate { src } else { dst }; + xmm[target].Low = (xmm[target].Low >> at_bit) & mask; + } else { + let value = (xmm[src].Low & mask) << at_bit; + xmm[dst].Low = xmm[dst].Low & !(mask << at_bit) | value; + } + Some(len) +} + +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 + } + // SAFETY: as above. + if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) { + // SAFETY: as above. + unsafe { report("first-chance exception", info, false) }; + } + EXCEPTION_CONTINUE_SEARCH +} + +/// For an unhandled-exception filter: reports the exception that is about +/// to end the process, and appends it to the crash log. +/// +/// # Safety +/// `info` comes from the system, for an exception being dispatched. +pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) { + // SAFETY: forwarded from the caller. + unsafe { report("unhandled exception", info, true) }; +} + +/// The bytes at `at` as hex, as many as the longest x86 instruction (15), +/// but none past the end of `at`'s page: the next page may not be mapped. +/// For an instruction the CPU refused, they name it (`0f 01 fd` is +/// `rdpru`), which the address alone does not. +/// +/// # Safety +/// `at`'s page is readable. +unsafe fn instruction_bytes(at: usize) -> String { + let n = (0x1000 - (at & 0xfff)).min(15); + // SAFETY: `n` bytes from `at` stay inside its page, which the caller + // says is readable. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, n) }; + let hex: Vec<_> = bytes.iter().map(|b| format!("{b:02x}")).collect(); + hex.join(" ") +} + +/// MSVC's code for a C++ `throw`, and its magic first parameter. +const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32; +const CPP_MAGIC: usize = 0x1993_0520; + +/// What a C++ throw threw: the decorated name of its type, then its value +/// where that names the cause (an integer, e.g. an HRESULT; a standard +/// exception's message). +/// +/// # Safety +/// `p` are the parameters of a live MSVC throw (`p[0]` the magic). +unsafe fn thrown(p: &[usize]) -> String { + // SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable + // type array at +12 (count, then type RVAs), each type's descriptor at + // +4, whose decorated name starts at +16; the object is at `p[1]`. + unsafe { + let rva = |at: usize| (at as *const u32).read_unaligned() as usize; + 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() + }; + let first = name(0); + let value = match &*first { + // int, unsigned, long (HRESULT), unsigned long + ".H" | ".I" | ".J" | ".K" if p[1] != 0 => { + format!(" = {:#010x}", (p[1] as *const u32).read_unaligned()) + } + // std::exception keeps its message after the table pointer. + _ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => { + let message = (p[1] as *const *const std::ffi::c_char).add(1).read(); + if message.is_null() { + String::new() + } else { + format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy()) + } + } + _ => String::new(), + }; + format!("{first}{value}") + } +} + +/// # Safety +/// See [`report_unhandled`]. +unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { + // SAFETY: the system passes valid exception pointers. + let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) }; + let code = record.ExceptionCode; + let at = record.ExceptionAddress as usize; + let p = record.ExceptionInformation; + let detail = if code == EXCEPTION_ACCESS_VIOLATION { + let kind = match p[0] { + 0 => "read", + 1 => "write", + _ => "execute", + }; + format!(" ({kind} {:#x}: {})", p[1], memory_at(p[1])) + } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC { + // SAFETY: a live MSVC throw. + format!(" (C++ {} thrown)", unsafe { thrown(&p) }) + } else if code == EXCEPTION_ILLEGAL_INSTRUCTION || code == EXCEPTION_PRIV_INSTRUCTION { + // SAFETY: the CPU refused the instruction at `at`, so it fetched it. + format!(" (code {})", unsafe { instruction_bytes(at) }) + } else { + String::new() + }; + // Printed line by line (a fault while unwinding must not lose the + // lines before it), and kept for the file. + let mut text = String::new(); + let mut line = |l: String| { + eprintln!("{l}"); + text.push_str(&l); + text.push('\n'); + }; + line(format!( + "VIctory: {what} {:#010x} at {}{detail}", + code as u32, + locate(at) + )); + line(format!( + " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}", + context.Rax, + context.Rbx, + context.Rcx, + context.Rdx, + context.Rsi, + context.Rdi, + context.Rsp, + context.Rbp + )); + line(format!( + " r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}", + context.R8, + context.R9, + context.R10, + context.R11, + context.R12, + context.R13, + context.R14, + context.R15 + )); + for (i, pc) in unwind(*context).into_iter().enumerate() { + line(format!(" #{i:<2} {}", locate(pc as usize))); + } + if to_file { + let said = title_output(); + eprint!("{said}"); + text.push_str(&said); + append_to_log(&text); + } + #[cfg(feature = "diagnostics")] + for (address, len, file) in SAVE.get().into_iter().flatten() { + // SAFETY: the caller of `save_on_crash` named readable memory. + let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) }; + let saved = std::fs::write(file, bytes); + eprintln!( + " saved {address:#x}+{len:#x} to {} ({saved:?})", + file.display() + ); + } +} + +/// Return addresses of the faulting thread's frames, from the faulting +/// instruction up, by the unwind data of each image (the Windows loader +/// registered it for title images too). Code without unwind data (our +/// thunks, leaf functions) is taken to have its return address at `rsp`. +fn unwind(context: CONTEXT) -> Vec<u64> { + let (mut low, mut high) = (0, 0); + // SAFETY: writes the current thread's stack bounds. + unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; + let mut frames = Vec::with_capacity(MAX_FRAMES); + unwind_into(context, low, high, &mut frames); + frames +} + +/// A `CONTEXT` at the 16-byte alignment the unwind and capture functions need. +#[repr(C, align(16))] +pub(crate) struct Aligned16(pub(crate) CONTEXT); + +/// [`unwind`] for any thread of the process, its stack being `low..high`; +/// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames` +/// has that capacity (another thread may be suspended holding the heap). +pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) { + // `RtlVirtualUnwind` writes the context with 16-byte aligned stores, and + // windows-sys declares `CONTEXT` without that alignment: a by-value copy on + // the stack can land 8 bytes off and fault (seen in a debug build). + let mut aligned = Aligned16(context); + let context = &mut aligned.0; + frames.push(context.Rip); + while frames.len() < MAX_FRAMES { + // Stop where reading the stack would fault inside this handler. + let rsp = context.Rsp as usize; + if rsp < low || rsp + 8 > high { + break; + } + let mut image = 0; + // SAFETY: looks up the function table entry covering `Rip`, if any. + let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) }; + if entry.is_null() { + // SAFETY: `rsp` is inside this thread's stack. + context.Rip = unsafe { (rsp as *const u64).read() }; + context.Rsp += 8; + } else { + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is our copy. + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + &mut data, + &mut frame, + null_mut(), + ) + }; + } + if context.Rip == 0 { + break; + } + frames.push(context.Rip); + } +} + +/// `module+rva`, or the bare address. +pub fn locate(address: usize) -> String { + module_of(address).unwrap_or_else(|| format!("{address:#x}")) +} + +fn module_of(address: usize) -> Option<String> { + let mut module: HMODULE = std::ptr::null_mut(); + // SAFETY: looks up the module containing `address`; no reference taken. + let found = unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + address as *const u16, + &mut module, + ) + }; + if found == 0 { + return None; + } + let mut path = [0u16; 260]; + // SAFETY: `module` is a loaded module; the buffer length is passed. + let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) }; + let path = String::from_utf16_lossy(&path[..len as usize]); + let name = path.rsplit('\\').next().unwrap_or(&path); + Some(format!("{name}+{:#x}", address - module as usize)) +} + +/// What is at `address`, for an access violation there: nothing, memory +/// reserved but never committed, a guard page, or the protection the access +/// broke (with the module, for an image's pages). Each points at a different +/// cause: a wild pointer, an allocation whose commit failed, a stack +/// overrun, a write to code or constants. +fn memory_at(address: usize) -> String { + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_IMAGE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE, + PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, + PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, VirtualQuery, + }; + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: reads the address space's bookkeeping, not `address` itself. + let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + // Above the process's address space: Windows reports a + // non-canonical address as all ones. + return "outside the address space".into(); + } + let protect = match info.State { + MEM_FREE => return "nothing mapped there".into(), + MEM_RESERVE => return "reserved, never committed".into(), + _ if info.Protect & PAGE_GUARD != 0 => return "a guard page".into(), + _ => match info.Protect & 0xff { + PAGE_NOACCESS => "no access".into(), + PAGE_READONLY => "read-only".into(), + PAGE_READWRITE => "read-write".into(), + PAGE_WRITECOPY => "copy-on-write".into(), + PAGE_EXECUTE => "execute-only".into(), + PAGE_EXECUTE_READ => "read-execute".into(), + PAGE_EXECUTE_READWRITE => "read-write-execute".into(), + PAGE_EXECUTE_WRITECOPY => "copy-on-write, executable".into(), + _ => format!("protection {:#x}", info.Protect), + }, + }; + match module_of(address) { + Some(module) if info.Type == MEM_IMAGE => format!("{protect}, in {module}"), + _ => protect, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Diagnostics::Debug::{ + EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace, + }; + + #[test] + #[inline(never)] + fn unwinds_like_the_system_walk() { + // SAFETY: zeroed CONTEXT is valid; both calls write our buffers. + let (frames, walked) = unsafe { + // `RtlCaptureContext` wants it 16-byte aligned too. + let mut context = Aligned16(std::mem::zeroed()); + RtlCaptureContext(&mut context.0); + let mut walked = [null_mut(); 8]; + let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut()); + (unwind(context.0), walked[..usize::from(n)].to_vec()) + }; + // Frame 0 differs (two call sites in this function); callers agree. + assert!(walked.len() >= 4, "{walked:?}"); + let ours: Vec<_> = frames[1..walked.len()] + .iter() + .map(|&f| f as usize) + .collect(); + let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect(); + assert_eq!(ours, system); + } + + #[test] + fn memory_at_names_what_an_access_hit() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, + PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + // SAFETY: reserves four pages of ours and commits three of them; + // nothing reads or writes them. + let base = unsafe { + let base = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS); + assert!(!base.is_null()); + let page = |i: usize, protect| { + let at = base.cast::<u8>().add(i * 0x1000).cast(); + assert!(!VirtualAlloc(at, 0x1000, MEM_COMMIT, protect).is_null()); + }; + page(1, PAGE_READONLY); + page(2, PAGE_READWRITE | PAGE_GUARD); + page(3, PAGE_NOACCESS); + base as usize + }; + assert_eq!(memory_at(base + 8), "reserved, never committed"); + assert_eq!(memory_at(base + 0x1008), "read-only"); + assert_eq!(memory_at(base + 0x2008), "a guard page"); + assert_eq!(memory_at(base + 0x3008), "no access"); + // SAFETY: releases the reservation made above. + unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; + assert_eq!(memory_at(base + 8), "nothing mapped there"); + assert_eq!(memory_at(0), "nothing mapped there"); + assert_eq!(memory_at(usize::MAX), "outside the address space"); + // This test's own code: an image page, named by its module. + let code = memory_at(memory_at_names_what_an_access_hit as *const () as usize); + let named = code.starts_with("read-execute, in victory_loader-"); + assert!(named, "{code}"); + } + + /// On an Intel CPU, the real instructions go through the vectored + /// handler. On an AMD CPU they run natively, and the tests below test + /// the emulation. + #[test] + fn clwb_loops() { + // clwb [rcx]; add rcx, 0x40; cmp rcx, rax; jbe top + let a = clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf3, + ]) + .expect("rcx loop"); + assert_eq!((a.base, a.limit, a.len), (1, 0, 13)); + // clwb [r9]; add r9, 0x40; cmp r9, rax; jbe top + let b = clwb_loop(&[ + 0x66, 0x41, 0x0f, 0xae, 0x31, 0x49, 0x83, 0xc1, 0x40, 0x49, 0x39, 0xc1, 0x76, 0xf2, + ]) + .expect("r9 loop"); + assert_eq!((b.base, b.limit, b.len), (9, 0, 14)); + // A different stride, a jump elsewhere, or a cut-off loop is not one. + assert!( + clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x20, 0x48, 0x39, 0xc1, 0x76, 0xf3 + ]) + .is_none() + ); + assert!( + clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf0 + ]) + .is_none() + ); + assert!(clwb_loop(&[0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40]).is_none()); + // The flags the last cmp leaves: base just past limit. + assert_eq!(cmp_flags(0x1040, 0x1000) & 0x41, 0); // CF and ZF clear: the loop ends + assert_eq!(cmp_flags(0x1000, 0x1000) & 0x40, 0x40); + } + + #[test] + fn clwb_lengths() { + let pad = |b: &[u8]| { + let mut c = [0u8; 15]; + c[..b.len()].copy_from_slice(b); + c + }; + assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), + Some(8) + ); // [rax+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), + Some(8) + ); // [rip+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7 + assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66 + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form + } + + #[test] + fn clzero_zeroes_its_line_on_any_cpu() { + report_crashes(); + #[repr(align(64))] + struct Line([u8; 128]); + let mut line = Line([0xff; 128]); + let at = line.0.as_mut_ptr().wrapping_add(5); // inside the first line + // SAFETY: clzero writes only the 64-byte line holding `at`, ours. + unsafe { std::arch::asm!(".byte 0x0f, 0x01, 0xfc", in("rax") at) }; + assert!(line.0[..64].iter().all(|&b| b == 0)); + assert!(line.0[64..].iter().all(|&b| b == 0xff)); + // insertq xmm0, xmm1, len 16, at 16; then extrq xmm0, len 8, at 20. + let out: u64; + // SAFETY: touches only the named registers. + unsafe { + std::arch::asm!( + "movq xmm0, {a}", "movq xmm1, {b}", + ".byte 0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10", + "movq {a}, xmm0", + ".byte 0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14", + "movq {b}, xmm0", + a = inout(reg) 0x1111_2222_3333_4444u64 => _, b = inout(reg) 0xabcdu64 => out, + out("xmm0") _, out("xmm1") _) + }; + assert_eq!(out, 0xbc); // 0x1111_2222_abcd_4444 >> 20, 8 bits + // SAFETY: monitorx/mwaitx are wait hints that write no memory. + unsafe { + std::arch::asm!(".byte 0x0f, 0x01, 0xfa", ".byte 0x0f, 0x01, 0xfb", + in("rax") at, in("ecx") 0, in("edx") 0) + }; + } + + fn reg(low: u64, high: u64) -> M128A { + M128A { + Low: low, + High: high as i64, + } + } + + /// Gives `code` to the emulation as if it faulted with `exception` at + /// its first byte, with `rax` and `xmm` as the saved registers. The + /// emulation does not execute `code`, so this works on any CPU. Returns + /// the number of bytes that the emulation skipped, or `None` if it did + /// not emulate the instruction. `xmm` gets the saved registers after. + fn emulate_as(exception: i32, code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> { + // `int3` after the instruction, so that a decoder that reads too + // far sees no valid bytes. + let mut bytes = [0xcc_u8; 16]; + bytes[..code.len()].copy_from_slice(code); + let start = bytes.as_ptr() as u64; + // SAFETY: a zeroed record and context are valid; the emulation + // reads only `bytes` and writes only `context` (and memory at + // `rax` for clzero, which the caller owns). + unsafe { + let mut record: EXCEPTION_RECORD = std::mem::zeroed(); + record.ExceptionCode = exception; + let mut context: CONTEXT = std::mem::zeroed(); + context.Rip = start; + context.Rax = rax; + context.Anonymous.FltSave.XmmRegisters = *xmm; + let mut pointers = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: &mut context, + }; + let emulated = emulate_amd_only(&mut pointers); + *xmm = context.Anonymous.FltSave.XmmRegisters; + emulated.then(|| context.Rip - start) + } + } + + fn emulate(code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option<u64> { + emulate_as(EXCEPTION_ILLEGAL_INSTRUCTION, code, rax, xmm) + } + + fn low(xmm: &[M128A; 16], i: usize) -> u64 { + xmm[i].Low + } + + #[test] + fn emulated_clzero_zeroes_its_line() { + #[repr(align(64))] + struct Line([u8; 128]); + let mut line = Line([0xff; 128]); + let at = line.0.as_mut_ptr().wrapping_add(5) as u64; // inside the first line + let mut xmm = [reg(0, 0); 16]; + assert_eq!(emulate(&[0x0f, 0x01, 0xfc], at, &mut xmm), Some(3)); + assert!(line.0[..64].iter().all(|&b| b == 0)); + assert!(line.0[64..].iter().all(|&b| b == 0xff)); + } + + #[test] + fn emulated_monitorx_and_mwaitx_are_skipped() { + let mut xmm = [reg(1, 2); 16]; + assert_eq!(emulate(&[0x0f, 0x01, 0xfa], 0, &mut xmm), Some(3)); + assert_eq!(emulate(&[0x0f, 0x01, 0xfb], 0, &mut xmm), Some(3)); + assert!(xmm.iter().all(|r| r.Low == 1 && r.High == 2)); + } + + #[test] + fn emulated_insertq_and_extrq_with_immediates() { + let mut xmm = [reg(0, 0); 16]; + xmm[0] = reg(0x1111_2222_3333_4444, 0x5555); + xmm[1] = reg(0xabcd, 0x6666); + // insertq xmm0, xmm1, length 16, index 16 + let insertq = [0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10]; + assert_eq!(emulate(&insertq, 0, &mut xmm), Some(6)); + assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444); + assert_eq!((low(&xmm, 1), xmm[1].High), (0xabcd, 0x6666)); + // extrq xmm0, length 8, index 20 + let extrq = [0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14]; + assert_eq!(emulate(&extrq, 0, &mut xmm), Some(6)); + assert_eq!(low(&xmm, 0), 0xbc); + } + + #[test] + fn emulated_insertq_and_extrq_with_fields_in_a_register() { + let mut xmm = [reg(0, 0); 16]; + // insertq xmm0, xmm1: length and index in xmm1's high half. + xmm[0] = reg(0x1111_2222_3333_4444, 0); + xmm[1] = reg(0xabcd, 0x10_10); + assert_eq!(emulate(&[0xf2, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4)); + assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444); + // extrq xmm0, xmm1: length and index in xmm1's low half. + xmm[1] = reg(0x14_08, 0); + assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4)); + assert_eq!(low(&xmm, 0), 0xbc); + } + + #[test] + fn emulated_sse4a_reaches_xmm8_to_xmm15() { + let mut xmm = [reg(0, 0); 16]; + xmm[8] = reg(0x1111_2222_3333_4444, 0); + xmm[9] = reg(0xabcd, 0); + // insertq xmm8, xmm9, length 16, index 16 (REX.R and REX.B) + let insertq = [0xf2, 0x45, 0x0f, 0x78, 0xc1, 0x10, 0x10]; + assert_eq!(emulate(&insertq, 0, &mut xmm), Some(7)); + assert_eq!(low(&xmm, 8), 0x1111_2222_abcd_4444); + assert_eq!((low(&xmm, 0), low(&xmm, 1)), (0, 0)); + // extrq xmm9, length 8, index 4 (REX.B) + let extrq = [0x66, 0x41, 0x0f, 0x78, 0xc1, 0x08, 0x04]; + assert_eq!(emulate(&extrq, 0, &mut xmm), Some(7)); + assert_eq!(low(&xmm, 9), 0xbc); + assert_eq!(low(&xmm, 1), 0); + } + + #[test] + fn emulated_sse4a_length_0_is_64_bits() { + let mut xmm = [reg(0, 0); 16]; + xmm[0] = reg(0x1122_3344_5566_7788, 0); + // extrq xmm0, length 0 (64), index 0. A non-zero index with + // length 64 goes past bit 63, and AMD leaves that result undefined. + assert_eq!( + emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x00], 0, &mut xmm), + Some(6) + ); + assert_eq!(low(&xmm, 0), 0x1122_3344_5566_7788); + // insertq xmm0, xmm1, length 0 (64), index 0 + xmm[1] = reg(0xdead_beef_cafe_f00d, 0); + assert_eq!( + emulate(&[0xf2, 0x0f, 0x78, 0xc1, 0x00, 0x00], 0, &mut xmm), + Some(6) + ); + assert_eq!(low(&xmm, 0), 0xdead_beef_cafe_f00d); + } + + #[test] + fn other_instructions_and_exceptions_are_not_emulated() { + let mut xmm = [reg(0, 0); 16]; + assert_eq!(emulate(&[0x0f, 0x0b], 0, &mut xmm), None); // ud2 + // extrq with a memory operand, which does not exist + assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0x00], 0, &mut xmm), None); + // extrq with immediates needs ModRM.reg 0 + let bad_extrq = [0x66, 0x0f, 0x78, 0xc8, 0x08, 0x14]; + assert_eq!(emulate(&bad_extrq, 0, &mut xmm), None); + // a clzero that did not cause an illegal instruction + let clzero = [0x0f, 0x01, 0xfc]; + assert_eq!( + emulate_as(EXCEPTION_ACCESS_VIOLATION, &clzero, 0, &mut xmm), + None + ); + } + + #[test] + fn instruction_bytes_stop_at_the_end_of_their_page() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, + VirtualFree, VirtualProtect, + }; + // rdpru, then the next instruction (mov rcx, rax) and padding. + let mut code = [0x90_u8; 16]; + code[..6].copy_from_slice(&[0x0f, 0x01, 0xfd, 0x48, 0x89, 0xc1]); + // SAFETY: two fresh pages of ours, the second made unreadable, so a + // read past the end of the first faults. + unsafe { + let page = VirtualAlloc( + std::ptr::null(), + 0x2000, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + .cast::<u8>(); + assert!(!page.is_null()); + let mut old = 0; + let guard = page.add(0x1000).cast(); + assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0); + page.copy_from_nonoverlapping(code.as_ptr(), code.len()); + let whole = "0f 01 fd 48 89 c1 90 90 90 90 90 90 90 90 90"; + assert_eq!(instruction_bytes(page as usize), whole); + // The page's last three bytes: rdpru, and nothing read after it. + let end = page.add(0x1000 - 3); + end.copy_from_nonoverlapping(code.as_ptr(), 3); + assert_eq!(instruction_bytes(end as usize), "0f 01 fd"); + VirtualFree(page.cast(), 0, MEM_RELEASE); + } + } +} diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs new file mode 100644 index 000000000..28cabd639 --- /dev/null +++ b/crates/victory-loader/src/lib.rs @@ -0,0 +1,62 @@ +//! Runs a title's original x86-64 code natively, inside our process. +//! +//! Xbox Series X|S executables are x86-64 PE32+ images built for a Zen 2 +//! CPU, so the machine code needs no translation. What differs is the +//! platform underneath, so the loader's job is to: +//! +//! 1. [`prepare()`] a lightly patched copy of the image (pure, portable): mark +//! it as a DLL, remove its entry point and import directory, and detach +//! its TLS callbacks, so the Windows loader maps it, relocates it, +//! allocates its static TLS and registers its unwind tables, but runs +//! none of its code and resolves none of its imports; +//! 2. load that copy as a real module (debuggers, profilers, crash dumps +//! and stack walks all see it); this step is Windows-only; +//! 3. map the DLLs the title ships beside it the same way +//! (`load_title_dlls`); +//! 4. bind every import ourselves through an [`ImportResolver`], our +//! runtime (`victory-hle`), the host or the title's DLLs, and route +//! anything unresolved to a generated stub that reports exactly what +//! was called; +//! 5. initialise the title's DLLs, then run TLS callbacks and the entry +//! 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; +mod crash; +pub mod prepare; +pub mod resolve; +#[cfg(all(windows, feature = "diagnostics"))] +mod stacks; +#[cfg(windows)] +mod threads; +#[cfg(windows)] +mod thunks; +#[cfg(windows)] +mod tls; +#[cfg(windows)] +mod windows; + +#[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"))] +pub use stacks::{dump_stacks, dump_stacks_on_schedule}; +#[cfg(windows)] +pub use threads::disable_thread_calls; +#[cfg(windows)] +pub use thunks::{UnimplementedPolicy, unimplemented_call_count}; +#[cfg(windows)] +pub use windows::{ + BindReport, LoadedImage, MissingImport, WithTitleDlls, load, load_title_dll, load_title_dlls, +}; + +/// `DLL_PROCESS_ATTACH`, for TLS callbacks. +pub const DLL_PROCESS_ATTACH: u32 = 1; +/// `DLL_PROCESS_DETACH`. +pub const DLL_PROCESS_DETACH: u32 = 0; diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs new file mode 100644 index 000000000..c8935081b --- /dev/null +++ b/crates/victory-loader/src/prepare.rs @@ -0,0 +1,283 @@ +//! 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 victory_pe::layout::{self, dir, dll_flags, file_flags}; +use victory_pe::{ImageInfo, PeError}; + +#[derive(Debug, thiserror::Error)] +pub enum PrepareError { + #[error(transparent)] + Pe(#[from] PeError), + #[error("cannot patch image: {0}")] + Patch(&'static str), +} + +/// A patched copy of an image plus everything we need from the original. +#[derive(Debug, Clone)] +pub struct PreparedImage { + /// Parsed from the *original* bytes: imports, TLS callbacks and entry + /// point as the title expects them. + pub info: ImageInfo, + /// The patched bytes to hand to the Windows loader. + pub bytes: Vec<u8>, + /// BLAKE3 of the original bytes: identifies the exact build. + pub original_hash: blake3::Hash, +} + +impl PreparedImage { + /// File name for the patched copy, unique per original build. + pub fn file_name(&self) -> String { + format!("victory-image-{}.dll", &self.original_hash.to_hex()[..16]) + } +} + +/// Produces the patched copy. The changes are: +/// +/// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL +/// and calls nothing; +/// * import directory points to its empty terminator and the bound-import +/// directory is cleared: we bind the original slots using `info.imports`; +/// * TLS callback pointer cleared: the OS still allocates static TLS for +/// the image, but callbacks only run when we call them (after binding); +/// its base relocation is made a no-op so the 0 survives a rebase; +/// * `FORCE_INTEGRITY` cleared, checksum zeroed: the copy is unsigned. +pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> { + let info = ImageInfo::parse(original)?; + let mut bytes = original.to_vec(); + + let fh = layout::file_header_offset(&bytes).ok_or(PrepareError::Patch("no file header"))?; + let opt = + layout::optional_header_offset(&bytes).ok_or(PrepareError::Patch("no optional header"))?; + + let characteristics = info.characteristics | file_flags::DLL; + write_u16( + &mut bytes, + fh + layout::FILE_HEADER_CHARACTERISTICS, + characteristics, + )?; + write_u32(&mut bytes, opt + layout::OPT_ADDRESS_OF_ENTRY_POINT, 0)?; + write_u32(&mut bytes, opt + layout::OPT_CHECKSUM, 0)?; + let dll_characteristics = info.dll_characteristics & !dll_flags::FORCE_INTEGRITY; + write_u16( + &mut bytes, + opt + layout::OPT_DLL_CHARACTERISTICS, + dll_characteristics, + )?; + + // Windows 10 assigns static TLS to the prepared DLL when its empty + // import table is present. The parser has already walked one descriptor + // per module up to the null terminator, regardless of the recorded Size. + if let Some(at) = layout::data_directory_offset(&bytes, dir::IMPORT) { + let rva = layout::read_u32(&bytes, at).ok_or(PrepareError::Patch("no import RVA"))?; + if rva != 0 { + let terminator = u32::try_from(info.imports.len()) + .ok() + .and_then(|count| count.checked_mul(IMPORT_DESCRIPTOR_SIZE)) + .and_then(|offset| rva.checked_add(offset)) + .ok_or(PrepareError::Patch("import terminator RVA overflow"))?; + write_u32(&mut bytes, at, terminator)?; + write_u32(&mut bytes, at + 4, IMPORT_DESCRIPTOR_SIZE)?; + } + } + if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) { + write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?; + } + + if let Some(tls) = &info.tls + && tls.callbacks_va != 0 + { + let at = info + .rva_to_file_offset(tls.directory_rva) + .ok_or(PrepareError::Patch("TLS directory is not file-backed"))?; + write_u64( + &mut bytes, + at as usize + layout::TLS64_ADDRESS_OF_CALLBACKS, + 0, + )?; + // The field's base relocation would turn the 0 into `delta` whenever + // the loader maps the copy away from its preferred base (Wine always + // does for DYNAMIC_BASE images), and the loader then reads callbacks + // from there. Make that entry a no-op. + let field_rva = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32; + for (entry, target) in dir64_relocations(&bytes, &info) { + if target == field_rva { + write_u16(&mut bytes, entry, 0)?; // IMAGE_REL_BASED_ABSOLUTE + } + } + } + + Ok(PreparedImage { + info, + bytes, + original_hash: blake3::hash(original), + }) +} + +/// Size of an IMAGE_IMPORT_DESCRIPTOR in the PE file. +const IMPORT_DESCRIPTOR_SIZE: u32 = 20; + +/// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry, +/// RVA it patches). Empty if the image has no readable relocation table. +fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { + const DIR64: u16 = 10; + let mut out = Vec::new(); + let Some(d) = layout::data_directory_offset(bytes, dir::BASERELOC) else { + return out; + }; + let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d + 4)) + else { + return out; + }; + let Some(start) = info.rva_to_file_offset(rva).filter(|_| size != 0) else { + return out; + }; + let (mut at, end) = (start as usize, start as usize + size as usize); + while at + 8 <= end { + let (Some(page), Some(block)) = + (layout::read_u32(bytes, at), layout::read_u32(bytes, at + 4)) + else { + break; + }; + let block = block as usize; + if block < 8 || at + block > end { + break; + } + for entry in (at + 8..at + block).step_by(2) { + let Some(e) = bytes.get(entry..entry + 2) else { + break; + }; + let e = u16::from_le_bytes([e[0], e[1]]); + if e >> 12 == DIR64 { + out.push((entry, page + u32::from(e & 0xFFF))); + } + } + at += block; + } + out +} + +fn write_u16(bytes: &mut [u8], at: usize, v: u16) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write_u32(bytes: &mut [u8], at: usize, v: u32) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write_u64(bytes: &mut [u8], at: usize, v: u64) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { + bytes + .get_mut(at..at + v.len()) + .ok_or(PrepareError::Patch("header field outside of file"))? + .copy_from_slice(v); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn patches_own_test_binary() { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let prepared = prepare(&original).unwrap(); + assert!(!prepared.info.is_dll(), "info describes the original"); + assert!(prepared.info.import_count() > 0); + + let patched = ImageInfo::parse(&prepared.bytes).unwrap(); + assert!(patched.is_dll()); + assert_eq!(patched.entry_rva, 0); + assert!(patched.imports.is_empty()); + assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0); + if let Some(tls) = &patched.tls { + assert_eq!(tls.callbacks_va, 0); + let field = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32; + assert!( + dir64_relocations(&prepared.bytes, &patched) + .iter() + .all(|&(_, target)| target != field), + "the cleared callback pointer must not be relocated" + ); + } + // Nothing else moved: same sections, same size. + assert_eq!(patched.sections.len(), prepared.info.sections.len()); + assert_eq!(prepared.bytes.len(), original.len()); + } + + #[test] + 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(); + let directory = layout::data_directory_offset(&original, dir::IMPORT).unwrap(); + // This linker layout counts the descriptors for real modules only. + let descriptor_bytes = u32::try_from(info.imports.len()).unwrap() * IMPORT_DESCRIPTOR_SIZE; + write_u32(&mut original, directory + 4, descriptor_bytes).unwrap(); + let prepared = prepare(&original).unwrap(); + let empty = layout::read_u32(&prepared.bytes, directory).unwrap(); + assert_eq!( + empty, + layout::read_u32(&original, directory).unwrap() + descriptor_bytes + ); + assert_eq!( + layout::read_u32(&prepared.bytes, directory + 4), + Some(IMPORT_DESCRIPTOR_SIZE) + ); + let at = info.rva_to_file_offset(empty).unwrap() as usize; + assert_eq!( + &prepared.bytes[at..at + IMPORT_DESCRIPTOR_SIZE as usize], + &[0; 20] + ); + let iat = layout::data_directory_offset(&original, dir::IAT).unwrap(); + assert_eq!( + &prepared.bytes[iat..iat + layout::DATA_DIRECTORY_SIZE], + &original[iat..iat + layout::DATA_DIRECTORY_SIZE] + ); + assert_eq!(prepared.info.import_count(), info.import_count()); + for module in &prepared.info.imports { + for entry in &module.entries { + let at = info.rva_to_file_offset(entry.iat_slot_rva).unwrap() as usize; + assert_eq!(&prepared.bytes[at..at + 8], &original[at..at + 8]); + } + } + } + + #[cfg(windows)] + #[test] + fn windows_assigns_static_tls_to_a_prepared_dll() { + // Model a title DLL using our own linked image. Loading a DLL leaves + // its assigned index intact; the executable-specific redirect resets it. + let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let flags = + layout::file_header_offset(&original).unwrap() + layout::FILE_HEADER_CHARACTERISTICS; + let characteristics = + ImageInfo::parse(&original).unwrap().characteristics | file_flags::DLL; + write_u16(&mut original, flags, characteristics).unwrap(); + let prepared = prepare(&original).unwrap(); + let info = &prepared.info; + let tls = info.tls.as_ref().expect("the test binary uses static TLS"); + let directory = info.rva_to_file_offset(tls.directory_rva).unwrap() as usize; + let index_va = layout::read_u64(&original, directory + 16).unwrap(); + let index_rva = index_va.checked_sub(info.image_base).unwrap(); + assert!(index_rva + 4 <= u64::from(info.size_of_image)); + + let folder = tempfile::tempdir().unwrap(); + let image = crate::load(&prepared, folder.path()).unwrap(); + // SAFETY: the mapped test image contains the checked DWORD above. + let assigned = + unsafe { ((image.base() + index_rva as usize) as *const u32).read_unaligned() }; + // SAFETY: the prepared DLL has never been attached or given to a caller. + unsafe { image.unload() }; + assert_ne!( + assigned, 0, + "the process executable already owns TLS slot zero" + ); + } + + #[test] + fn file_name_is_stable_per_build() { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let a = prepare(&original).unwrap(); + let b = prepare(&original).unwrap(); + assert_eq!(a.file_name(), b.file_name()); + } +} diff --git a/crates/victory-loader/src/resolve.rs b/crates/victory-loader/src/resolve.rs new file mode 100644 index 000000000..2da129176 --- /dev/null +++ b/crates/victory-loader/src/resolve.rs @@ -0,0 +1,33 @@ +//! How imports get their addresses. + +use victory_pe::ImportSymbol; + +/// Who provides a bound import. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Provenance { + /// Our implementation of the console API. + Hle, + /// The host's own implementation (e.g. Windows API sets that behave the + /// same on console and PC). + Host, + /// A DLL the title ships, mapped like the executable. + Title, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Resolution { + Found { + address: usize, + provenance: Provenance, + }, + /// Nobody implements it; the loader installs a reporting stub. + Missing, +} + +/// Supplies an address for each `dll!symbol` the title imports. +/// +/// `dll` is passed exactly as written in the image; implementations should +/// compare case-insensitively. +pub trait ImportResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution; +} diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs new file mode 100644 index 000000000..1d309109c --- /dev/null +++ b/crates/victory-loader/src/stacks.rs @@ -0,0 +1,224 @@ +//! Where every thread is: `VICTORY_STACKS=<seconds>[,<seconds>...]` prints +//! each thread's unwound stack as `module+rva` that many seconds after +//! [`dump_stacks_on_schedule`], to find what a title waits on. + +use std::ffi::c_void; + +use windows_sys::Wdk::System::Threading::{ + NtQueryInformationThread, ThreadBasicInformation, ThreadQuerySetWin32StartAddress, +}; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, +}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, +}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread, + SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, +}; + +use crate::crash::{MAX_FRAMES, locate, unwind_into}; + +/// Reads `VICTORY_STACKS` and, if set, starts a thread that prints every +/// thread's stack at each listed time (seconds from now). +pub fn dump_stacks_on_schedule() { + let Ok(list) = std::env::var("VICTORY_STACKS") else { + return; + }; + let mut times: Vec<f64> = 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 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(); + } + }); +} + +/// `THREAD_BASIC_INFORMATION` (ntddk). +#[repr(C)] +struct BasicInfo { + exit_status: i32, + teb: *const usize, + client_id: [usize; 2], + affinity: usize, + priority: i32, + base_priority: i32, +} + +/// `GetThreadContext` wants a 16-byte aligned context. +#[repr(C, align(16))] +struct Aligned(CONTEXT); + +/// Prints every other thread's stack to stderr. Each thread is suspended +/// only while its context is read and unwound into a buffer allocated +/// beforehand (it may hold the heap lock). +pub fn dump_stacks() { + // SAFETY: plain queries and a snapshot of this process's threads. + let (me, process, snapshot) = unsafe { + ( + GetCurrentThreadId(), + GetCurrentProcessId(), + CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), + ) + }; + if snapshot == INVALID_HANDLE_VALUE { + return; + } + let mut ids = Vec::new(); + // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use. + let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() }; + entry.dwSize = size_of::<THREADENTRY32>() as u32; + // SAFETY: `snapshot` is open; `entry` is sized. + let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0; + while more { + if entry.th32OwnerProcessID == process && entry.th32ThreadID != me { + ids.push(entry.th32ThreadID); + } + // SAFETY: as above. + more = unsafe { Thread32Next(snapshot, &mut entry) } != 0; + } + // SAFETY: we opened it. + unsafe { CloseHandle(snapshot) }; + eprintln!("VIctory: stacks of {} threads", ids.len()); + for id in ids { + // SAFETY: opens a thread of our own process. + let thread = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + }; + if thread.is_null() { + continue; + } + let (frames, (priority, base)) = frames_of(thread); + eprintln!( + " thread {id} \"{}\" start {} priority {priority} (base {base})", + name_of(thread), + locate(start_of(thread)) + ); + for (i, pc) in frames.into_iter().enumerate() { + eprintln!(" #{i:<2} {}", locate(pc as usize)); + } + // SAFETY: we opened it. + unsafe { CloseHandle(thread) }; + } +} + +/// The thread's frames and its current and base scheduling priority (0-31). +fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32)) { + let mut frames = Vec::with_capacity(MAX_FRAMES); + let mut info: BasicInfo = BasicInfo { + exit_status: 0, + teb: std::ptr::null(), + client_id: [0; 2], + affinity: 0, + priority: 0, + base_priority: 0, + }; + // SAFETY: writes `info`, whose layout and size are the system's. + let status = unsafe { + NtQueryInformationThread( + thread, + ThreadBasicInformation, + (&raw mut info).cast(), + size_of::<BasicInfo>() as u32, + std::ptr::null_mut(), + ) + }; + if status != 0 || info.teb.is_null() { + return (frames, (0, 0)); + } + // SAFETY: the TEB of a live thread of this process: its NT_TIB holds + // the stack base at +8 and the stack limit at +0x10. + let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) }; + // SAFETY: zeroed is a valid CONTEXT. + let mut context = Aligned(unsafe { std::mem::zeroed() }); + context.0.ContextFlags = CONTEXT_FULL_AMD64; + // SAFETY: suspends, reads and resumes a thread that is not this one; + // nothing between suspend and resume allocates or takes a lock the + // thread could hold besides the unwinder's own. + unsafe { + if SuspendThread(thread) == u32::MAX { + return (frames, (info.priority, info.base_priority)); + } + if GetThreadContext(thread, &mut context.0) != 0 { + unwind_into(context.0, low, high, &mut frames); + } + ResumeThread(thread); + } + (frames, (info.priority, info.base_priority)) +} + +fn start_of(thread: HANDLE) -> usize { + let mut start = 0usize; + // SAFETY: writes one pointer-sized start address. + unsafe { + NtQueryInformationThread( + thread, + ThreadQuerySetWin32StartAddress, + (&raw mut start).cast(), + size_of::<usize>() as u32, + std::ptr::null_mut(), + ) + }; + start +} + +fn name_of(thread: HANDLE) -> String { + let mut name = std::ptr::null_mut(); + // SAFETY: the system allocates the string; we free it with LocalFree. + unsafe { + if GetThreadDescription(thread, &mut name) < 0 || name.is_null() { + return String::new(); + } + let len = (0..).take_while(|&i| *name.add(i) != 0).count(); + let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len)); + LocalFree(name.cast::<c_void>()); + text + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn another_threads_stack_unwinds_to_its_start() { + let (tx, rx) = std::sync::mpsc::channel(); + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let parked = std::thread::spawn(move || { + // SAFETY: plain query. + tx.send(unsafe { GetCurrentThreadId() }).unwrap(); + stop_rx.recv().ok(); + }); + let id = rx.recv().unwrap(); + // SAFETY: a thread of this process. + let thread = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + }; + assert!(!thread.is_null()); + let (frames, _) = frames_of(thread); + // Waiting in the kernel, several frames down from the thread start. + assert!(frames.len() >= 3, "{frames:?}"); + assert!(start_of(thread) != 0); + // SAFETY: opened above. + unsafe { CloseHandle(thread) }; + dump_stacks(); + stop_tx.send(()).unwrap(); + parked.join().unwrap(); + } +} diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs new file mode 100644 index 000000000..903aebd4c --- /dev/null +++ b/crates/victory-loader/src/threads.rs @@ -0,0 +1,439 @@ +//! Thread notices for title images. The prepared copies have no entry point +//! and no TLS callbacks, so the Windows loader tells them nothing when a +//! thread starts or ends. Our own TLS callback, which Windows calls on every +//! thread of the process whoever created it (title, host CRT or our +//! runtime), passes each notice on to every attached image: its TLS +//! callbacks, then a DLL's `DllMain`. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use crate::{DLL_PROCESS_DETACH, LoadedImage}; + +const DLL_THREAD_ATTACH: u32 = 2; +const DLL_THREAD_DETACH: u32 = 3; + +struct Mapped { + image: Arc<LoadedImage>, + /// Its `DLL_PROCESS_ATTACH` is done; only then does it get thread notices. + attached: bool, + /// `DisableThreadLibraryCalls`: no more `DllMain` thread notices. + quiet: bool, +} + +/// Every title image we mapped, in load order. +static IMAGES: Mutex<Vec<Mapped>> = Mutex::new(Vec::new()); + +fn images() -> std::sync::MutexGuard<'static, Vec<Mapped>> { + IMAGES.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub(crate) fn mapped(image: &LoadedImage) { + // SAFETY: reads our own static, so the linker keeps it (and its section). + unsafe { std::ptr::from_ref(&ON_THREAD).read_volatile() }; + let image = Arc::new(image.clone()); + let mut images = images(); + images.retain(|m| m.image.base() != image.base()); + images.push(Mapped { + image, + attached: false, + quiet: false, + }); +} + +/// Its `DLL_PROCESS_ATTACH` is done. The list keeps attach order, which is +/// the Windows loader's initialisation order. +pub(crate) fn attached(base: usize) { + let mut images = images(); + if let Some(i) = images.iter().position(|m| m.image.base() == base) { + let mut m = images.remove(i); + m.attached = true; + images.push(m); + } + static AT_EXIT: std::sync::Once = std::sync::Once::new(); + // Registered before the title's own exit functions, so it runs after + // them, as `ExitProcess` follows `exit`'s functions on Windows. + // SAFETY: registers a function with the host CRT's exit table. + AT_EXIT.call_once(|| unsafe { + atexit(detach_all); + }); +} + +pub(crate) fn detached(base: usize) { + if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) { + m.attached = false; + } +} + +unsafe extern "C" { + fn atexit(f: extern "C" fn()) -> i32; +} + +/// Set once the process is ending: no more thread notices. +static EXITING: AtomicBool = AtomicBool::new(false); + +/// How long title images may take to detach before the process ends anyway +/// (a thread ended while holding a lock their detach code wants). +const DETACH_DEADLINE: Duration = Duration::from_secs(5); + +/// Process exit (the CRT's `exit`, which titles call), in `ExitProcess`'s +/// order: the title's exit functions have run; every other thread ends +/// (title threads and ours); every attached image gets +/// `DLL_PROCESS_DETACH`, DLLs in reverse initialisation order, then the +/// exe's TLS callbacks; then the CRT ends the process. +extern "C" fn detach_all() { + let attached: Vec<_> = images() + .iter_mut() + .filter(|m| m.attached) + .map(|m| { + m.attached = false; + m.image.clone() + }) + .collect(); + let (dlls, exes): (Vec<_>, Vec<_>) = + attached.into_iter().rev().partition(|i| i.info().is_dll()); + tracing::info!( + images = dlls.len() + exes.len(), + "process exit: ending other threads, detaching title images" + ); + EXITING.store(true, Ordering::SeqCst); + // As on Windows, a lock a thread held when it ended stays taken; detach + // code that waits for one would hang the exit. The watchdog runs before + // the other threads end: a thread that ends can hold the heap lock or + // the loader lock, and a new thread needs both to start. After the + // deadline it only ends the process; it does not log, because logging + // needs the heap and the log writer's lock. + // Its thread id, set when it runs its own code; 0 until then. + static WATCHDOG: AtomicU32 = AtomicU32::new(0); + drop(std::thread::spawn(|| { + // SAFETY: a plain query of the calling thread. + let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + WATCHDOG.store(id, Ordering::SeqCst); + std::thread::sleep(DETACH_DEADLINE); + end_process(); + })); + // Its start (loader notices, Rust's thread set-up) is done only when + // it runs its own code. The loader notices need the loader lock. This + // thread can hold it, or a thread that waits for this thread can hold + // it. Then the watchdog does not start, so this wait has the same + // deadline. + let waiting = Instant::now(); + let watchdog = loop { + match WATCHDOG.load(Ordering::SeqCst) { + 0 if waiting.elapsed() >= DETACH_DEADLINE => end_process(), + 0 => std::thread::yield_now(), + id => break id, + } + }; + end_other_threads(&[watchdog]); + for image in dlls.iter().chain(&exes) { + // SAFETY: attached images are bound. A non-null third argument + // tells the entry points the process is ending. + unsafe { + image.notify( + DLL_PROCESS_DETACH, + true, + std::ptr::without_provenance_mut(1), + ) + }; + } +} + +/// Ends this process when the title images do not detach in time. It does +/// not use the heap or any lock: a thread that ended can hold them. +fn end_process() { + // SAFETY: ends this process, which is exiting anyway. + unsafe { + windows_sys::Win32::System::Threading::TerminateProcess( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + 1, + ) + }; +} + +/// Ends every thread of the process but this one and those in `keep` (and +/// the ones started while doing so), as `ExitProcess` does first; except +/// the system's thread-pool workers, which `TerminateThread` refuses (the +/// process fails fast) and which run no title code (no title image uses +/// that pool). +fn end_other_threads(keep: &[u32]) { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, + }; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread, + THREAD_QUERY_INFORMATION, + }; + // SAFETY: plain queries of the calling process and thread. + let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) }; + let mut ended = std::collections::HashSet::new(); + loop { + // SAFETY: a snapshot of every thread, walked with a sized entry. + let others: Vec<u32> = unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + break; + } + let mut entry = THREADENTRY32 { + dwSize: size_of::<THREADENTRY32>() as u32, + ..std::mem::zeroed() + }; + let mut ids = Vec::new(); + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == process + && entry.th32ThreadID != me + && !keep.contains(&entry.th32ThreadID) + { + ids.push(entry.th32ThreadID); + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + ids + }; + let new: Vec<u32> = others.into_iter().filter(|id| ended.insert(*id)).collect(); + if new.is_empty() { + break; + } + for id in new { + // SAFETY: a thread of this process, which is exiting. + unsafe { + let thread = OpenThread(THREAD_TERMINATE | THREAD_QUERY_INFORMATION, 0, id); + if !thread.is_null() { + if !starts_in(thread, c"ntdll.dll") { + TerminateThread(thread, 0); + } + CloseHandle(thread); + } + } + } + } +} + +pub(crate) fn unmapped(base: usize) { + images().retain(|m| m.image.base() != base); +} + +/// `DisableThreadLibraryCalls` for a title image; `None` if `base` is not +/// one. Fails, as on Windows, for an image with static TLS. +pub fn disable_thread_calls(base: usize) -> Option<bool> { + let mut images = images(); + let m = images.iter_mut().find(|m| m.image.base() == base)?; + if m.image.info().tls.is_some() { + return Some(false); + } + m.quiet = true; + Some(true) +} + +/// Windows calls every pointer between the CRT's markers `.CRT$XLA` and +/// `.CRT$XLZ`; `XLAV` sorts ahead of the usual `XLB`, so ours runs before +/// any other callback linked into the exe. +#[used] +#[unsafe(link_section = ".CRT$XLAV")] +static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread; + +unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) { + if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH { + return; + } + if EXITING.load(Ordering::SeqCst) { + return; // our exit watchdog, or threads ending with the process + } + // A snapshot: title code may map and attach another DLL from here. + let notify: Vec<_> = images() + .iter() + .filter(|m| m.attached) + .map(|m| (m.image.clone(), !m.quiet)) + .collect(); + if notify.is_empty() { + return; + } + // Rust's std sets its threads up after this callback and aborts the + // process if their per-thread state was touched first (the current + // thread's id, which our logging asks for when title code calls us). + // That state is put back as the thread started. + let saved = (reason == DLL_THREAD_ATTACH && started_by_rust()).then(OwnTls::save); + // Starts in load order, ends in reverse, as the Windows loader does. + let notify_one = |(image, dll_main): &(Arc<LoadedImage>, bool)| { + // SAFETY: attached images have their imports bound. + unsafe { image.notify(reason, *dll_main, std::ptr::null_mut()) }; + }; + if reason == DLL_THREAD_ATTACH { + notify.iter().for_each(notify_one); + } else { + notify.iter().rev().for_each(notify_one); + } + if let Some(saved) = saved { + saved.restore(); + } +} + +/// Our own image's static TLS block on this thread (Rust's std keeps its +/// per-thread state there), as copied before title code ran. +struct OwnTls { + block: *mut u8, + saved: Vec<u8>, +} + +/// The TLS directory the linker emits for our image (the CRT's symbol). +#[repr(C)] +struct TlsDirectory { + start: usize, + end: usize, + index: *const u32, + callbacks: usize, + zero_fill: u32, + characteristics: u32, +} + +unsafe extern "C" { + static _tls_used: TlsDirectory; +} + +impl OwnTls { + fn save() -> OwnTls { + let array: *const *mut u8; + // SAFETY: reads TEB.ThreadLocalStoragePointer; the directory is our + // image's, and Windows set up its block on this thread before + // calling TLS callbacks. + let (block, len) = unsafe { + std::arch::asm!("mov {}, gs:[0x58]", out(reg) array, options(nostack, readonly)); + let dir = &raw const _tls_used; + let block = *array.add((*dir).index.read() as usize); + (block, (*dir).end - (*dir).start + (*dir).zero_fill as usize) + }; + // SAFETY: the block is `len` bytes, live for the thread's life. + let saved = unsafe { std::slice::from_raw_parts(block, len) }.to_vec(); + OwnTls { block, saved } + } + + fn restore(self) { + // SAFETY: the same block on the same thread, no reference to it held. + unsafe { std::ptr::copy_nonoverlapping(self.saved.as_ptr(), self.block, self.saved.len()) }; + } +} + +/// Whether Rust's std started this thread (its start routine is in our +/// exe): the title's main thread and our runtime's workers, which run +/// title callbacks. +fn started_by_rust() -> bool { + // SAFETY: the calling thread's pseudo handle. + starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"") +} + +/// Whether `thread`'s start routine lies in the module named `module` +/// (empty: our exe). +fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi::CStr) -> bool { + use windows_sys::Wdk::System::Threading::{ + NtQueryInformationThread, ThreadQuerySetWin32StartAddress, + }; + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleHandleA, GetModuleHandleExW, + }; + + let mut start = 0usize; + // SAFETY: writes one pointer-sized start address. + let status = unsafe { + NtQueryInformationThread( + thread, + ThreadQuerySetWin32StartAddress, + (&raw mut start).cast(), + size_of::<usize>() as u32, + std::ptr::null_mut(), + ) + }; + let mut found = std::ptr::null_mut(); + let name = if module.is_empty() { + std::ptr::null() + } else { + module.as_ptr().cast() + }; + // SAFETY: looks up the module containing an address, taking no reference. + status == 0 + && unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + start as *const u16, + &mut found, + ) + } != 0 + // SAFETY: a module handle by name (or our exe's); no reference taken. + && found == unsafe { GetModuleHandleA(name) } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + use std::time::Duration; + + /// A thread that counts in `ticks` until it ends; returns its thread id + /// when it has counted once. + fn busy(ticks: &'static AtomicU64) -> u32 { + static ID: AtomicU32 = AtomicU32::new(0); + ID.store(0, Ordering::SeqCst); + std::thread::spawn(move || { + // SAFETY: a plain query of the calling thread. + let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + ID.store(id, Ordering::SeqCst); + loop { + ticks.fetch_add(1, Ordering::SeqCst); + std::thread::yield_now(); + } + }); + while ticks.load(Ordering::SeqCst) == 0 { + std::thread::yield_now(); + } + ID.load(Ordering::SeqCst) + } + + /// Whether `ticks` stays the same for a short time. + fn stopped(ticks: &AtomicU64) -> bool { + let at = ticks.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(50)); + ticks.load(Ordering::SeqCst) == at + } + + /// In a child process of the next test: ends the other threads but one + /// kept thread, and checks that a busy thread stopped and the kept one + /// did not. + #[test] + fn exit_child() { + if std::env::var_os("VICTORY_EXIT_CHILD").is_none() { + return; + } + static ENDS: AtomicU64 = AtomicU64::new(0); + static KEPT: AtomicU64 = AtomicU64::new(0); + busy(&ENDS); + let kept = busy(&KEPT); + super::end_other_threads(&[kept]); + let ended = stopped(&ENDS); + let still_running = !stopped(&KEPT); + // The test harness's threads are gone too: leave at once. + println!( + "{} {}", + if ended { "ENDED" } else { "STILL RUNNING" }, + if still_running { "KEPT" } else { "NOT KEPT" } + ); + std::process::exit(0); + } + + #[test] + fn exit_ends_the_other_threads_first() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "threads::tests::exit_child", "--nocapture"]) + .env("VICTORY_EXIT_CHILD", "1") + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success() && text.contains("ENDED KEPT"), + "{text}" + ); + } +} diff --git a/crates/victory-loader/src/thunks.rs b/crates/victory-loader/src/thunks.rs new file mode 100644 index 000000000..48a799823 --- /dev/null +++ b/crates/victory-loader/src/thunks.rs @@ -0,0 +1,187 @@ +//! Stubs for imports nobody implements yet. +//! +//! Each unresolved import gets 32 bytes of generated code: +//! +//! ```text +//! mov rcx, <&'static ImportSite> ; 48 B9 imm64 +//! mov rax, <unimplemented_import> ; 48 B8 imm64 +//! jmp rax ; FF E0 +//! ``` +//! +//! The jump keeps the title's return address on the stack, so the handler +//! returns straight to the caller. Bring-up then shows exactly which API to +//! implement next, rather than failing at load time. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use anyhow::{Result, bail}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + DebugBreak, FlushInstructionCache, IsDebuggerPresent, +}; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualProtect, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// What an unimplemented import does when called. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum UnimplementedPolicy { + /// Log, break into an attached debugger, then abort. The default: + /// silently continuing usually crashes later and further from the cause. + #[default] + Trap, + /// Log once per import and return 0. Useful to push through bring-up. + ReturnZero, +} + +/// Identifies one unresolved import. Leaked: lives as long as the process. +#[derive(Debug)] +pub struct ImportSite { + pub dll: String, + pub symbol: String, + pub policy: UnimplementedPolicy, + pub calls: AtomicU64, +} + +static UNIMPLEMENTED_CALLS: AtomicU64 = AtomicU64::new(0); + +/// Total number of calls that reached an unimplemented-import stub. +pub fn unimplemented_call_count() -> u64 { + UNIMPLEMENTED_CALLS.load(Ordering::Relaxed) +} + +extern "system" fn unimplemented_import(site: &'static ImportSite) -> u64 { + UNIMPLEMENTED_CALLS.fetch_add(1, Ordering::Relaxed); + let previous = site.calls.fetch_add(1, Ordering::Relaxed); + match site.policy { + UnimplementedPolicy::ReturnZero => { + if previous == 0 { + tracing::warn!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called, returning 0"); + } + 0 + } + UnimplementedPolicy::Trap => { + tracing::error!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called"); + // Into the crash log too: `abort` ends the process without + // running the handlers that write it. + let (dll, symbol) = (&site.dll, &site.symbol); + let text = format!("VIctory: unimplemented import {dll}!{symbol} called"); + crate::log_crash(&text); + // SAFETY: plain Win32 calls without preconditions. + unsafe { + if IsDebuggerPresent() != 0 { + DebugBreak(); + } + } + std::process::abort(); + } + } +} + +const THUNK_SIZE: usize = 32; + +/// Executable memory holding one stub per unresolved import. +pub(crate) struct ThunkBlock { + base: *mut u8, + len: usize, + used: usize, +} + +impl ThunkBlock { + /// Reserves room for `count` stubs (writable until [`Self::seal`]). + pub(crate) fn new(count: usize) -> Result<Self> { + let len = (count.max(1) * THUNK_SIZE).next_multiple_of(4096); + // SAFETY: fresh anonymous allocation; no existing memory is touched. + let base = unsafe { + VirtualAlloc( + std::ptr::null(), + len, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + } as *mut u8; + if base.is_null() { + bail!( + "VirtualAlloc for import stubs failed: {}", + std::io::Error::last_os_error() + ); + } + Ok(ThunkBlock { base, len, used: 0 }) + } + + /// Emits a stub for `site` and returns its address. + pub(crate) fn emit(&mut self, site: &'static ImportSite) -> Result<usize> { + if self.used + THUNK_SIZE > self.len { + bail!("import stub block is full"); + } + let mut code = [0xCC_u8; THUNK_SIZE]; // int3 padding + code[0..2].copy_from_slice(&[0x48, 0xB9]); + code[2..10].copy_from_slice(&(site as *const ImportSite as u64).to_le_bytes()); + code[10..12].copy_from_slice(&[0x48, 0xB8]); + let handler = unimplemented_import as extern "system" fn(&'static ImportSite) -> u64; + code[12..20].copy_from_slice(&(handler as *const () as u64).to_le_bytes()); + code[20..22].copy_from_slice(&[0xFF, 0xE0]); + // SAFETY: `used + THUNK_SIZE <= len`, and the block is still writable. + let at = unsafe { + let at = self.base.add(self.used); + std::ptr::copy_nonoverlapping(code.as_ptr(), at, THUNK_SIZE); + at + }; + self.used += THUNK_SIZE; + Ok(at as usize) + } + + /// Makes the block read+execute. The block is intentionally leaked: + /// title code may hold these addresses for the life of the process. + pub(crate) fn seal(self) -> Result<()> { + let mut old = 0; + // SAFETY: `base..base+len` is the allocation made in `new`. + let ok = unsafe { VirtualProtect(self.base as _, self.len, PAGE_EXECUTE_READ, &mut old) }; + if ok == 0 { + bail!( + "VirtualProtect for import stubs failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: flushing our own process's instruction cache for our own block. + unsafe { FlushInstructionCache(GetCurrentProcess(), self.base as _, self.len) }; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// In a child process of the next test: calls an unimplemented import + /// that traps, with the crash log where `VICTORY_TRAP_LOG` says. + #[test] + fn trap_child() { + let Some(log) = std::env::var_os("VICTORY_TRAP_LOG") else { + return; + }; + crate::log_crashes_to(log.into()); + let site = Box::leak(Box::new(ImportSite { + dll: "probe.dll".into(), + symbol: "Missing".into(), + policy: UnimplementedPolicy::Trap, + calls: AtomicU64::new(0), + })); + unimplemented_import(site); + } + + #[test] + fn a_trapped_import_is_in_the_crash_log() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("crashes.log"); + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "thunks::tests::trap_child", "--nocapture"]) + .env("VICTORY_TRAP_LOG", &log) + .output() + .unwrap(); + assert!(!out.status.success(), "the trap ends the process"); + let text = std::fs::read_to_string(&log).unwrap_or_default(); + let named = text.contains("VIctory: unimplemented import probe.dll!Missing called"); + assert!(named, "crash log: {text:?}"); + } +} diff --git a/crates/victory-loader/src/tls.rs b/crates/victory-loader/src/tls.rs new file mode 100644 index 000000000..a234183e9 --- /dev/null +++ b/crates/victory-loader/src/tls.rs @@ -0,0 +1,219 @@ +//! Static TLS of an executable mapped as a DLL. +//! +//! An exe always gets TLS index 0, so title code reaches its thread-local +//! block as `mov r64, gs:[0x58]` (the thread's TLS array) followed by +//! `[r64]`, without reading `_tls_index`. Mapped as a DLL, the image gets +//! another index. Every such load is turned into a call to a thunk that +//! yields `&array[index]` instead, and the image's `_tls_index` (which CRT +//! code does read, and adds to the array pointer) is set to 0. + +use std::ffi::c_void; + +use anyhow::{Result, bail}; +use victory_pe::ImageInfo; +use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, + VirtualAlloc, VirtualProtect, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +const SCN_MEM_EXECUTE: u32 = 0x2000_0000; +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; + +/// Redirects the image's TLS-array loads if the OS gave it an index other +/// than 0. Returns the number of loads patched. +/// +/// # Safety +/// `base` is the image `info` describes, mapped and not yet running. +pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result<usize> { + let Some(tls) = &info.tls else { return Ok(0) }; + // 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 + 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); + } + let thunks = thunks(near(base, info.size_of_image as usize)?, index)?; + let mut patched = 0; + for section in info + .sections + .iter() + .filter(|s| s.characteristics & SCN_MEM_EXECUTE != 0) + { + let start = base + section.rva as usize; + let len = section.virtual_size as usize; + 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 { + bail!( + "VirtualProtect(code) failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: writable now, and no title code runs yet. + let code = unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) }; + patched += patch(code, start, thunks); + // SAFETY: restoring the protection we changed; flushing our own code. + unsafe { + VirtualProtect(start as _, len, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), start as _, len); + } + } + // SAFETY: see `index_at`; `.data` is writable. + unsafe { index_at.write(0) }; + tracing::info!(index, patched, "static TLS redirected"); + Ok(patched) +} + +/// Rewrites each `mov r64, gs:[0x58]` in `code` (at address `at`) as +/// `call thunks[r]; nop4`. `thunks` must be within 2 GiB of `code`. +fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { + let mut count = 0; + let mut i = 0; + while i + LOAD_LEN <= code.len() { + 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 + // 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 + && (rex == 0x48 || rex == 0x4C) + && c[2] == 0x8B + && c[3] & 0xC7 == 0x04 + && c[4..] == [0x25, 0x58, 0, 0, 0] + && reg != 4 + { + let rel = (thunks + reg * THUNK_SIZE) as i64 - (at + i + 5) as i64; + code[i] = 0xE8; + code[i + 1..i + 5].copy_from_slice(&(rel as i32).to_le_bytes()); + code[i + 5..i + 9].copy_from_slice(&[0x0F, 0x1F, 0x40, 0x00]); + count += 1; + i += LOAD_LEN; + } else { + i += 1; + } + } + count +} + +/// Fills `block` with one thunk per register: `mov r, gs:[0x58]; +/// lea r, [r + index * 8]; ret` (flags untouched, like the load it replaces). +fn thunks(block: *mut u8, index: u32) -> Result<usize> { + let disp = (index * 8).to_le_bytes(); + for reg in 0..16u8 { + let (r, low) = (reg >> 3, reg & 7); + let mut code = vec![0x65, 0x48 | r << 2, 0x8B, low << 3 | 4, 0x25, 0x58, 0, 0, 0]; + code.extend([0x48 | r << 2 | r, 0x8D, 0x80 | low << 3 | low]); + if low == 4 { + code.push(0x24); // SIB: [r12 + disp32] + } + code.extend(disp); + code.push(0xC3); + // SAFETY: `block` holds 16 thunks and is still writable. + unsafe { + std::ptr::copy_nonoverlapping( + code.as_ptr(), + block.add(usize::from(reg) * THUNK_SIZE), + code.len(), + ) + }; + } + let mut old = 0; + // SAFETY: `block` is our allocation of one page. + if unsafe { VirtualProtect(block as _, 4096, PAGE_EXECUTE_READ, &mut old) } == 0 { + bail!( + "VirtualProtect(TLS thunks) failed: {}", + std::io::Error::last_os_error() + ); + } + Ok(block as usize) +} + +/// One writable page within `rel32` reach of `[base, base + size)`. Leaked: +/// title code calls into it for the life of the process. +fn near(base: usize, size: usize) -> Result<*mut u8> { + const GRANULE: usize = 0x1_0000; + // The search spans 1 GiB each side, so every call site stays in reach. + if size >= 1 << 30 { + bail!("image too large for TLS thunks within rel32 reach"); + } + let above = (base + size).next_multiple_of(GRANULE); + for k in 0..(1usize << 14) { + for hint in [ + base.checked_sub((k + 1) * GRANULE), + Some(above + k * GRANULE), + ] { + let Some(hint) = hint else { continue }; + // SAFETY: a fresh allocation at a free address, or null. + let p = unsafe { + VirtualAlloc( + hint as *const c_void, + 4096, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + }; + if !p.is_null() { + return Ok(p.cast()); + } + } + } + bail!("no free page near the image for TLS thunks") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reads the thread's TLS array pointer the way title code does. + fn tls_array() -> usize { + let array: usize; + // SAFETY: reads TEB.ThreadLocalStoragePointer. + unsafe { std::arch::asm!("mov {}, gs:[0x58]", out(reg) array) }; + array + } + + #[test] + fn loads_become_calls_that_yield_the_title_slot() { + let page = near(tls_array as *const () as usize, 0).unwrap(); + let thunks = thunks(near(page as usize, 4096).unwrap(), 3).unwrap(); + // (before the load, REX, ModRM, after the load): each case returns + // the loaded register in rax; r12 is saved, being callee-saved. + let cases: [(&[u8], u8, u8, &[u8]); 3] = [ + (&[], 0x48, 0x04, &[0xC3]), // rax + (&[], 0x4C, 0x04, &[0x4C, 0x89, 0xC0, 0xC3]), // r8 + ( + &[0x41, 0x54], + 0x4C, + 0x24, + &[0x4C, 0x89, 0xE0, 0x41, 0x5C, 0xC3], + ), // r12 + ]; + for (before, rex, modrm, after) in cases { + let mut code = before.to_vec(); + code.extend([0x65, rex, 0x8B, modrm, 0x25, 0x58, 0, 0, 0]); + code.extend(after); + // SAFETY: the page is ours and writable. + let bytes = unsafe { std::slice::from_raw_parts_mut(page, code.len()) }; + bytes.copy_from_slice(&code); + assert_eq!(patch(bytes, page as usize, thunks), 1); + let mut old = 0; + // SAFETY: our page, made executable to run the patched code. + unsafe { VirtualProtect(page as _, 4096, PAGE_EXECUTE_READ, &mut old) }; + // SAFETY: the page holds the patched load and a return. + let f: extern "system" fn() -> usize = unsafe { std::mem::transmute(page) }; + assert_eq!(f(), tls_array() + 3 * 8, "REX {rex:#x} ModRM {modrm:#x}"); + // SAFETY: our page again. + unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) }; + } + } +} diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs new file mode 100644 index 000000000..e709d115a --- /dev/null +++ b/crates/victory-loader/src/windows.rs @@ -0,0 +1,432 @@ +//! Loading a prepared image as a real Windows module and binding it. + +use std::collections::HashSet; +use std::ffi::{CString, c_void}; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicU64; + +use anyhow::{Context, Result, bail}; +use victory_pe::{ImageInfo, ImportSymbol}; +use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW}; +use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + +use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy}; +use crate::{ + DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, ImportResolver, PreparedImage, Provenance, Resolution, + prepare, +}; + +/// A title image mapped into this process. A clone names the same mapping +/// (no reference of its own): unload one copy only. +#[derive(Debug, Clone)] +pub struct LoadedImage { + module: HMODULE, + path: PathBuf, + info: ImageInfo, +} + +// SAFETY: HMODULE is a process-wide handle (the base address); using it from +// any thread is fine. +unsafe impl Send for LoadedImage {} +// SAFETY: as above; `LoadedImage` has no interior mutability. +unsafe impl Sync for LoadedImage {} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MissingImport { + pub dll: String, + pub symbol: String, +} + +/// Outcome of [`LoadedImage::bind_imports`]. +#[derive(Debug, Default, Clone)] +pub struct BindReport { + pub hle: usize, + pub host: usize, + pub title: usize, + pub missing: Vec<MissingImport>, +} + +/// Writes the prepared copy into `dir` and maps it with the Windows loader. +/// +/// `dir` receives derived game data, so it must be outside the repository. +pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> { + victory_core::ensure_outside_repo(dir)?; + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + let path = dir.join(prepared.file_name()); + write_if_changed(&path, &prepared.bytes)?; + + let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect(); + // SAFETY: `wide` is a NUL-terminated path. The image has no entry point + // and no imports, so loading it runs no title code. + let module = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0) }; + if module.is_null() { + bail!( + "LoadLibraryExW({}) failed: {}{}", + path.display(), + std::io::Error::last_os_error(), + if prepared.info.has_relocations { + "" + } else { + " (image has no relocations; its preferred base may be taken)" + } + ); + } + let loaded = LoadedImage { + module, + path, + info: prepared.info.clone(), + }; + // 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. + unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?; + } + tracing::info!( + base = format_args!("{:#x}", loaded.base()), + preferred = format_args!("{:#x}", loaded.info.image_base), + path = %loaded.path.display(), + "image mapped" + ); + crate::threads::mapped(&loaded); + Ok(loaded) +} + +/// Maps the DLLs the title ships in `title_dir` that `main` imports, +/// directly or through each other, in initialisation order (dependencies +/// first). Only DLL names `wanted` accepts are considered, so DLLs the host +/// or our runtime provide stay with them. Imports are not bound. +pub fn load_title_dlls( + main: &ImageInfo, + title_dir: &Path, + cache_dir: &Path, + wanted: &dyn Fn(&str) -> bool, +) -> Result<Vec<(String, LoadedImage)>> { + let mut loaded = Vec::new(); + let dirs = (title_dir, cache_dir); + map_imports(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?; + Ok(loaded) +} + +/// Maps the DLL `name` from `title_dir` like [`load_title_dlls`] does, with +/// the title DLLs it imports (dependencies first, `name` last); empty if +/// `wanted` refuses it or the folder has no such file. For DLLs a title +/// loads itself; `wanted` must refuse those already mapped. +pub fn load_title_dll( + name: &str, + title_dir: &Path, + cache_dir: &Path, + wanted: &dyn Fn(&str) -> bool, +) -> Result<Vec<(String, LoadedImage)>> { + let mut loaded = Vec::new(); + let dirs = (title_dir, cache_dir); + map_dll(name, dirs, wanted, &mut HashSet::new(), &mut loaded)?; + Ok(loaded) +} + +fn map_imports( + info: &ImageInfo, + dirs: (&Path, &Path), + wanted: &dyn Fn(&str) -> bool, + seen: &mut HashSet<String>, + loaded: &mut Vec<(String, LoadedImage)>, +) -> Result<()> { + for module in info.imports.iter().chain(&info.delay_imports) { + map_dll(&module.dll, dirs, wanted, seen, loaded)?; + } + Ok(()) +} + +fn map_dll( + name: &str, + dirs: (&Path, &Path), + wanted: &dyn Fn(&str) -> bool, + seen: &mut HashSet<String>, + loaded: &mut Vec<(String, LoadedImage)>, +) -> Result<()> { + let name = name.to_ascii_lowercase(); + let path = dirs.0.join(&name); + if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() { + return Ok(()); + } + let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; + let prepared = prepare(&original).with_context(|| format!("preparing {}", path.display()))?; + let image = load(&prepared, dirs.1).with_context(|| format!("loading {}", path.display()))?; + map_imports(&image.info, dirs, wanted, seen, loaded)?; + loaded.push((name, image)); + Ok(()) +} + +/// Resolves through `inner`, then through the exports of the title's DLLs. +pub struct WithTitleDlls<'a> { + pub inner: &'a dyn ImportResolver, + pub dlls: &'a [(String, LoadedImage)], +} + +impl ImportResolver for WithTitleDlls<'_> { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + let found = self.inner.resolve(dll, symbol); + if found != Resolution::Missing { + return found; + } + self.dlls + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case(dll)) + .and_then(|(_, image)| image.export_symbol(symbol)) + .map_or(Resolution::Missing, |address| Resolution::Found { + address, + provenance: Provenance::Title, + }) + } +} + +fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> { + if std::fs::read(path).is_ok_and(|existing| existing == bytes) { + return Ok(()); + } + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?; + std::fs::rename(&tmp, path).with_context(|| format!("renaming to {}", path.display()))?; + Ok(()) +} + +impl LoadedImage { + pub fn base(&self) -> usize { + self.module as usize + } + + /// Parsed from the original image (imports, entry point, TLS callbacks). + pub fn info(&self) -> &ImageInfo { + &self.info + } + + /// Address of an export of the image, if it has one by that name. + pub fn export(&self, name: &str) -> Option<usize> { + let name = CString::new(name).ok()?; + // SAFETY: valid module handle and NUL-terminated name. + unsafe { GetProcAddress(self.module, name.as_ptr().cast()) } + .map(|f| f as *const () as usize) + } + + /// Address of an export, by name or ordinal. + pub fn export_symbol(&self, symbol: &ImportSymbol) -> Option<usize> { + match symbol { + ImportSymbol::Name { name, .. } => self.export(name), + // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module. + ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(self.module, *o as usize as _) } + .map(|f| f as *const () as usize), + } + } + + /// Fills every IAT slot of the image. + /// + /// Each import goes to `resolver`; whatever it cannot resolve gets an + /// unimplemented-import stub that behaves according to `policy`. + pub fn bind_imports( + &self, + resolver: &dyn ImportResolver, + policy: UnimplementedPolicy, + ) -> Result<BindReport> { + let mut report = BindReport::default(); + let mut slots: Vec<(u32, usize)> = Vec::with_capacity(self.info.import_count()); + let mut unresolved: Vec<(u32, &str, &ImportSymbol)> = Vec::new(); + + // Delay-load slots are bound eagerly too, so the title's own + // delay-load helper (which would ask the host) never runs. + for module in self.info.imports.iter().chain(&self.info.delay_imports) { + for entry in &module.entries { + match resolver.resolve(&module.dll, &entry.symbol) { + Resolution::Found { + address, + provenance, + } => { + match provenance { + Provenance::Hle => report.hle += 1, + Provenance::Host => report.host += 1, + Provenance::Title => report.title += 1, + } + slots.push((entry.iat_slot_rva, address)); + } + Resolution::Missing => { + unresolved.push((entry.iat_slot_rva, &module.dll, &entry.symbol)); + } + } + } + } + + if !unresolved.is_empty() { + let mut block = ThunkBlock::new(unresolved.len())?; + for (slot, dll, symbol) in unresolved { + let site: &'static ImportSite = Box::leak(Box::new(ImportSite { + dll: dll.to_owned(), + symbol: symbol.to_string(), + policy, + calls: AtomicU64::new(0), + })); + slots.push((slot, block.emit(site)?)); + report.missing.push(MissingImport { + dll: site.dll.clone(), + symbol: site.symbol.clone(), + }); + } + block.seal()?; + } + + self.write_slots(&slots)?; + tracing::info!( + hle = report.hle, + host = report.host, + missing = report.missing.len(), + "imports bound" + ); + Ok(report) + } + + /// 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<()> { + for &(rva, address) in slots { + let slot = (self.base() + rva as usize) as *mut u64; + let mut old = 0; + // 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: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: inside the image, now writable, 8-byte aligned by the PE format. + unsafe { slot.write_volatile(address as u64) }; + let mut ignored = 0; + // SAFETY: restoring the protection we just changed. + unsafe { VirtualProtect(slot as *const c_void, 8, old, &mut ignored) }; + } + Ok(()) + } + + /// Calls the image's TLS callbacks with `reason` (e.g. `DLL_PROCESS_ATTACH`). + /// + /// # Safety + /// Runs title code. Imports must be bound first. + pub unsafe fn run_tls_callbacks(&self, reason: u32) { + // SAFETY: forwarded from the caller. + unsafe { self.tls_callbacks(reason, std::ptr::null_mut()) } + } + + /// # Safety + /// See [`Self::run_tls_callbacks`]. + 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 { + type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void); + // 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) }; + } + } + + /// Initialises a DLL as the Windows loader would: its TLS callbacks, + /// then `DllMain(DLL_PROCESS_ATTACH)`. From then on it hears of every + /// thread start and end (see `threads`). + /// + /// # Safety + /// Runs title code. Imports must be bound first, and the DLLs this one + /// depends on attached. + pub unsafe fn attach(&self) -> Result<()> { + // SAFETY: forwarded from the caller. + if unsafe { self.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) } == Some(0) { + bail!("DllMain returned FALSE"); + } + crate::threads::attached(self.base()); + Ok(()) + } + + /// `DLL_PROCESS_DETACH` as `FreeLibrary` sends it (TLS callbacks, then + /// `DllMain`); the image hears of no more threads. + /// + /// # Safety + /// Runs title code. The image must have been attached (or its attach + /// failed), and no other thread may be using it. + pub unsafe fn detach(&self) { + crate::threads::detached(self.base()); + // SAFETY: forwarded from the caller. + unsafe { self.notify(DLL_PROCESS_DETACH, true, std::ptr::null_mut()) }; + } + + /// Runs the image's TLS callbacks with `reason`, then, if `dll_main` and + /// the image is a DLL with an entry point, its `DllMain`, whose result + /// is returned. `reserved` is the entry points' third argument. + /// + /// # Safety + /// Runs title code. Imports must be bound first. + pub(crate) unsafe fn notify( + &self, + reason: u32, + dll_main: bool, + reserved: *mut c_void, + ) -> Option<i32> { + // SAFETY: forwarded from the caller. + unsafe { self.tls_callbacks(reason, reserved) }; + if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 { + return None; + } + type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + // 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. + Some(unsafe { main(self.module, reason, reserved) }) + } + + /// Starts the title: on a new thread with the stack size from the image + /// header, attaches `dlls` in order (see [`Self::attach`]), runs the + /// image's TLS callbacks (`DLL_PROCESS_ATTACH`), then its original entry + /// point. Returns the thread so the caller can join it. + /// + /// # Safety + /// Runs title code. Imports of the image and of `dlls` must be bound. + pub unsafe fn spawn_main( + self: Arc<Self>, + dlls: Vec<(String, LoadedImage)>, + ) -> Result<std::thread::JoinHandle<Result<u32>>> { + if self.info.entry_rva == 0 { + bail!("image has no entry point"); + } + let stack = usize::try_from(self.info.stack_reserve) + .unwrap_or(usize::MAX) + .max(1 << 20); + std::thread::Builder::new() + .name("title-main".into()) + .stack_size(stack) + .spawn(move || { + for (name, dll) in &dlls { + // SAFETY: forwarded from the caller of `spawn_main`. + unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?; + } + // SAFETY: forwarded from the caller of `spawn_main`. + unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) }; + crate::threads::attached(self.base()); + type Entry = unsafe extern "system" fn(*mut c_void) -> u32; + // SAFETY: the entry RVA came from the original image header. + let entry: Entry = + unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; + // SAFETY: forwarded from the caller of `spawn_main`. + Ok(unsafe { entry(std::ptr::null_mut()) }) + }) + .context("spawning title main thread") + } + + /// Unmaps the image. + /// + /// # Safety + /// No title code may be running or run later, and no pointer into the + /// image may be used afterwards. + pub unsafe fn unload(self) { + crate::threads::unmapped(self.base()); + // SAFETY: guaranteed by the caller. + unsafe { FreeLibrary(self.module) }; + } +} diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs new file mode 100644 index 000000000..cf1111bda --- /dev/null +++ b/crates/victory-loader/tests/load_probe.rs @@ -0,0 +1,268 @@ +//! End-to-end: prepare, load, bind and call into a stand-in title +//! (tests/fixtures/hle-probe), without any game data. +#![cfg(windows)] + +use std::ffi::CString; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use victory_loader::{ + ImportResolver, Provenance, Resolution, UnimplementedPolicy, WithTitleDlls, prepare, + unimplemented_call_count, +}; +use victory_pe::ImportSymbol; +use windows_sys::Win32::Foundation::CloseHandle; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; +use windows_sys::Win32::System::Threading::{CreateThread, INFINITE, WaitForSingleObject}; + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +/// 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"); + let status = Command::new(env!("CARGO")) + .args(["build", "--quiet", "--manifest-path"]) + .arg(&manifest) + .arg("--target-dir") + .arg(&target) + .status() + .expect("running cargo"); + assert!(status.success(), "building hle-probe failed"); + target.join("debug").join("hle_probe.dll") +} + +extern "system" fn fake_xgameruntime_initialize() -> i32 { + 0x1234 +} +/// Asks for the current thread, as our logging does: on a thread std is +/// still starting, that must not abort the process. +extern "system" fn fake_get_tick_count() -> u32 { + let _ = std::thread::current().id(); + 777 +} +extern "system" fn fake_delayed() -> u32 { + 4242 +} + +struct TestResolver; + +impl ImportResolver for TestResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + let dll = dll.to_ascii_lowercase(); + let ImportSymbol::Name { name, .. } = symbol else { + return Resolution::Missing; + }; + let hle = match (dll.as_str(), name.as_str()) { + ("xgameruntime.dll", "XGameRuntimeInitialize") => { + Some(fake_xgameruntime_initialize as *const () as usize) + } + ("kernel32.dll", "GetTickCount") => Some(fake_get_tick_count as *const () as usize), + ("victory-probe-delayed.dll", "VIctoryProbeDelayed") => { + Some(fake_delayed as *const () as usize) + } + _ => None, + }; + if let Some(address) = hle { + return Resolution::Found { + address, + provenance: Provenance::Hle, + }; + } + host(&dll, name) + .map(|address| Resolution::Found { + address, + provenance: Provenance::Host, + }) + .unwrap_or(Resolution::Missing) + } +} + +fn host(dll: &str, name: &str) -> Option<usize> { + let dll = CString::new(dll).ok()?; + let name = CString::new(name).ok()?; + // SAFETY: NUL-terminated strings; loading system DLLs into the test process. + unsafe { + let module = LoadLibraryA(dll.as_ptr().cast()); + if module.is_null() { + return None; + } + GetProcAddress(module, name.as_ptr().cast()).map(|f| f as *const () as usize) + } +} + +#[test] +fn loads_binds_and_calls_probe() { + let dll = build_probe(); + let original = std::fs::read(&dll).unwrap(); + let prepared = prepare(&original).unwrap(); + + let imports: Vec<_> = prepared + .info + .imports + .iter() + .map(|m| m.dll.to_ascii_lowercase()) + .collect(); + assert!( + imports.contains(&"xgameruntime.dll".to_owned()), + "{imports:?}" + ); + assert!( + imports.contains(&"victory-probe-missing.dll".to_owned()), + "{imports:?}" + ); + assert!( + prepared + .info + .delay_imports + .iter() + .any(|m| m.dll.eq_ignore_ascii_case("victory-probe-delayed.dll")), + "fixture must delay-load victory-probe-delayed.dll" + ); + + let dir = tempfile::tempdir().unwrap(); + let image = victory_loader::load(&prepared, dir.path()).unwrap(); + + // The "title" ships victory-probe-title.dll: any real DLL will do. + let title_dir = tempfile::tempdir().unwrap(); + 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(); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["victory-probe-title.dll"]); + let resolver = WithTitleDlls { + inner: &TestResolver, + dlls: &dlls, + }; + for (_, dll) in &dlls { + dll.bind_imports(&resolver, UnimplementedPolicy::ReturnZero) + .unwrap(); + // SAFETY: its imports are bound, and it depends on no other title DLL. + unsafe { dll.attach() }.unwrap(); + } + let report = image + .bind_imports(&resolver, UnimplementedPolicy::ReturnZero) + .unwrap(); + assert_eq!(report.title, 1); + + assert_eq!(report.hle, 3); + assert!(report.host > 0); + assert_eq!(report.missing.len(), 1); + assert_eq!(report.missing[0].symbol, "VIctoryProbeNotImplemented"); + + let call = |name: &str| -> usize { image.export(name).unwrap_or_else(|| panic!("{name}")) }; + // SAFETY: the exports have the signatures declared in the fixture and + // every import they use has been bound. + unsafe { + let f: extern "system" fn() -> i32 = std::mem::transmute(call("probe_xgameruntime_init")); + assert_eq!(f(), 0x1234, "console API must reach our implementation"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_tick")); + assert_eq!(f(), 777, "host API must be overridable"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid")); + assert_eq!(f(), std::process::id(), "host API must pass through"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_title")); + assert_ne!(f(), 0, "title DLL export must be bound"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed")); + assert_eq!(f(), 4242, "delay-loaded API must be bound"); + + let before = unimplemented_call_count(); + let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_missing")); + assert_eq!(f(), 0); + assert_eq!(unimplemented_call_count(), before + 1); + + // Once attached, every thread start reaches its TLS callback and + // DllMain (other tests may start threads too, hence at least one). + assert!( + image + .info() + .tls + .as_ref() + .is_some_and(|t| !t.callback_rvas.is_empty()) + ); + image.attach().unwrap(); + let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts")); + let before = f(); + // A thread std starts, as our runtime's workers are: notified + // before std sets it up, which must still find its state pristine. + let worker = std::thread::Builder::new() + .name("probe-worker".into()) + .spawn(|| std::thread::current().name().map(str::to_owned)) + .unwrap(); + assert_eq!(worker.join().unwrap().as_deref(), Some("probe-worker")); + let mid = f(); + assert!(mid >> 32 > before >> 32 && mid as u32 > before as u32); + let before = mid; + // Starting in title code, as a title's threads do; the extra + // argument is ignored. + let start: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 = + std::mem::transmute(call("probe_pid")); + let thread = CreateThread( + std::ptr::null(), + 0, + Some(start), + std::ptr::null(), + 0, + std::ptr::null_mut(), + ); + assert!(!thread.is_null()); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + let after = f(); + assert!( + after >> 32 > before >> 32, + "TLS callback: {before:#x} → {after:#x}" + ); + assert!( + after as u32 > before as u32, + "DllMain: {before:#x} → {after:#x}" + ); + // It has static TLS, so Windows would refuse too. + assert_eq!( + victory_loader::disable_thread_calls(image.base()), + Some(false) + ); + assert_eq!(victory_loader::disable_thread_calls(1), None); + + // `FreeLibrary`'s notice, as a failed late load sends it. + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_detaches")); + assert_eq!(f(), 0); + image.detach(); + assert_eq!(f(), 1); + image.unload(); + } +} + +#[test] +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. + 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() + }; + let dlls = load("LATE.DLL", &|_| true); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["late.dll"]); + assert!(dlls[0].1.export("GetFileVersionInfoW").is_some()); + assert!(load("absent.dll", &|_| true).is_empty()); + assert!(load("late.dll", &|_| false).is_empty()); +} diff --git a/crates/victory-loader/tests/title_dlls.rs b/crates/victory-loader/tests/title_dlls.rs new file mode 100644 index 000000000..49101bf8c --- /dev/null +++ b/crates/victory-loader/tests/title_dlls.rs @@ -0,0 +1,16 @@ +//! A title DLL that cannot be loaded is named in the error. +#![cfg(windows)] + +#[test] +fn a_title_dll_that_does_not_prepare_is_named() { + let title = tempfile::tempdir().unwrap(); + let cache = tempfile::tempdir().unwrap(); + std::fs::write(title.path().join("broken.dll"), b"MZ not a PE").unwrap(); + let wanted = |_: &str| true; + let loaded = victory_loader::load_title_dll("broken.dll", title.path(), cache.path(), &wanted); + let Err(error) = loaded else { + panic!("a DLL that is not a PE loaded"); + }; + let text = format!("{error:#}"); + assert!(text.contains("broken.dll"), "{text}"); +} diff --git a/crates/victory-pe/Cargo.toml b/crates/victory-pe/Cargo.toml new file mode 100644 index 000000000..0f7c457ee --- /dev/null +++ b/crates/victory-pe/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "victory-pe" +description = "Read-only analysis of PE32+ images and COFF import libraries." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +object.workspace = true +thiserror.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs new file mode 100644 index 000000000..fc8f0f658 --- /dev/null +++ b/crates/victory-pe/src/image.rs @@ -0,0 +1,547 @@ +use object::LittleEndian as LE; +use object::Object; +use object::pe::{self, ImageNtHeaders64}; +use object::read::pe::{ + ExportTarget, ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList, + PeFile64, +}; + +use crate::layout::{self, dir}; +use crate::{MACHINE_AMD64, PeError}; + +/// Everything we need to know about a PE32+ image, extracted in one pass. +#[derive(Debug, Clone)] +pub struct ImageInfo { + pub machine: u16, + /// `IMAGE_FILE_HEADER::Characteristics`. + pub characteristics: u16, + pub timestamp: u32, + pub subsystem: u16, + /// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics`. + pub dll_characteristics: u16, + pub image_base: u64, + pub size_of_image: u32, + pub entry_rva: u32, + pub stack_reserve: u64, + pub stack_commit: u64, + pub sections: Vec<SectionInfo>, + pub imports: Vec<ImportModule>, + pub delay_imports: Vec<ImportModule>, + pub exports: Vec<ExportInfo>, + pub tls: Option<TlsInfo>, + pub has_relocations: bool, + pub has_exception_table: bool, + pub has_load_config: bool, + pub codeview: Option<CodeViewInfo>, +} + +#[derive(Debug, Clone)] +pub struct SectionInfo { + pub name: String, + pub rva: u32, + pub virtual_size: u32, + pub file_offset: u32, + pub file_size: u32, + pub characteristics: u32, +} + +/// One imported DLL and the functions taken from it. +#[derive(Debug, Clone)] +pub struct ImportModule { + /// DLL name exactly as written in the image (case preserved). + pub dll: String, + pub entries: Vec<ImportEntry>, +} + +#[derive(Debug, Clone)] +pub struct ImportEntry { + pub symbol: ImportSymbol, + /// RVA of the 8-byte IAT slot the loader must fill in. + pub iat_slot_rva: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ImportSymbol { + Name { hint: u16, name: String }, + Ordinal(u16), +} + +impl std::fmt::Display for ImportSymbol { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ImportSymbol::Name { name, .. } => f.write_str(name), + ImportSymbol::Ordinal(o) => write!(f, "#{o}"), + } + } +} + +#[derive(Debug, Clone)] +pub struct ExportInfo { + pub name: Option<String>, + pub ordinal: u16, + /// `None` for forwarded exports. + pub rva: Option<u32>, + /// `"dll.name"` or `"dll.#ordinal"` for forwarded exports. + pub forward: Option<String>, +} + +#[derive(Debug, Clone)] +pub struct TlsInfo { + /// RVA of `IMAGE_TLS_DIRECTORY64`. + pub directory_rva: u32, + /// VA (at the preferred base) of the callback array, 0 if none. + pub callbacks_va: u64, + /// Callback RVAs, in call order. + pub callback_rvas: Vec<u32>, +} + +/// CodeView (RSDS) record: identifies the exact build that produced an image. +#[derive(Debug, Clone)] +pub struct CodeViewInfo { + pub pdb_path: String, + pub guid: [u8; 16], + pub age: u32, +} + +impl CodeViewInfo { + /// The key symbol servers use: GUID (Windows byte order) + age. + pub fn symbol_key(&self) -> String { + let g = &self.guid; + let d1 = u32::from_le_bytes([g[0], g[1], g[2], g[3]]); + let d2 = u16::from_le_bytes([g[4], g[5]]); + let d3 = u16::from_le_bytes([g[6], g[7]]); + let mut s = format!("{d1:08X}{d2:04X}{d3:04X}"); + for b in &g[8..] { + s.push_str(&format!("{b:02X}")); + } + s.push_str(&format!("{:X}", self.age)); + s + } +} + +/// Upper bound on TLS callbacks we are willing to walk (defends against garbage). +const MAX_TLS_CALLBACKS: usize = 1024; + +impl ImageInfo { + /// Parses a complete PE32+ x86-64 image from its file bytes. + pub fn parse(data: &[u8]) -> Result<Self, PeError> { + let kind = object::FileKind::parse(data)?; + if kind != object::FileKind::Pe64 { + return Err(PeError::Unsupported(format!( + "expected PE32+, found {kind:?}" + ))); + } + let file = PeFile64::parse(data)?; + let nt = file.nt_headers(); + let fh = nt.file_header(); + let opt = nt.optional_header(); + + let machine = fh.machine.get(LE).0; + if machine != MACHINE_AMD64 { + return Err(PeError::Unsupported(format!( + "machine 0x{machine:04x} is not AMD64" + ))); + } + + let sections = file + .section_table() + .iter() + .map(|s| SectionInfo { + name: String::from_utf8_lossy(s.raw_name()).into_owned(), + rva: s.virtual_address.get(LE), + virtual_size: s.virtual_size.get(LE), + file_offset: s.pointer_to_raw_data.get(LE), + file_size: s.size_of_raw_data.get(LE), + characteristics: s.characteristics.get(LE).0, + }) + .collect(); + + let dir_present = |index: usize| { + file.data_directory(index) + .is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0) + }; + + let imports = match file.import_table()? { + Some(table) => parse_imports(&table, opt.size_of_image())?, + None => Vec::new(), + }; + let delay_imports = parse_delay_imports(&file, opt.size_of_image())?; + let exports = parse_exports(&file)?; + let tls = parse_tls(&file, data, opt.image_base())?; + let codeview = file.pdb_info()?.map(|cv| CodeViewInfo { + pdb_path: String::from_utf8_lossy(cv.path()).into_owned(), + guid: cv.guid(), + age: cv.age(), + }); + + Ok(ImageInfo { + machine, + characteristics: fh.characteristics.get(LE).0, + timestamp: fh.time_date_stamp.get(LE), + subsystem: opt.subsystem().0, + dll_characteristics: opt.dll_characteristics().0, + image_base: opt.image_base(), + size_of_image: opt.size_of_image(), + entry_rva: opt.address_of_entry_point(), + stack_reserve: opt.size_of_stack_reserve(), + stack_commit: opt.size_of_stack_commit(), + sections, + imports, + delay_imports, + exports, + tls, + has_relocations: dir_present(dir::BASERELOC) + && !has_flag( + fh.characteristics.get(LE).0, + layout::file_flags::RELOCS_STRIPPED, + ), + has_exception_table: dir_present(dir::EXCEPTION), + has_load_config: dir_present(dir::LOAD_CONFIG), + codeview, + }) + } + + pub fn is_dll(&self) -> bool { + has_flag(self.characteristics, layout::file_flags::DLL) + } + + /// Maps an RVA to an offset in the file, if it is backed by file data. + pub fn rva_to_file_offset(&self, rva: u32) -> Option<u32> { + self.sections.iter().find_map(|s| { + let delta = rva.checked_sub(s.rva)?; + // Raw data may be padded past the virtual size; that padding is + // not part of the section in memory. + let backed = match s.virtual_size { + 0 => s.file_size, + vs => vs.min(s.file_size), + }; + // Header values are untrusted: an offset near 4 GiB overflows. + (delta < backed).then(|| s.file_offset.checked_add(delta))? + }) + } + + pub fn import_count(&self) -> usize { + self.imports.iter().map(|m| m.entries.len()).sum() + } + + pub fn subsystem_name(&self) -> &'static str { + use layout::subsystem::*; + match self.subsystem { + WINDOWS_GUI => "windows-gui", + WINDOWS_CUI => "windows-cui", + XBOX => "xbox", + XBOX_CODE_CATALOG => "xbox-code-catalog", + _ => "other", + } + } +} + +fn has_flag(value: u16, flag: u16) -> bool { + value & flag != 0 +} + +fn utf8(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() +} + +fn convert_import(import: Import<'_>) -> ImportSymbol { + match import { + Import::Ordinal(o) => ImportSymbol::Ordinal(o), + Import::Name(hint, name) => ImportSymbol::Name { + hint, + name: utf8(name), + }, + } +} + +fn parse_imports( + table: &ImportTable<'_>, + size_of_image: u32, +) -> Result<Vec<ImportModule>, PeError> { + let mut modules = Vec::new(); + let mut descriptors = table.descriptors()?; + while let Some(desc) = descriptors.next()? { + let iat_rva = desc.first_thunk.get(LE); + // Prefer the unbound name table; fall back to the IAT for old linkers. + let int_rva = match desc.original_first_thunk.get(LE) { + 0 => iat_rva, + rva => rva, + }; + modules.push(ImportModule { + dll: utf8(table.name(desc.name.get(LE))?), + entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| { + table.import::<ImageNtHeaders64>(t) + })?, + }); + } + Ok(modules) +} + +fn parse_delay_imports( + file: &PeFile64<'_>, + size_of_image: u32, +) -> Result<Vec<ImportModule>, PeError> { + let Some(table) = file.delay_load_import_table()? else { + return Ok(Vec::new()); + }; + let mut modules = Vec::new(); + let mut descriptors = table.descriptors()?; + while let Some(desc) = descriptors.next()? { + modules.push(ImportModule { + dll: utf8(table.name(desc.dll_name_rva.get(LE))?), + entries: entries( + table.thunks(desc.import_name_table_rva.get(LE))?, + desc.import_address_table_rva.get(LE), + size_of_image, + |t| table.import::<ImageNtHeaders64>(t), + )?, + }); + } + Ok(modules) +} + +/// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked +/// by `object`, so every slot is checked to lie inside the image here. +fn entries<'data>( + mut thunks: ImportThunkList<'data>, + iat_rva: u32, + size_of_image: u32, + import: impl Fn(pe::ImageThunkData64) -> object::read::Result<Import<'data>>, +) -> Result<Vec<ImportEntry>, PeError> { + let mut entries = Vec::new(); + while let Some(thunk) = thunks.next::<ImageNtHeaders64>()? { + let iat_slot_rva = u32::try_from(entries.len() * 8) + .ok() + .and_then(|offset| iat_rva.checked_add(offset)) + .filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image)) + .ok_or_else(|| { + PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image")) + })?; + entries.push(ImportEntry { + symbol: convert_import(import(thunk)?), + iat_slot_rva, + }); + } + Ok(entries) +} + +fn parse_exports(file: &PeFile64<'_>) -> Result<Vec<ExportInfo>, PeError> { + let Some(table) = file.export_table()? else { + return Ok(Vec::new()); + }; + Ok(table + .exports()? + .into_iter() + // An address of 0 marks an unused slot in the address table (a gap + // in the ordinals), not an export at the image base. + .filter(|e| !matches!(e.target, ExportTarget::Address(0))) + .map(|e| { + let (rva, forward) = match e.target { + ExportTarget::Address(rva) => (Some(rva), None), + ExportTarget::ForwardByName(d, n) => { + (None, Some(format!("{}.{}", utf8(d), utf8(n)))) + } + ExportTarget::ForwardByOrdinal(d, o) => { + (None, Some(format!("{}.#{}", utf8(d), o.0))) + } + }; + ExportInfo { + name: e.name.map(utf8), + ordinal: e.ordinal.0, + rva, + forward, + } + }) + .collect()) +} + +fn parse_tls( + file: &PeFile64<'_>, + data: &[u8], + image_base: u64, +) -> Result<Option<TlsInfo>, PeError> { + let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else { + return Ok(None); + }; + let directory_rva = dd.virtual_address.get(LE); + if directory_rva == 0 { + return Ok(None); + } + let sections = file.section_table(); + let tls = sections + .pe_data_at(data, directory_rva) + .ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?; + let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS) + .ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?; + + let mut callback_rvas = Vec::new(); + if callbacks_va != 0 { + let array_rva = va_to_rva(callbacks_va, image_base)?; + let array = sections + .pe_data_at(data, array_rva) + .ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?; + for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) { + let va = u64::from_le_bytes(*slot); + if va == 0 { + break; + } + callback_rvas.push(va_to_rva(va, image_base)?); + } + } + Ok(Some(TlsInfo { + directory_rva, + callbacks_va, + callback_rvas, + })) +} + +fn va_to_rva(va: u64, image_base: u64) -> Result<u32, PeError> { + va.checked_sub(image_base) + .and_then(|rva| u32::try_from(rva).ok()) + .ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The test binary itself is a real MSVC-linked PE32+ image. + fn own_image() -> Vec<u8> { + std::fs::read(std::env::current_exe().unwrap()).unwrap() + } + + #[test] + fn parses_own_test_binary() { + let info = ImageInfo::parse(&own_image()).unwrap(); + assert_eq!(info.machine, MACHINE_AMD64); + assert!(!info.is_dll()); + assert!(info.entry_rva != 0); + assert!(info.has_exception_table, "x64 images always carry .pdata"); + assert!(info.sections.iter().any(|s| s.name.starts_with(".text"))); + let kernel32 = info + .imports + .iter() + .find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll")) + .expect("Rust std imports kernel32"); + assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0)); + // Rust std uses static TLS, so a TLS directory must be present (its + // callback array may legitimately be empty). + assert!(info.tls.is_some()); + } + + #[test] + fn rva_to_file_offset_maps_entry_point() { + let data = own_image(); + let info = ImageInfo::parse(&data).unwrap(); + let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize; + assert!(off < data.len()); + } + + #[test] + 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; + assert!(info.rva_to_file_offset(rva).is_some()); + // Used to overflow (a panic in debug builds, a wrong offset in + // release ones). + info.sections[0].file_offset = u32::MAX - 0x10; + assert_eq!(info.rva_to_file_offset(rva), None); + } + + #[test] + fn rejects_garbage_without_panicking() { + assert!(ImageInfo::parse(b"").is_err()); + assert!(ImageInfo::parse(b"MZ not really").is_err()); + let mut truncated = own_image(); + truncated.truncate(0x200); + assert!(ImageInfo::parse(&truncated).is_err()); + } + + #[test] + fn rejects_iat_outside_image() { + let mut data = own_image(); + let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap(); + let import_rva = layout::read_u32(&data, dd).unwrap(); + let desc = ImageInfo::parse(&data) + .unwrap() + .rva_to_file_offset(import_rva) + .unwrap() as usize; + // First descriptor's FirstThunk, at the 4 GiB limit: used to overflow. + data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes()); + assert!(matches!( + ImageInfo::parse(&data), + Err(PeError::Malformed(_)) + )); + } + /// A minimal PE32+ image: one section at RVA 0x1000 holding `body`, with + /// the export directory (RVA 0x1000, 0x80 bytes) pointing at it. + fn synthetic_image(body: &[u8]) -> Vec<u8> { + let mut d = vec![0u8; 0x200]; + d[0..2].copy_from_slice(b"MZ"); + d[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes()); + d[0x40..0x44].copy_from_slice(b"PE\0\0"); + d[0x44..0x46].copy_from_slice(&MACHINE_AMD64.to_le_bytes()); + d[0x46..0x48].copy_from_slice(&1u16.to_le_bytes()); // sections + d[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // optional header size + d[0x56..0x58].copy_from_slice(&0x2022u16.to_le_bytes()); // DLL, large address aware + let opt = 0x58; + d[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes()); + d[opt + 24..opt + 32].copy_from_slice(&0x1_8000_0000u64.to_le_bytes()); + d[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); + d[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); + d[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); + d[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes()); + d[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); + d[opt + 112..opt + 116].copy_from_slice(&0x1000u32.to_le_bytes()); + d[opt + 116..opt + 120].copy_from_slice(&0x80u32.to_le_bytes()); + let sec = opt + 240; + d[sec..sec + 6].copy_from_slice(b".edata"); + d[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size + d[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes()); + d[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw size + d[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw offset + d.extend_from_slice(body); + d.resize(0x400, 0); + d + } + + #[test] + fn unused_export_slots_are_not_exports() { + // Ordinal base 1; three address slots: "alpha", an unused hole (0), + // and "gamma". The Windows loader treats address 0 as "not exported". + let mut body = vec![0u8; 0x100]; + let put32 = + |b: &mut Vec<u8>, at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + put32(&mut body, 12, 0x1040); // name of the DLL + put32(&mut body, 16, 1); // ordinal base + put32(&mut body, 20, 3); // number of functions + put32(&mut body, 24, 2); // number of names + put32(&mut body, 28, 0x1028); // address table + put32(&mut body, 32, 0x1034); // name pointer table + put32(&mut body, 36, 0x103C); // name ordinal table + put32(&mut body, 0x28, 0x1200); + put32(&mut body, 0x2C, 0); + put32(&mut body, 0x30, 0x1204); + put32(&mut body, 0x34, 0x1044); + put32(&mut body, 0x38, 0x104A); + body[0x3C..0x3E].copy_from_slice(&0u16.to_le_bytes()); + body[0x3E..0x40].copy_from_slice(&2u16.to_le_bytes()); + body[0x40..0x44].copy_from_slice(b"t.dl"); + body[0x44..0x4A].copy_from_slice(b"alpha\0"); + body[0x4A..0x50].copy_from_slice(b"gamma\0"); + + let info = ImageInfo::parse(&synthetic_image(&body)).unwrap(); + let exports: Vec<_> = info + .exports + .iter() + .map(|e| (e.name.as_deref(), e.ordinal, e.rva)) + .collect(); + assert_eq!( + exports, + [ + (Some("alpha"), 1, Some(0x1200)), + (Some("gamma"), 3, Some(0x1204)) + ] + ); + } +} diff --git a/crates/victory-pe/src/implib.rs b/crates/victory-pe/src/implib.rs new file mode 100644 index 000000000..234c1ecf0 --- /dev/null +++ b/crates/victory-pe/src/implib.rs @@ -0,0 +1,66 @@ +//! COFF import libraries (`.lib`). +//! +//! An umbrella import library tells us which DLL provides each API that a +//! console title may link against. That is the map the runtime needs to +//! decide which of our implementations answers which import. + +use object::read::archive::ArchiveFile; +use object::read::coff::{ImportFile, ImportName, ImportType}; + +use crate::{ImportSymbol, PeError}; + +/// One `dll!export` pair described by an import library. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct LibImport { + pub dll: String, + pub export: ImportSymbol, + pub kind: LibImportKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum LibImportKind { + Code, + Data, + Const, +} + +/// Result of reading an import library. +#[derive(Debug, Default)] +pub struct ImportLibrary { + pub imports: Vec<LibImport>, + /// Members that are not short-format import objects (regular objects, + /// long-format import descriptors). Reported so nothing is silently lost. + pub other_members: usize, +} + +impl ImportLibrary { + pub fn parse(data: &[u8]) -> Result<Self, PeError> { + let archive = ArchiveFile::parse(data)?; + let mut lib = ImportLibrary::default(); + for member in archive.members() { + let member = member?; + let bytes = member.data(data)?; + match ImportFile::parse(bytes) { + Ok(import) => lib.imports.push(LibImport { + dll: String::from_utf8_lossy(import.dll()).into_owned(), + export: match import.import() { + ImportName::Name(name) => ImportSymbol::Name { + hint: 0, + name: String::from_utf8_lossy(name).into_owned(), + }, + ImportName::Ordinal(o) => ImportSymbol::Ordinal(o), + }, + kind: match import.import_type() { + ImportType::Code => LibImportKind::Code, + ImportType::Data => LibImportKind::Data, + ImportType::Const => LibImportKind::Const, + }, + }), + Err(_) => lib.other_members += 1, + } + } + lib.imports.sort(); + lib.imports.dedup(); + Ok(lib) + } +} diff --git a/crates/victory-pe/src/layout.rs b/crates/victory-pe/src/layout.rs new file mode 100644 index 000000000..888f9d23f --- /dev/null +++ b/crates/victory-pe/src/layout.rs @@ -0,0 +1,110 @@ +//! Raw byte offsets of PE32+ header fields, for code that patches images. +//! +//! All offsets are relative to the start of the structure named in the +//! constant's prefix. They follow the published PE/COFF specification. + +/// Offset of `e_lfanew` (u32) in the DOS header. +pub const DOS_E_LFANEW: usize = 0x3C; + +/// Size of the `PE\0\0` signature that precedes the file header. +pub const NT_SIGNATURE_SIZE: usize = 4; +/// Size of `IMAGE_FILE_HEADER`. +pub const FILE_HEADER_SIZE: usize = 20; + +/// `IMAGE_FILE_HEADER::Characteristics` (u16). +pub const FILE_HEADER_CHARACTERISTICS: usize = 18; + +/// `IMAGE_OPTIONAL_HEADER64::AddressOfEntryPoint` (u32). +pub const OPT_ADDRESS_OF_ENTRY_POINT: usize = 16; +/// `IMAGE_OPTIONAL_HEADER64::CheckSum` (u32). +pub const OPT_CHECKSUM: usize = 64; +/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` (u16). +pub const OPT_DLL_CHARACTERISTICS: usize = 70; +/// `IMAGE_OPTIONAL_HEADER64::NumberOfRvaAndSizes` (u32). +pub const OPT_NUMBER_OF_RVA_AND_SIZES: usize = 108; +/// First `IMAGE_DATA_DIRECTORY` entry (each is `{ rva: u32, size: u32 }`). +pub const OPT_DATA_DIRECTORY: usize = 112; +/// Size of one `IMAGE_DATA_DIRECTORY`. +pub const DATA_DIRECTORY_SIZE: usize = 8; + +/// `IMAGE_TLS_DIRECTORY64::AddressOfCallBacks` (u64 VA). +pub const TLS64_ADDRESS_OF_CALLBACKS: usize = 24; + +/// Data directory indices. +pub mod dir { + pub const IMPORT: usize = 1; + pub const EXCEPTION: usize = 3; + pub const BASERELOC: usize = 5; + pub const LOAD_CONFIG: usize = 10; + pub const BOUND_IMPORT: usize = 11; + pub const IAT: usize = 12; +} + +/// `IMAGE_FILE_HEADER::Characteristics` flags. +pub mod file_flags { + pub const RELOCS_STRIPPED: u16 = 0x0001; + pub const DLL: u16 = 0x2000; +} + +/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` flags. +pub mod dll_flags { + pub const HIGH_ENTROPY_VA: u16 = 0x0020; + pub const DYNAMIC_BASE: u16 = 0x0040; + pub const FORCE_INTEGRITY: u16 = 0x0080; + pub const NX_COMPAT: u16 = 0x0100; + pub const APPCONTAINER: u16 = 0x1000; + pub const GUARD_CF: u16 = 0x4000; +} + +/// `IMAGE_OPTIONAL_HEADER64::Subsystem` values. +pub mod subsystem { + pub const WINDOWS_GUI: u16 = 2; + pub const WINDOWS_CUI: u16 = 3; + pub const XBOX: u16 = 14; + pub const XBOX_CODE_CATALOG: u16 = 17; +} + +/// Offset of the optional header from the start of the file. +pub fn optional_header_offset(data: &[u8]) -> Option<usize> { + let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; + lfanew.checked_add(NT_SIGNATURE_SIZE + FILE_HEADER_SIZE) +} + +/// Offset of the file header from the start of the file. +pub fn file_header_offset(data: &[u8]) -> Option<usize> { + let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; + lfanew.checked_add(NT_SIGNATURE_SIZE) +} + +/// Offset of data directory `index` from the start of the file. +pub fn data_directory_offset(data: &[u8], index: usize) -> Option<usize> { + let opt = optional_header_offset(data)?; + let count = read_u32(data, opt.checked_add(OPT_NUMBER_OF_RVA_AND_SIZES)?)? as usize; + if index >= count { + return None; + } + opt.checked_add(OPT_DATA_DIRECTORY)? + .checked_add(index.checked_mul(DATA_DIRECTORY_SIZE)?) +} + +pub fn read_u32(data: &[u8], at: usize) -> Option<u32> { + let end = at.checked_add(4)?; + Some(u32::from_le_bytes(data.get(at..end)?.try_into().ok()?)) +} + +pub fn read_u64(data: &[u8], at: usize) -> Option<u64> { + let end = at.checked_add(8)?; + Some(u64::from_le_bytes(data.get(at..end)?.try_into().ok()?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_reject_overflowing_offsets() { + let data = [0u8; 16]; + assert_eq!(read_u32(&data, usize::MAX - 1), None); + assert_eq!(read_u64(&data, usize::MAX - 2), None); + } +} diff --git a/crates/victory-pe/src/lib.rs b/crates/victory-pe/src/lib.rs new file mode 100644 index 000000000..89cd91553 --- /dev/null +++ b/crates/victory-pe/src/lib.rs @@ -0,0 +1,35 @@ +//! Read-only analysis of PE32+ (x86-64) images and COFF import libraries. +//! +//! Xbox Series X|S titles are ordinary x86-64 PE32+ images (the console CPU +//! is a Zen 2), so the same parser serves titles, console system DLLs and +//! host binaries alike. This crate never modifies anything; patching lives in +//! `victory-loader`, which uses the raw offsets exported from [`layout`]. + +mod image; +pub mod implib; +pub mod layout; + +pub use image::{ + CodeViewInfo, ExportInfo, ImageInfo, ImportEntry, ImportModule, ImportSymbol, SectionInfo, + TlsInfo, +}; + +/// Errors produced while parsing an image or import library. +#[derive(Debug, thiserror::Error)] +pub enum PeError { + /// The file is a valid PE but not one we handle (e.g. 32-bit or ARM64). + #[error("unsupported image: {0}")] + Unsupported(String), + /// The file is truncated or internally inconsistent. + #[error("malformed image: {0}")] + Malformed(String), +} + +impl From<object::read::Error> for PeError { + fn from(e: object::read::Error) -> Self { + PeError::Malformed(e.to_string()) + } +} + +/// `IMAGE_FILE_MACHINE_AMD64`. +pub const MACHINE_AMD64: u16 = 0x8664; diff --git a/crates/victory-pipeline/Cargo.toml b/crates/victory-pipeline/Cargo.toml new file mode 100644 index 000000000..f5d5ccb33 --- /dev/null +++ b/crates/victory-pipeline/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "victory-pipeline" +description = "Offline conversion of user-supplied game data into host formats, with a content-addressed cache." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-core.workspace = true +anyhow.workspace = true +blake3.workspace = true +tracing.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-pipeline/src/cache.rs b/crates/victory-pipeline/src/cache.rs new file mode 100644 index 000000000..81e57de2d --- /dev/null +++ b/crates/victory-pipeline/src/cache.rs @@ -0,0 +1,159 @@ +use std::io::Write; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; + +use crate::Converter; + +/// Identifies one conversion result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct CacheKey(blake3::Hash); + +impl CacheKey { + pub fn new(converter: &dyn Converter, input: &[u8]) -> Self { + let mut h = blake3::Hasher::new(); + h.update(converter.id().as_bytes()); + h.update(&[0]); + h.update(&converter.version().to_le_bytes()); + h.update(input); + CacheKey(h.finalize()) + } + + pub fn to_hex(&self) -> String { + self.0.to_hex().to_string() + } +} + +/// Content-addressed store under the user's cache directory. +#[derive(Debug, Clone)] +pub struct Cache { + root: PathBuf, +} + +impl Cache { + /// Opens (creating) a cache at `root`. Refuses locations inside the repo. + pub fn open(root: impl Into<PathBuf>) -> Result<Self> { + let root = root.into(); + victory_core::ensure_outside_repo(&root)?; + std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?; + Ok(Cache { root }) + } + + pub fn path_for(&self, key: &CacheKey) -> PathBuf { + let hex = key.to_hex(); + self.root.join(&hex[..2]).join(&hex[2..]) + } + + /// Returns the cached output for `input`, converting it first if needed. + pub fn get_or_convert(&self, converter: &dyn Converter, input: &[u8]) -> Result<PathBuf> { + let key = CacheKey::new(converter, input); + let path = self.path_for(&key); + if path.is_file() { + tracing::trace!(converter = converter.id(), key = %key.to_hex(), "cache hit"); + return Ok(path); + } + let output = converter + .convert(input) + .with_context(|| format!("converter {} v{}", converter.id(), converter.version()))?; + let dir = path.parent().expect("hashed path has a parent"); + std::fs::create_dir_all(dir)?; + // Write-then-rename so readers never see partial output. + let tmp = tempfile_in(dir); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp)?; + let written = file.write_all(&output); + drop(file); + let published = written.and_then(|()| std::fs::rename(&tmp, &path)); + if published.is_err() { + let _ = std::fs::remove_file(&tmp); + } + published?; + Ok(path) + } +} + +fn tempfile_in(dir: &Path) -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + dir.join(format!(".tmp-{}-{n}", std::process::id())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Upper { + version: u32, + runs: AtomicUsize, + } + + impl Converter for Upper { + fn id(&self) -> &'static str { + "test.upper" + } + fn version(&self) -> u32 { + self.version + } + fn convert(&self, input: &[u8]) -> Result<Vec<u8>> { + self.runs.fetch_add(1, Ordering::Relaxed); + Ok(input.to_ascii_uppercase()) + } + } + + #[test] + fn converts_once_then_hits() { + let tmp = tempfile::tempdir().unwrap(); + let cache = Cache::open(tmp.path().join("cache")).unwrap(); + let conv = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let a = cache.get_or_convert(&conv, b"abc").unwrap(); + let b = cache.get_or_convert(&conv, b"abc").unwrap(); + assert_eq!(a, b); + assert_eq!(std::fs::read(&a).unwrap(), b"ABC"); + assert_eq!(conv.runs.load(Ordering::Relaxed), 1); + } + + #[test] + fn failed_publication_removes_the_staging_file() { + let tmp = tempfile::tempdir().unwrap(); + let cache = Cache::open(tmp.path().join("cache")).unwrap(); + let conv = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let path = cache.path_for(&CacheKey::new(&conv, b"abc")); + std::fs::create_dir_all(&path).unwrap(); + + assert!(cache.get_or_convert(&conv, b"abc").is_err()); + assert!(path.is_dir()); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } + + #[test] + fn version_bump_invalidates() { + let v1 = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let v2 = Upper { + version: 2, + runs: AtomicUsize::new(0), + }; + assert_ne!(CacheKey::new(&v1, b"x"), CacheKey::new(&v2, b"x")); + } + + #[test] + fn refuses_cache_inside_repo() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); + assert!(Cache::open(inside).is_err()); + } +} diff --git a/crates/victory-pipeline/src/lib.rs b/crates/victory-pipeline/src/lib.rs new file mode 100644 index 000000000..c417e5c1a --- /dev/null +++ b/crates/victory-pipeline/src/lib.rs @@ -0,0 +1,23 @@ +//! Offline conversion of the user's game data into host formats. +//! +//! Everything here runs on the user's machine, reads the user's files and +//! writes into the user's cache. Nothing produced here is ever committed: +//! derived data is still game data (docs/asset-policy.md). +//! +//! The unit of work is a [`Converter`]: bytes in, bytes out, deterministic. +//! Results are stored in a content-addressed [`Cache`] keyed by converter +//! id, converter version and input bytes, so re-running the pipeline after +//! a game update or a converter fix only redoes what changed. + +mod cache; + +pub use cache::{Cache, CacheKey}; + +/// A deterministic transformation of one input into one output. +pub trait Converter: Send + Sync { + /// Stable identifier, e.g. `"texture.detile"`. Part of the cache key. + fn id(&self) -> &'static str; + /// Bump whenever the output for a given input changes. + fn version(&self) -> u32; + fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>>; +} diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml new file mode 100644 index 000000000..edfd1b969 --- /dev/null +++ b/crates/victory-shader/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "victory-shader" +description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +thiserror.workspace = true +miniz_oxide.workspace = true + +[features] +# Host D3D12 pipeline checks (`emit::host`). +host = ["dep:windows"] +# Debugging switches (emitted-module dumps and the like). +diagnostics = [] + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_System_LibraryLoader"] } +windows = { workspace = true, optional = true, features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", +] } + +[target.'cfg(windows)'.dev-dependencies] +windows = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", +] } + +[lints] +workspace = true diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs new file mode 100644 index 000000000..43fb195a3 --- /dev/null +++ b/crates/victory-shader/src/bvh.rs @@ -0,0 +1,696 @@ +//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and +//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the +//! instruction returns for one ray and one node. The emitter lowers the +//! instruction to the same arithmetic in the same order +//! (`emit/intersect.rs`), so its code can be compared against this dword +//! for dword. +//! +//! The instruction tests one ray against one 64-byte node of a bounding +//! volume hierarchy and returns four dwords. Traversal (the stack, instance +//! transforms, culling, the hit distance `numerator / denominator`) is the +//! program's own code. +//! +//! # Node pointers +//! +//! A node pointer's low three bits are the node's kind, the rest its byte +//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the +//! base address of the descriptor (40 bits in dword 0 and the low byte of +//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer; +//! the 64-bit form a 64-bit one, with which a program uses one descriptor +//! with base 0 for every structure and adds `address >> 3` itself. +//! +//! | kind | node | +//! |---|---| +//! | 0-3 | triangle 0-3 of a triangle node | +//! | 4 | box node, 16-bit floats (64 bytes) | +//! | 5 | box node, 32-bit floats (128 bytes) | +//! | 6 | instance: not read by the instruction | +//! | 7 | procedural primitive: not read by the instruction | +//! +//! # Box nodes +//! +//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four +//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16 +//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes +//! 112-127 are not read). The result is the pointers of the children whose +//! box the ray enters before its extent, nearest entry first when the +//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest. +//! +//! # Triangle nodes +//! +//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte +//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that +//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an +//! input triangle's second vertex at the former, its third at the latter +//! and its first at the remaining one, so I and J are the weights of the +//! input triangle's second and third vertices). Triangle `k` of the node +//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that +//! keeps fewer triangles in a node uses the bytes of the unused vertices +//! for its own data. +//! +//! With the descriptor's triangle return mode set (bit 120) the result is +//! the hit distance's numerator, its denominator, and the numerators of I +//! and J over the same denominator, as floats. The denominator is positive +//! for a triangle whose vertices run clockwise seen from the ray's origin +//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0. +//! The ray's extent is not tested for triangles. +//! +//! # Where this comes from +//! +//! The node formats, the descriptor bits and the tests are those of the +//! 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 +//! 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 +//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here: +//! a triangle miss; the title's programs do not read it). + +/// The result dword for a box the ray misses, or a child that is not there. +pub const NONE: u32 = 0xffff_ffff; + +/// The node's vertices that make triangle 0-3, by the triangle's own +/// vertex numbers 0-2. +pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]]; + +/// Descriptor dword 1: boxes are returned nearest first. +pub const BOX_SORT: u32 = 1 << 31; +/// Descriptor dword 3: triangles return the numerators of I and J (clear: +/// a triangle id and a hit status, which nothing here produces). +pub const RETURN_BARYCENTRICS: u32 = 1 << 24; +/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing +/// structure. +pub const DESCRIPTOR_TYPE: u32 = 8; + +/// The ray as the instruction takes it. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Ray { + pub extent: f32, + pub origin: [f32; 3], + pub direction: [f32; 3], + /// What the program computed as `1 / direction`. + pub inverse: [f32; 3], +} + +impl Ray { + /// A ray with the inverse direction a program computes by division. + pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self { + Self { + extent, + origin, + direction, + inverse: direction.map(|d| 1.0 / d), + } + } +} + +/// The kind of the node a pointer names. +pub fn kind(pointer: u64) -> u32 { + (pointer & 7) as u32 +} + +/// The byte address of the node `pointer` names, for a descriptor whose +/// first two dwords are `word0` and `word1`. +pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 { + let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8; + base.wrapping_add((pointer >> 3) << 6) +} + +/// What the instruction returns for the node at `words` (its first 28 +/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer +/// of this `kind`, with box sorting as `sort` says and the triangle return +/// mode set. +pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] { + match kind & 7 { + 4 => boxes(&children(words), &boxes16(words), ray, sort), + 5 => boxes(&children(words), &boxes32(words), ray, sort), + k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits), + _ => MISS.map(f32::to_bits), + } +} + +/// A box node's four child pointers. +pub fn children(words: &[u32; 28]) -> [u32; 4] { + [words[0], words[1], words[2], words[3]] +} + +/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z. +pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] { + std::array::from_fn(|b| { + std::array::from_fn(|k| { + let half = 6 * b + k; + half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16) + }) + }) +} + +/// The four boxes of a 32-bit box node. +pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] { + std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k]))) +} + +/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest +/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432, +/// 0x042). +pub fn vertex_map(k: u32) -> u32 { + let v = TRIANGLE_VERTICES[(k & 3) as usize]; + v[0] | v[1] << 4 | v[2] << 8 +} + +/// The vertices of triangle `k` (0-3) of a triangle node, the first being +/// the one neither barycentric weighs, then I's, then J's. +pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] { + let id = words[15] >> (8 * k); + let (i, j) = (id & 3, id >> 2 & 3); + // An id naming one vertex twice, or a vertex 3, is malformed; it reads + // what this arithmetic lands on (a vertex of the node), as the emitted + // code does. + let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3; + [first, i, j].map(|n| { + let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize; + std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c])) + }) +} + +/// The box test: child pointers of the boxes the ray enters, `NONE` for +/// the others; sorted by entry distance when `sort`, in child order +/// otherwise. +pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] { + // An infinite inverse (a direction component of 0) would turn an + // origin exactly on a box's face into a NaN. (Maximum then minimum, as + // the emitted code: a NaN becomes the lower bound, where `clamp` would + // keep it.) + #[allow(clippy::manual_clamp)] + let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX)); + let mut ids = [NONE; 4]; + let mut distances = [f32::INFINITY; 4]; + for (n, b) in boxes.iter().enumerate() { + let (mut near, mut far) = ([0f32; 3], [0f32; 3]); + for a in 0..3 { + let low = (b[a] - ray.origin[a]) * inverse[a]; + let high = (b[3 + a] - ray.origin[a]) * inverse[a]; + near[a] = low.min(high); + far[a] = low.max(high); + } + let enter = near[0].max(near[1]).max(near[2]); + let leave = far[0].min(far[1]).min(far[2]); + // A box whose minimum x is NaN is switched off. + if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent { + ids[n] = children[n]; + distances[n] = enter; + } + } + if sort { + for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] { + if distances[b] < distances[a] { + distances.swap(a, b); + ids.swap(a, b); + } + } + } + ids +} + +/// What a triangle the ray misses returns. +pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0]; + +/// The triangle test: the hit distance's numerator, the denominator, and +/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise. +/// Watertight: the vertices are sheared so the ray runs along its largest +/// axis, and the signs of the three edge functions decide, so a ray +/// between two triangles that share an edge cannot miss both. Any NaN +/// misses, and so does a triangle seen edge-on. +pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] { + let d = ray.direction; + let size = d.map(f32::abs); + // The largest axis, and the other two in an order that keeps the + // triangle's winding. + let kz = if size[0] >= size[1] { + if size[0] >= size[2] { 0 } else { 2 } + } else if size[1] >= size[2] { + 1 + } else { + 2 + }; + let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3); + if d[kz] < 0.0 { + std::mem::swap(&mut kx, &mut ky); + } + let sz = ray.inverse[kz]; + let (sx, sy) = (d[kx] * sz, d[ky] * sz); + let sheared = |v: &[f32; 3]| { + let r = [ + v[0] - ray.origin[0], + v[1] - ray.origin[1], + v[2] - ray.origin[2], + ]; + (r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz]) + }; + let (ax, ay, az) = sheared(&p[0]); + let (bx, by, bz) = sheared(&p[1]); + let (cx, cy, cz) = sheared(&p[2]); + let u = cx * by - cy * bx; + let v = ax * cy - ay * cx; + let w = bx * ay - by * ax; + let behind = u < 0.0 || v < 0.0 || w < 0.0; + let before = u > 0.0 || v > 0.0 || w > 0.0; + let det = u + (v + w); + let t = (u * az + v * bz) + w * cz; + let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0; + if !(behind && before) && ahead { + [t, det, v, w] + } else { + MISS + } +} + +/// A 16-bit float as a 32-bit one (exact). +pub fn half_to_f32(h: u16) -> f32 { + let sign = u32::from(h >> 15) << 31; + let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff)); + let bits = match exponent { + 0 if mantissa == 0 => sign, + 0 => { + // Subnormal: normalise. + let shift = mantissa.leading_zeros() - 21; + sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13 + } + 0x1f => sign | 0xff << 23 | mantissa << 13, + e => sign | (e + 112) << 23 | mantissa << 13, + }; + f32::from_bits(bits) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// The smallest 16-bit float not below `x` (`up`) or not above it. + pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 { + let mut best: Option<u16> = None; + for h in 0..=0xffffu16 { + let f = half_to_f32(h); + if f.is_nan() || if up { f < x } else { f > x } { + continue; + } + best = match best { + Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b), + _ => Some(h), + }; + } + best.expect("a half") + } + + /// A 32-bit box node. + pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] { + let mut w = [0u32; 28]; + w[..4].copy_from_slice(&children); + for (b, bx) in boxes.iter().enumerate() { + for (k, x) in bx.iter().enumerate() { + w[4 + 6 * b + k] = x.to_bits(); + } + } + w + } + + /// A 16-bit box node holding `boxes` rounded outward. + pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] { + let mut w = [0u32; 28]; + w[..4].copy_from_slice(&children); + for (b, bx) in boxes.iter().enumerate() { + for (k, x) in bx.iter().enumerate() { + let half = 6 * b + k; + let h = if x.is_nan() { + 0x7e00 + } else { + f32_to_half(*x, k >= 3) + }; + w[4 + half / 2] |= u32::from(h) << (16 * (half % 2)); + } + } + w + } + + /// A triangle node: up to five vertices, and the dword at byte 60. + pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] { + let mut w = [0u32; 28]; + for (n, v) in vertices.iter().enumerate() { + for (c, x) in v.iter().enumerate() { + w[3 * n + c] = x.to_bits(); + } + } + w[15] = id; + w + } + + const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]; + + fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] { + std::array::from_fn(|k| b[k] + by[k % 3]) + } + + const OFF: [f32; 6] = [f32::NAN; 6]; + + #[test] + fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() { + // The 64-bit form as the title uses it: base 0, the structure's + // address folded into the pointer. + let structure = 0x12_3456_7800u64; + let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5); + assert_eq!(kind(pointer), 5); + assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40); + // The 32-bit form: the base in the descriptor. + let word0 = (structure >> 8) as u32; + let word1 = (structure >> 40) as u32 | BOX_SORT; + assert_eq!( + node_address(word0, word1, 0x1000 >> 3 | 4), + structure + 0x1000 + ); + // A base past 4 GiB of 256-byte units. + assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64); + } + + #[test] + fn halves_convert_exactly() { + assert_eq!(half_to_f32(0x3c00), 1.0); + assert_eq!(half_to_f32(0xc000), -2.0); + assert_eq!(half_to_f32(0x7c00), f32::INFINITY); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24)); + assert_eq!(half_to_f32(0x7bff), 65504.0); + assert!(half_to_f32(0x7e00).is_nan()); + assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000); + // Outward rounding of the test helper. + assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1); + assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1); + } + + #[test] + fn boxes_are_returned_nearest_first_and_misses_last() { + let children = [0x105, 0x20c, 0x304, 0x400]; + // Along +x from the origin: boxes at x = 30, 10, (off axis), 20. + let node = box32( + children, + [ + moved(UNIT, [30.0, 0.0, 0.0]), + moved(UNIT, [10.0, 0.0, 0.0]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.0, 0.0, 0.0]), + ], + ); + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]); + // Without sorting: child order, the miss in its place. + assert_eq!( + intersect(&node, 5, &ray, false), + [0x105, 0x20c, NONE, 0x400] + ); + // The extent cuts the far ones off (entered at 9, 19, 29). + let short = Ray { + extent: 19.5, + ..ray + }; + assert_eq!( + intersect(&node, 5, &short, true), + [0x20c, 0x400, NONE, NONE] + ); + // An entry exactly at the extent is no hit. + let exact = Ray { + extent: 19.0, + ..ray + }; + assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]); + // Backwards: nothing. + let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]); + } + + #[test] + fn a_ray_starting_inside_a_box_enters_it_at_its_origin() { + let node = box32( + [8, 16, NONE, NONE], + [UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF], + ); + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0); + // Box 0 is entered at -1 (behind the origin), box 1 at 2. + assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]); + // Even with a tiny extent the box around the origin is a hit. + let tiny = Ray { + extent: 1e-6, + ..ray + }; + assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() { + let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]); + // Direction components of 0: the inverse is infinite. + let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert!(ray.inverse[1].is_infinite()); + // The origin lies in the plane of the box's -y face: (-1 - -1) x inf + // would be a NaN; with the inverse held finite it is 0, and the ray + // running along the face is inside. + assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]); + // Along the +y face it is outside: the face's plane is left at 0 + // and the box is entered at 4 (as the public emulation has it). + let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]); + let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]); + // -0 gives -infinity. + let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0); + assert_eq!(minus.inverse[1], f32::NEG_INFINITY); + assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn a_box_switched_off_and_a_missing_child_return_none() { + let node = box32( + [8, NONE, 24, 32], + [UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF], + ); + let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0); + // Child 1 is hit but is not there: its pointer is what "none" is. + assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn equal_distances_keep_child_order() { + let node = box32([8, 16, 24, 32], [UNIT; 4]); + let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]); + } + + #[test] + fn half_float_boxes_test_like_their_widened_values() { + let boxes = [ + moved(UNIT, [30.0, 0.1, 0.0]), + moved(UNIT, [10.0, 0.0, 0.3]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.7, 0.0, 0.0]), + ]; + let children = [0x105, 0x20c, 0x304, 0x400]; + let node = box16(children, boxes); + let wide = boxes16(&node); + for (w, b) in wide.iter().zip(&boxes) { + for k in 0..3 { + assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward"); + } + } + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]); + assert_eq!( + intersect(&node, 4, &ray, true), + intersect(&box32(children, wide), 5, &ray, true) + ); + } + + /// The hit a result describes: distance, I, J, front face. + fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> { + let [t, det, i, j] = r.map(f32::from_bits); + (t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0)) + } + + /// Clockwise seen from the origin looking down +z in a left-handed + /// system (x right, y up): the front face. + const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]]; + + #[test] + fn a_triangle_returns_distance_and_weights_over_one_denominator() { + let node = triangles(&TRIANGLE, 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert_eq!(t, 5.0); + // (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2. + assert_eq!((i, j), (0.25, 0.25)); + assert!(front); + // Near vertex 1: I near 1. + let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0); + let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert!(i > 0.85 && j < 0.1, "{i} {j}"); + // From behind: the same weights, the back face. + let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0); + let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false)); + // An unnormalised direction: the distance is in its units. + let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0); + assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25); + } + + #[test] + fn a_triangle_is_missed_beside_behind_and_edge_on() { + let node = triangles(&TRIANGLE, 9); + let miss = MISS.map(f32::to_bits); + // Beside it. + let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // It lies behind the origin. + let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // In its plane. + let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // A triangle with no area. + let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9); + let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&flat, 0, &ray, true), miss); + // A vertex that is not a number, a direction of zero. + let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&nan, 0, &ray, true), miss); + let still = Ray::new([0.0; 3], [0.0; 3], 100.0); + assert_eq!(intersect(&node, 0, &still, true), miss); + // The extent is the program's to test: a far triangle is a hit. + let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0); + assert!(hit(intersect(&node, 0, &short, true)).is_some()); + } + + #[test] + fn a_ray_through_a_shared_edge_misses_neither_triangle() { + // Two triangles of a quad sharing the diagonal, wound alike. + let quad = [ + [-1.0, -1.0, 4.0], + [-1.0, 1.0, 4.0], + [1.0, 1.0, 4.0], + [1.0, -1.0, 4.0], + ]; + let first = triangles(&[quad[0], quad[1], quad[2]], 9); + let second = triangles(&[quad[0], quad[2], quad[3]], 9); + // A fan of rays crossing the diagonal, some exactly on it. + for n in -40..=40 { + let x = n as f32 / 64.0; + for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] { + for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] { + // Aim at (ox, oy, 4). + let s = 4.0 / d[2]; + let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0); + let a = hit(intersect(&first, 0, &ray, true)); + let b = hit(intersect(&second, 0, &ray, true)); + assert!( + a.is_some() || b.is_some(), + "a hole at {ox} {oy} along {d:?}" + ); + for h in [a, b].into_iter().flatten() { + assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}"); + } + } + } + } + } + + #[test] + fn the_id_dword_says_which_vertices_the_weights_belong_to() { + // What the title's builder does with an input triangle (a, b, c) + // and an id byte: a at the vertex neither field names, b at I's, + // c at J's. + let [a, b, c] = TRIANGLE; + let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0); + let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true); + for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] { + let mut stored = [[0f32; 3]; 3]; + stored[(3 - i - j) as usize] = a; + stored[i as usize] = b; + stored[j as usize] = c; + let node = triangles(&stored, i | j << 2); + assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}"); + } + // The higher bits of the byte (opaque and the like) change nothing. + let node = triangles(&[a, b, c], 9 | 0x80); + assert_eq!(intersect(&node, 0, &ray, true), plain); + } + + #[test] + fn triangles_one_to_three_take_their_vertices_and_their_id_byte() { + let [a, b, c] = TRIANGLE; + let far = [50.0, 50.0, 50.0]; + let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0); + let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true); + for k in 1..4u32 { + // Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`. + let mut vertices = [far; 5]; + let at = TRIANGLE_VERTICES[k as usize]; + vertices[at[0] as usize] = a; + vertices[at[1] as usize] = b; + vertices[at[2] as usize] = c; + // Triangle 0's byte would be malformed here; only byte k counts. + let node = triangles(&vertices, 9 << (8 * k)); + assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}"); + } + // A pair as the title's builder stores it: the second triangle's + // own vertex at node vertex 3, named by I. + let d = [2.0, 2.0, 5.0]; + // Input triangles (a, b, c) and (a, d, b): they share a and b. + let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8); + // Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2. + let got = triangle_vertices(&node, 1); + assert_eq!(got, [b, d, c]); + } + + #[test] + fn instances_and_procedural_nodes_return_a_triangle_miss() { + let node = triangles(&TRIANGLE, 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + for k in [6, 7] { + assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits)); + } + } + + #[test] + fn the_largest_axis_and_its_sign_do_not_change_the_answer() { + // The same triangle and ray turned so the ray's largest axis is each + // of the three, forwards and backwards. Both turns are rotations, + // so the facing stays. + let turn = |v: [f32; 3], axis: usize, flip: bool| { + let mut r = v; + for _ in 0..axis { + r = [r[2], r[0], r[1]]; + } + if flip { + // Half a turn about the axis after the largest one's next. + let largest = (2 + axis) % 3; + r[largest] = -r[largest]; + r[(largest + 1) % 3] = -r[(largest + 1) % 3]; + } + r + }; + let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0); + let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit"); + for axis in 0..3 { + for flip in [false, true] { + let p = TRIANGLE.map(|v| turn(v, axis, flip)); + let r = Ray::new( + turn(ray.origin, axis, flip), + turn(ray.direction, axis, flip), + 100.0, + ); + let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit"); + assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}"); + assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5); + assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}"); + } + } + } +} diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs new file mode 100644 index 000000000..7a20963b6 --- /dev/null +++ b/crates/victory-shader/src/dxbc.rs @@ -0,0 +1,181 @@ +//! The DXBC container: a header, then a table of FourCC-tagged parts. +//! +//! ```text +//! 0x00 "DXBC" +//! 0x04 digest[16] +//! 0x14 version major u16, minor u16 +//! 0x18 total size u32 +//! 0x1C part count u32 +//! 0x20 part offsets u32[count] +//! part: fourcc[4], size u32, data[size] +//! ``` + +use crate::ShaderError; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct FourCC(pub [u8; 4]); + +impl FourCC { + pub const DXIL: FourCC = FourCC(*b"DXIL"); + pub const STAT: FourCC = FourCC(*b"STAT"); + pub const RTS0: FourCC = FourCC(*b"RTS0"); + pub const PSV0: FourCC = FourCC(*b"PSV0"); + pub const ISG1: FourCC = FourCC(*b"ISG1"); + pub const OSG1: FourCC = FourCC(*b"OSG1"); + /// Per-primitive outputs of a mesh shader. + pub const PSG1: FourCC = FourCC(*b"PSG1"); + pub const SFI0: FourCC = FourCC(*b"SFI0"); + pub const HASH: FourCC = FourCC(*b"HASH"); + pub const ILDB: FourCC = FourCC(*b"ILDB"); + pub const ILDN: FourCC = FourCC(*b"ILDN"); +} + +impl std::fmt::Debug for FourCC { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self) + } +} + +impl std::fmt::Display for FourCC { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + for &b in &self.0 { + let c = if b.is_ascii_graphic() { b as char } else { '.' }; + write!(f, "{c}")?; + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Part<'a> { + pub fourcc: FourCC, + /// Offset of the part header within the container. + pub offset: usize, + pub data: &'a [u8], +} + +#[derive(Debug, Clone)] +pub struct Container<'a> { + pub digest: [u8; 16], + pub version: (u16, u16), + pub parts: Vec<Part<'a>>, +} + +const HEADER_SIZE: usize = 0x20; +const MAX_PARTS: usize = 256; + +impl<'a> Container<'a> { + pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> { + if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" { + return Err(ShaderError::NotDxbc); + } + let digest = data[4..20].try_into().expect("16 bytes"); + let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?); + 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; + let fourcc = FourCC( + data.get(offset..offset + 4) + .ok_or(ShaderError::Malformed("part header out of bounds"))? + .try_into() + .expect("4 bytes"), + ); + let size = u32_at(data, offset + 4)? as usize; + let body = data + .get(offset + 8..offset + 8 + size) + .ok_or(ShaderError::Malformed("part data out of bounds"))?; + parts.push(Part { + fourcc, + offset, + data: body, + }); + } + Ok(Container { + digest, + version, + parts, + }) + } + + pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> { + self.parts.iter().find(|p| p.fourcc == fourcc) + } +} + +pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> { + data.get(at..at + 2) + .map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes"))) + .ok_or(ShaderError::Malformed("truncated")) +} + +pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> { + data.get(at..at + 4) + .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) + .ok_or(ShaderError::Malformed("truncated")) +} + +pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> { + data.get(at..at + 8) + .map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes"))) + .ok_or(ShaderError::Malformed("truncated")) +} + +/// Builds a container from parts (test helper). +#[cfg(test)] +pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> { + let table = HEADER_SIZE + 4 * parts.len(); + let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>(); + let mut out = Vec::with_capacity(total); + out.extend_from_slice(b"DXBC"); + out.extend_from_slice(&[0; 16]); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&(total as u32).to_le_bytes()); + out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + let mut offset = table; + for (_, d) in parts { + out.extend_from_slice(&(offset as u32).to_le_bytes()); + offset += 8 + d.len(); + } + for (fourcc, d) in parts { + out.extend_from_slice(&fourcc.0); + out.extend_from_slice(&(d.len() as u32).to_le_bytes()); + out.extend_from_slice(d); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_parts() { + let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]); + let c = Container::parse(&bytes).unwrap(); + assert_eq!(c.parts.len(), 2); + assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]); + assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20); + assert!(c.part(FourCC::DXIL).is_none()); + } + + #[test] + fn rejects_bad_input() { + assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc); + let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]); + let last = bytes.len() - 1; + bytes[0x20] = 0xFF; // corrupt the first part offset + assert!(Container::parse(&bytes).is_err()); + bytes.truncate(last); + assert!(Container::parse(&bytes).is_err()); + } +} diff --git a/crates/victory-shader/src/dxil.rs b/crates/victory-shader/src/dxil.rs new file mode 100644 index 000000000..8c7a71ce6 --- /dev/null +++ b/crates/victory-shader/src/dxil.rs @@ -0,0 +1,211 @@ +//! The DXIL program inside a container's `DXIL` (or `STAT`) part. +//! +//! ```text +//! 0x00 program version u32 (kind << 16 | major << 4 | minor) +//! 0x04 size in dwords u32 +//! 0x08 "DXIL" <- bitcode offset is relative to here +//! 0x0C dxil version u32 +//! 0x10 bitcode offset u32 (16 in standard PC DXIL) +//! 0x14 bitcode size u32 +//! ``` + +use crate::ShaderError; +use crate::dxbc::u32_at; + +const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE]; +#[cfg(test)] +const STANDARD_BITCODE_OFFSET: u32 = 16; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ShaderKind { + Pixel, + Vertex, + Geometry, + Hull, + Domain, + Compute, + Library, + RayGeneration, + Intersection, + AnyHit, + ClosestHit, + Miss, + Callable, + Mesh, + Amplification, + Node, + Unknown(u16), +} + +impl ShaderKind { + fn from_raw(v: u16) -> Self { + use ShaderKind::*; + match v { + 0 => Pixel, + 1 => Vertex, + 2 => Geometry, + 3 => Hull, + 4 => Domain, + 5 => Compute, + 6 => Library, + 7 => RayGeneration, + 8 => Intersection, + 9 => AnyHit, + 10 => ClosestHit, + 11 => Miss, + 12 => Callable, + 13 => Mesh, + 14 => Amplification, + 15 => Node, + other => Unknown(other), + } + } +} + +#[derive(Debug, Clone)] +pub struct DxilProgram<'a> { + pub kind: ShaderKind, + pub shader_model: (u8, u8), + pub dxil_version: u32, + /// LLVM bitcode (starts with `BC C0 DE`). + pub bitcode: &'a [u8], + /// Bytes between the bitcode header and the bitcode. Empty on PC. + pub prefix: &'a [u8], + /// Bytes after the bitcode, up to the program size. Empty on PC. + pub trailer: &'a [u8], +} + +/// Xbox additions recognised around the bitcode. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct XboxExtras { + /// The prefix starts with an `XDAT` table. + pub xdat: bool, + /// The trailer contains an `xbop` blob (compiler options). + pub xbop: bool, +} + +impl<'a> DxilProgram<'a> { + pub fn parse(part: &'a [u8]) -> Result<Self, ShaderError> { + let version = u32_at(part, 0)?; + let size = (u32_at(part, 4)? as usize) + .checked_mul(4) + .filter(|&s| s <= part.len() && s >= 24) + .ok_or(ShaderError::Malformed( + "program size disagrees with part size", + ))?; + let part = &part[..size]; + if part.get(8..12) != Some(b"DXIL") { + return Err(ShaderError::Malformed("missing DXIL magic")); + } + let dxil_version = u32_at(part, 12)?; + let offset = u32_at(part, 16)?; + let len = u32_at(part, 20)? as usize; + let start = 8 + offset as usize; + let bitcode = part + .get(start..start + len) + .ok_or(ShaderError::Malformed("bitcode out of bounds"))?; + if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) { + return Err(ShaderError::Malformed("bitcode lacks LLVM magic")); + } + let prefix = part + .get(24..start) + .ok_or(ShaderError::Malformed("bitcode offset too small"))?; + Ok(DxilProgram { + kind: ShaderKind::from_raw((version >> 16) as u16), + shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8), + dxil_version, + bitcode, + prefix, + trailer: &part[start + len..], + }) + } + + /// True for a program laid out exactly like PC DXIL. + pub fn is_standard_layout(&self) -> bool { + self.prefix.is_empty() && self.trailer.is_empty() + } + + pub fn xbox_extras(&self) -> XboxExtras { + XboxExtras { + xdat: self.prefix.starts_with(b"XDAT"), + xbop: self.trailer.windows(4).any(|w| w == b"xbop"), + } + } +} + +/// Builds a standard PC-layout program around `bitcode` (test helper). +#[cfg(test)] +pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec<u8> { + let mut out = Vec::new(); + let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1); + let padded = bitcode.len().next_multiple_of(4); + let size_dwords = (24 + padded) / 4; + out.extend_from_slice(&version.to_le_bytes()); + out.extend_from_slice(&(size_dwords as u32).to_le_bytes()); + out.extend_from_slice(b"DXIL"); + out.extend_from_slice(&dxil_version.to_le_bytes()); + out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes()); + out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes()); + out.extend_from_slice(bitcode); + out.resize(24 + padded, 0); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fake_bitcode() -> Vec<u8> { + let mut b = LLVM_BITCODE_MAGIC.to_vec(); + b.extend_from_slice(&[0xAA; 12]); + b + } + + #[test] + fn parses_standard_layout() { + let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode()); + let p = DxilProgram::parse(&bytes).unwrap(); + assert_eq!(p.kind, ShaderKind::Pixel); + assert_eq!(p.shader_model, (6, 0)); + assert!(p.is_standard_layout()); + assert_eq!(p.xbox_extras(), XboxExtras::default()); + } + + #[test] + fn detects_xbox_layout() { + // Xbox layout: XDAT table before the bitcode, xbop blob after it. + let bitcode = fake_bitcode(); + let xdat = b"XDAT\x01\x00\x00\x00"; + let trailer = b"xbop\x02\x00\x00\x00"; + let mut bytes = Vec::new(); + let size = 24 + xdat.len() + bitcode.len() + trailer.len(); + bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5 + bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes()); + bytes.extend_from_slice(b"DXIL"); + bytes.extend_from_slice(&0x105u32.to_le_bytes()); + bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes()); + bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes()); + bytes.extend_from_slice(xdat); + bytes.extend_from_slice(&bitcode); + bytes.extend_from_slice(trailer); + + let p = DxilProgram::parse(&bytes).unwrap(); + assert_eq!(p.kind, ShaderKind::Compute); + assert_eq!(p.shader_model, (6, 5)); + assert!(!p.is_standard_layout()); + assert_eq!( + p.xbox_extras(), + XboxExtras { + xdat: true, + xbop: true + } + ); + assert_eq!(p.bitcode, &bitcode[..]); + } + + #[test] + fn rejects_missing_bitcode_magic() { + let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]); + assert!(DxilProgram::parse(&bytes).is_err()); + } +} diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs new file mode 100644 index 000000000..40b0883ae --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -0,0 +1,1235 @@ +//! A DXIL module and its LLVM 3.7 bitcode, written with unabbreviated +//! records only (the format DXIL fixes; codes from LLVM's `LLVMBitCodes.h`). +//! +//! Values are symbolic while the module is built ([`V`]) and numbered when +//! it is written: functions, then constants (all at module level), then the +//! instructions of `main` in block order. + +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, + /// Pointee and address space. + Ptr(Ty, u32), + Struct(Option<String>, Vec<Ty>), + Array(u32, Ty), + Func(Ty, Vec<Ty>), +} + +/// A value: a global variable, a function, a module constant, or an +/// instruction result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) enum V { + Global(u32), + Func(u32), + Const(u32), + Inst(u32), +} + +/// A global variable declaration (thread-group shared memory). +struct Global { + name: String, + ty: Ty, + /// Its pointer type. + ptr: Ty, + space: u32, + /// An internal constant with this initialiser (a constant table). + init: Option<u32>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Const { + Int(i64), + Float(u32), + Undef, + Aggregate(Vec<u32>), +} + +/// LLVM binary opcodes (the same codes serve the float forms). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Bin { + Add = 0, + Sub = 1, + Mul = 2, + UDiv = 3, + SDiv = 4, + URem = 5, + Shl = 7, + LShr = 8, + AShr = 9, + And = 10, + Or = 11, + Xor = 12, +} + +/// `atomicrmw` operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Rmw { + Xchg = 0, + Add = 1, + Sub = 2, + And = 3, + Or = 5, + Xor = 6, + Max = 7, + Min = 8, + UMax = 9, + UMin = 10, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Cast { + Trunc = 0, + ZExt = 1, + SExt = 2, + FpToUi = 3, + FpToSi = 4, + UiToFp = 5, + SiToFp = 6, + Bitcast = 11, +} + +/// Compare predicates: floats 0-15, integers 32-41. +pub(crate) mod pred { + pub const FALSE: u8 = 0; + pub const OEQ: u8 = 1; + pub const OGT: u8 = 2; + pub const OGE: u8 = 3; + pub const OLT: u8 = 4; + pub const OLE: u8 = 5; + // Not emitted: the AMD D3D12 driver treats it as UNE, so `v_cmp_lg` + // lowers as OLT | OGT instead. + #[allow(dead_code)] + pub const ONE: u8 = 6; + pub const ORD: u8 = 7; + pub const UNO: u8 = 8; + pub const UEQ: u8 = 9; + pub const UGT: u8 = 10; + pub const UGE: u8 = 11; + pub const ULT: u8 = 12; + pub const ULE: u8 = 13; + pub const UNE: u8 = 14; + pub const TRUE: u8 = 15; + pub const EQ: u8 = 32; + pub const NE: u8 = 33; + pub const IUGT: u8 = 34; + pub const IUGE: u8 = 35; + pub const IULT: u8 = 36; + pub const IULE: u8 = 37; + pub const SGT: u8 = 38; + pub const SGE: u8 = 39; + pub const SLT: u8 = 40; + pub const SLE: u8 = 41; +} + +#[derive(Debug, Clone)] +enum Op { + Bin(Bin, V, V), + Cast(Cast, V), + Cmp(u8, V, V), + Select(V, V, V), + Extract(V, u32), + Call(u32, Vec<V>), + /// Filled in later: (value, block). + Phi(Vec<(V, usize)>), + /// `getelementptr` over the pointee type, from a pointer. + Gep(Ty, V, Vec<V>), + Load(V), + /// Pointer, value. + Store(V, V), + AtomicRmw(Rmw, V, V), + /// Pointer, expected, new; returns `{i32, i1}`. + CmpXchg(V, V, V), +} + +#[derive(Debug, Clone)] +struct Inst { + ty: Ty, + op: Op, +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Term { + Br(usize), + CondBr(V, usize, usize), + Ret, +} + +#[derive(Debug, Clone, Default)] +struct Block { + phis: Vec<u32>, + body: Vec<u32>, + term: Option<Term>, +} + +/// Function attributes of a `dx.op` declaration. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Attr { + ReadNone = 1, + NoUnwind = 2, + ReadOnly = 3, + /// Barriers. + NoDuplicate = 4, +} + +struct Func { + name: String, + ty: Ty, + attr: Option<Attr>, + body: bool, +} + +/// A metadata node operand. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Md(u32); + +enum MdDef { + Str(String), + Value(Ty, V), + Node(Vec<Option<Md>>), +} + +#[derive(Default)] +pub(crate) struct Module { + types: Vec<TypeDef>, + type_ids: HashMap<TypeDef, u32>, + consts: Vec<(Ty, Const)>, + const_ids: HashMap<(Ty, Const), u32>, + globals: Vec<Global>, + funcs: Vec<Func>, + func_ids: HashMap<String, u32>, + insts: Vec<Inst>, + blocks: Vec<Block>, + mds: Vec<MdDef>, + named: Vec<(String, Vec<Md>)>, + /// See [`Tag`]: by instruction. + tags: HashMap<u32, Tag>, +} + +impl Module { + fn ty(&mut self, def: TypeDef) -> Ty { + if let Some(&t) = self.type_ids.get(&def) { + return Ty(t); + } + let t = self.types.len() as u32; + self.types.push(def.clone()); + self.type_ids.insert(def, t); + Ty(t) + } + + pub fn void(&mut self) -> Ty { + self.ty(TypeDef::Void) + } + pub fn int(&mut self, bits: u32) -> Ty { + self.ty(TypeDef::Int(bits)) + } + pub fn float(&mut self) -> Ty { + self.ty(TypeDef::Float) + } + pub fn ptr(&mut self, to: Ty) -> Ty { + self.ty(TypeDef::Ptr(to, 0)) + } + pub fn ptr_in(&mut self, to: Ty, space: u32) -> Ty { + self.ty(TypeDef::Ptr(to, space)) + } + pub fn array(&mut self, n: u32, of: Ty) -> Ty { + self.ty(TypeDef::Array(n, of)) + } + pub fn named_struct(&mut self, name: &str, fields: Vec<Ty>) -> Ty { + self.ty(TypeDef::Struct(Some(name.into()), fields)) + } + pub fn func_ty(&mut self, ret: Ty, params: Vec<Ty>) -> Ty { + self.ty(TypeDef::Func(ret, params)) + } + + fn is_void(&self, t: Ty) -> bool { + self.types[t.0 as usize] == TypeDef::Void + } + + fn constant(&mut self, ty: Ty, c: Const) -> V { + if let Some(&i) = self.const_ids.get(&(ty, c.clone())) { + return V::Const(i); + } + let i = self.consts.len() as u32; + self.consts.push((ty, c.clone())); + self.const_ids.insert((ty, c), i); + V::Const(i) + } + + pub fn int_const(&mut self, ty: Ty, v: i64) -> V { + self.constant(ty, Const::Int(v)) + } + pub fn i32(&mut self, v: u32) -> V { + let t = self.int(32); + self.int_const(t, i64::from(v as i32)) + } + pub fn i8(&mut self, v: u8) -> V { + let t = self.int(8); + self.int_const(t, i64::from(v as i8)) + } + pub fn bool(&mut self, v: bool) -> V { + let t = self.int(1); + self.int_const(t, -i64::from(v)) + } + pub fn f32(&mut self, bits: u32) -> V { + let t = self.float(); + self.constant(t, Const::Float(bits)) + } + pub fn undef(&mut self, ty: Ty) -> V { + self.constant(ty, Const::Undef) + } + /// A constant struct or array of constants. + pub fn aggregate(&mut self, ty: Ty, fields: &[V]) -> V { + let ids = fields + .iter() + .map(|f| match f { + V::Const(i) => *i, + _ => panic!("aggregate of a non-constant"), + }) + .collect(); + self.constant(ty, Const::Aggregate(ids)) + } + + /// The value of an integer constant; `None` for anything else. + pub fn int_value(&self, v: V) -> Option<i64> { + match v { + V::Const(i) => match self.consts[i as usize].1 { + Const::Int(x) => Some(x), + _ => None, + }, + _ => None, + } + } + + /// 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) { + self.consts[o as usize] = self.consts[n as usize].clone(); + } + } + + /// A function declaration (or `main` with `body`), found by name. + pub fn function(&mut self, name: &str, ty: Ty, attr: Option<Attr>, body: bool) -> V { + if let Some(&i) = self.func_ids.get(name) { + return V::Func(i); + } + let i = self.funcs.len() as u32; + self.funcs.push(Func { + name: name.into(), + ty, + attr, + body, + }); + self.func_ids.insert(name.into(), i); + V::Func(i) + } + + /// An external global of type `ty` in address space `space` (DXIL + /// declares thread-group shared memory this way). + pub fn global(&mut self, name: &str, ty: Ty, space: u32) -> V { + let ptr = self.ptr_in(ty, space); + self.globals.push(Global { + name: name.into(), + ty, + ptr, + space, + init: None, + }); + V::Global(self.globals.len() as u32 - 1) + } + + /// An internal constant global initialised with the constant `init`. + pub fn constant_global(&mut self, name: &str, init: V) -> V { + let V::Const(i) = init else { + panic!("a global initialised with a non-constant") + }; + let ty = self.consts[i as usize].0; + let g = self.global(name, ty, 0); + if let V::Global(n) = g { + self.globals[n as usize].init = Some(i); + } + 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 + } + + pub fn type_of(&self, v: V) -> Ty { + match v { + V::Global(i) => self.globals[i as usize].ptr, + V::Const(i) => self.consts[i as usize].0, + V::Inst(i) => self.insts[i as usize].ty, + V::Func(i) => { + let t = self.funcs[i as usize].ty; + *self + .type_ids + .get(&TypeDef::Ptr(t, 0)) + .map(|t| Ty(*t)) + .as_ref() + .expect("function pointer type") + } + } + } + + fn push(&mut self, block: usize, ty: Ty, op: Op) -> V { + let i = self.insts.len() as u32; + self.insts.push(Inst { ty, op }); + // Terminators are kept apart, so a block can still grow at its end. + self.blocks[block].body.push(i); + V::Inst(i) + } + + pub fn bin(&mut self, block: usize, op: Bin, a: V, b: V) -> V { + let ty = self.type_of(a); + self.push(block, ty, Op::Bin(op, a, b)) + } + pub fn cast(&mut self, block: usize, op: Cast, v: V, to: Ty) -> V { + self.push(block, to, Op::Cast(op, v)) + } + pub fn cmp(&mut self, block: usize, pred: u8, a: V, b: V) -> V { + let t = self.int(1); + self.push(block, t, Op::Cmp(pred, a, b)) + } + pub fn select(&mut self, block: usize, c: V, t: V, f: V) -> V { + let ty = self.type_of(t); + self.push(block, ty, Op::Select(c, t, f)) + } + pub fn extract(&mut self, block: usize, agg: V, index: u32) -> V { + let ty = match &self.types[self.type_of(agg).0 as usize] { + TypeDef::Struct(_, f) => f[index as usize], + TypeDef::Array(_, t) => *t, + t => panic!("extractvalue from {t:?}"), + }; + self.push(block, ty, Op::Extract(agg, index)) + } + pub fn call(&mut self, block: usize, f: V, args: Vec<V>) -> V { + let V::Func(i) = f else { + panic!("call of a non-function") + }; + let TypeDef::Func(ret, _) = self.types[self.funcs[i as usize].ty.0 as usize] else { + unreachable!() + }; + self.push(block, ret, Op::Call(i, args)) + } + /// A phi at the top of `block`; incoming values come with [`Module::set_phi`]. + pub fn phi(&mut self, block: usize, ty: Ty) -> V { + let i = self.insts.len() as u32; + self.insts.push(Inst { + ty, + op: Op::Phi(Vec::new()), + }); + self.blocks[block].phis.push(i); + V::Inst(i) + } + /// The address of element `index` of the array `ptr` points to. + pub fn element(&mut self, block: usize, ptr: V, index: V) -> V { + let TypeDef::Ptr(arr, space) = self.types[self.type_of(ptr).0 as usize] else { + panic!("element of a non-pointer") + }; + let TypeDef::Array(_, elem) = self.types[arr.0 as usize] else { + panic!("element of a non-array") + }; + let ty = self.ptr_in(elem, space); + let zero = self.i32(0); + self.push(block, ty, Op::Gep(arr, ptr, vec![zero, index])) + } + pub fn load(&mut self, block: usize, ptr: V) -> V { + let TypeDef::Ptr(ty, _) = self.types[self.type_of(ptr).0 as usize] else { + panic!("load from a non-pointer") + }; + self.push(block, ty, Op::Load(ptr)) + } + pub fn store(&mut self, block: usize, ptr: V, value: V) { + let void = self.void(); + self.push(block, void, Op::Store(ptr, value)); + } + pub fn atomic(&mut self, block: usize, op: Rmw, ptr: V, value: V) -> V { + let ty = self.type_of(value); + self.push(block, ty, Op::AtomicRmw(op, ptr, value)) + } + /// The old value of a compare-exchange. + pub fn cmpxchg(&mut self, block: usize, ptr: V, expected: V, new: V) -> V { + let (i32t, i1) = (self.type_of(new), self.int(1)); + let pair = self.ty(TypeDef::Struct(None, vec![i32t, i1])); + let r = self.push(block, pair, Op::CmpXchg(ptr, expected, new)); + self.extract(block, r, 0) + } + + pub fn set_phi(&mut self, phi: V, incoming: Vec<(V, usize)>) { + let V::Inst(i) = phi else { panic!() }; + self.insts[i as usize].op = Op::Phi(incoming); + } + pub fn terminate(&mut self, block: usize, t: Term) { + self.blocks[block].term = Some(t); + } + + pub fn md_str(&mut self, s: &str) -> Md { + self.mds.push(MdDef::Str(s.into())); + Md(self.mds.len() as u32 - 1) + } + pub fn md_value(&mut self, v: V) -> Md { + let ty = self.type_of(v); + self.mds.push(MdDef::Value(ty, v)); + Md(self.mds.len() as u32 - 1) + } + pub fn md_node(&mut self, ops: Vec<Option<Md>>) -> Md { + self.mds.push(MdDef::Node(ops)); + Md(self.mds.len() as u32 - 1) + } + pub fn named_md(&mut self, name: &str, nodes: Vec<Md>) { + self.named.push((name.into(), nodes)); + } + + /// The module as bitcode. + /// Which instructions are written: every body instruction, the branch + /// conditions, and whatever they read, transitively (a phi nothing reads + /// is dropped). A worklist visits each instruction once, so a long chain + /// of merges costs one pass, not one pass per merge. + fn live(&self) -> Vec<bool> { + let mut live = vec![false; self.insts.len()]; + let mut work: Vec<u32> = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec<u32>, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + work.push(i); + } + }; + for b in &self.blocks { + for &i in &b.body { + mark(&mut live, &mut work, V::Inst(i)); + } + if let Some(Term::CondBr(c, ..)) = b.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) + }); + } + live + } + + pub fn write(&self) -> Vec<u8> { + let mut w = Writer::default(); + w.bytes(b"BC\xC0\xDE"); + w.enter(MODULE_BLOCK, 3); + w.record(1, &[1]); // VERSION: relative value ids + + // Attribute groups 1-4 and one list per group. + w.enter(PARAMATTR_GROUP_BLOCK, 3); + for (id, kinds) in [ + (1, &[18u64, 20][..]), + (2, &[18]), + (3, &[18, 21]), + (4, &[12, 18]), + ] { + let mut r = vec![id, 0xFFFF_FFFF]; + for &k in kinds { + r.extend([0, k]); + } + w.record(3, &r); + } + w.exit(); + w.enter(PARAMATTR_BLOCK, 3); + for id in 1..=4 { + w.record(2, &[id]); + } + w.exit(); + + w.enter(TYPE_BLOCK, 4); + w.record(1, &[self.types.len() as u64]); + for t in &self.types { + match t { + TypeDef::Void => w.record(2, &[]), + TypeDef::Float => w.record(3, &[]), + 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)]), + TypeDef::Struct(name, fields) => { + let mut r = vec![0]; + r.extend(fields.iter().map(|f| u64::from(f.0))); + match name { + Some(n) => { + w.record(19, &chars(n)); + w.record(20, &r); + } + None => w.record(18, &r), + } + } + TypeDef::Func(ret, params) => { + let mut r = vec![0, u64::from(ret.0)]; + r.extend(params.iter().map(|p| u64::from(p.0))); + w.record(21, &r); + } + } + } + w.exit(); + + w.record(2, &chars("dxil-ms-dx")); + w.record( + 3, + &chars( + "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64", + ), + ); + let first_const = (self.globals.len() + self.funcs.len()) as u64; + for g in &self.globals { + // [type, address space << 2 | explicit type | constant, init id + // + 1, linkage (external 0, internal 3), log2 alignment + 1, + // section] + let (constant, init, linkage) = match g.init { + Some(i) => (1, first_const + u64::from(i) + 1, 3), + None => (0, 0, 0), + }; + w.record( + 7, + &[ + u64::from(g.ty.0), + u64::from(g.space) << 2 | 2 | constant, + init, + linkage, + 3, + 0, + ], + ); + } + for f in &self.funcs { + // [type, cc, isproto, linkage, paramattr, align, section, + // visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix] + let attr = f.attr.map_or(0, |a| a as u64); + w.record( + 8, + &[ + u64::from(f.ty.0), + 0, + u64::from(!f.body), + 0, + attr, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + ); + } + + // Value ids: globals, functions, constants, instructions. + let globals = self.globals.len() as u32; + let funcs = globals + self.funcs.len() as u32; + let const_id = |i: u32| u64::from(funcs + i); + w.enter(CONSTANTS_BLOCK, 4); + let mut current = None; + for (ty, c) in &self.consts { + if current != Some(*ty) { + w.record(1, &[u64::from(ty.0)]); + current = Some(*ty); + } + match c { + Const::Undef => w.record(3, &[]), + Const::Int(v) => w.record(4, &[signed(*v)]), + Const::Float(bits) => w.record(6, &[u64::from(*bits)]), + Const::Aggregate(ids) => { + let r: Vec<u64> = ids.iter().map(|&i| const_id(i)).collect(); + w.record(7, &r); + } + } + } + w.exit(); + + // Phis nothing reads are left out (one register per phi makes many). + let live = self.live(); + + // Blocks are laid out in reverse postorder, so every block follows + // its forward predecessors (drivers take a branch to an earlier + // block for a loop's back edge). + let succs = |b: usize| successors(self.blocks[b].term); + let mut seen = vec![false; self.blocks.len()]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in post.iter().enumerate() { + pos[b] = n as u64; + } + // An empty latch (only a branch back to its loop header) is folded + // into its one predecessor, so the exiting block is the latch as in + // DXC's loops; the AMD driver hangs on divergent loops otherwise. + let mut preds = vec![Vec::new(); self.blocks.len()]; + for &b in &post { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + let mut fold = vec![None; self.blocks.len()]; + for &b in &post { + let blk = &self.blocks[b]; + if let (Some(Term::Br(h)), true, [p]) = ( + blk.term, + blk.phis.is_empty() && blk.body.is_empty(), + &preds[b][..], + ) && pos[h] < pos[b] + && !succs(*p).contains(&h) + { + fold[b] = Some((*p, h)); + } + } + let layout: Vec<usize> = post.into_iter().filter(|&b| fold[b].is_none()).collect(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in layout.iter().enumerate() { + pos[b] = n as u64; + } + // Branch targets and phi blocks through folded latches. + let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]); + let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]); + + // Instruction value ids, in layout order. + let base = funcs + self.consts.len() as u32; + let mut ids = vec![u32::MAX; self.insts.len()]; + let mut next = base; + for b in layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + if !self.is_void(self.insts[i as usize].ty) { + ids[i as usize] = next; + next += 1; + } + } + } + let abs = |v: V| -> u32 { + match v { + V::Global(i) => i, + V::Func(i) => globals + i, + V::Const(i) => funcs + i, + V::Inst(i) => { + let id = ids[i as usize]; + assert_ne!(id, u32::MAX, "use of a void value"); + id + } + } + }; + + w.enter(METADATA_BLOCK, 3); + for m in &self.mds { + match m { + MdDef::Str(s) => w.record(1, &chars(s)), + MdDef::Value(ty, v) => w.record(2, &[u64::from(ty.0), u64::from(abs(*v))]), + MdDef::Node(ops) => { + let r: Vec<u64> = ops + .iter() + .map(|o| o.map_or(0, |m| u64::from(m.0) + 1)) + .collect(); + w.record(3, &r); + } + } + } + for (name, nodes) in &self.named { + w.record(4, &chars(name)); + let r: Vec<u64> = nodes.iter().map(|m| u64::from(m.0)).collect(); + w.record(10, &r); + } + w.exit(); + // The metadata kinds an LLVM 3.7 module declares, as DXC writes them. + w.enter(METADATA_BLOCK, 3); + for (id, kind) in [ + "dbg", + "tbaa", + "prof", + "fpmath", + "range", + "tbaa.struct", + "invariant.load", + "alias.scope", + "noalias", + "nontemporal", + "llvm.mem.parallel_loop_access", + "nonnull", + "dereferenceable", + "dereferenceable_or_null", + ] + .into_iter() + .enumerate() + { + let mut r = vec![id as u64]; + r.extend(chars(kind)); + w.record(6, &r); + } + w.exit(); + + w.enter(VALUE_SYMTAB_BLOCK, 4); + let names = self.globals.iter().map(|g| &g.name); + for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() { + let mut r = vec![i as u64]; + r.extend(chars(name)); + w.record(1, &r); + } + w.exit(); + + w.enter(FUNCTION_BLOCK, 4); + w.record(1, &[layout.len() as u64]); + let mut inst_id = base; + // The operands of variable-length records, reused across them. + let mut r: Vec<u64> = Vec::new(); + for b in layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + let inst = &self.insts[i as usize]; + let rel = |v: V| { + let a = abs(v); + assert!(a < inst_id, "forward reference outside a phi"); + u64::from(inst_id - a) + }; + match &inst.op { + Op::Bin(op, a, b) => w.record(2, &[rel(*a), rel(*b), *op as u64]), + Op::Cast(op, v) => w.record(3, &[rel(*v), u64::from(inst.ty.0), *op as u64]), + Op::Cmp(p, a, b) => w.record(28, &[rel(*a), rel(*b), u64::from(*p)]), + Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]), + Op::Call(f, args) => { + r.clear(); + r.extend([0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)]); + r.push(rel(V::Func(*f))); + r.extend(args.iter().map(|&a| rel(a))); + w.record(34, &r); + } + Op::Phi(incoming) => { + r.clear(); + r.push(u64::from(inst.ty.0)); + for &(v, b) in incoming { + r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); + r.push(from(b)); + } + w.record(16, &r); + } + Op::Gep(ty, p, idx) => { + r.clear(); + r.extend([0, u64::from(ty.0), rel(*p)]); + r.extend(idx.iter().map(|&i| rel(i))); + w.record(43, &r); + } + // Alignment 4 (log2 + 1), not volatile. + Op::Load(p) => w.record(20, &[rel(*p), u64::from(inst.ty.0), 3, 0]), + Op::Store(p, v) => w.record(44, &[rel(*p), rel(*v), 3, 0]), + // Sequentially consistent, across threads. + Op::AtomicRmw(op, p, v) => { + w.record(38, &[rel(*p), rel(*v), *op as u64, 0, 6, 1]) + } + Op::CmpXchg(p, c, n) => { + w.record(46, &[rel(*p), rel(*c), rel(*n), 0, 6, 1, 6, 0]); + } + } + if !self.is_void(inst.ty) { + inst_id += 1; + } + } + match b.term.expect("unterminated block") { + Term::Ret => w.record(10, &[]), + Term::Br(t) => w.record(11, &[target(t)]), + Term::CondBr(c, t, f) => { + let a = abs(c); + assert!(a < inst_id); + w.record(11, &[target(t), target(f), u64::from(inst_id - a)]); + } + } + } + w.exit(); + w.exit(); + w.finish() + } +} + +const MODULE_BLOCK: u64 = 8; +const PARAMATTR_BLOCK: u64 = 9; +const PARAMATTR_GROUP_BLOCK: u64 = 10; +const CONSTANTS_BLOCK: u64 = 11; +const FUNCTION_BLOCK: u64 = 12; +const VALUE_SYMTAB_BLOCK: u64 = 14; +const METADATA_BLOCK: u64 = 15; +const TYPE_BLOCK: u64 = 17; + +/// Calls `f` with every value `op` reads, in operand order. +fn for_each_operand(op: &Op, mut f: impl FnMut(V)) { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + f(*a); + f(*b); + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + f(*a); + f(*b); + f(*c); + } + Op::Call(_, args) => args.iter().copied().for_each(f), + Op::Phi(inc) => inc.iter().for_each(|x| f(x.0)), + Op::Gep(_, p, idx) => { + f(*p); + idx.iter().copied().for_each(f); + } + } +} + +/// A block's successors (at most two), without allocating. +struct Succs { + to: [usize; 2], + len: usize, +} + +impl std::ops::Deref for Succs { + type Target = [usize]; + fn deref(&self) -> &[usize] { + &self.to[..self.len] + } +} + +fn successors(term: Option<Term>) -> Succs { + match term { + Some(Term::Br(t)) => Succs { to: [t, 0], len: 1 }, + Some(Term::CondBr(_, t, f)) => Succs { to: [t, f], len: 2 }, + _ => Succs { to: [0, 0], len: 0 }, + } +} + +fn chars(s: &str) -> Vec<u64> { + s.bytes().map(u64::from).collect() +} + +/// LLVM's signed VBR operand: magnitude shifted left, sign in bit 0. +fn signed(v: i64) -> u64 { + if v >= 0 { + (v as u64) << 1 + } else { + (v.unsigned_abs() << 1) | 1 + } +} + +/// The bitstream: little-endian 32-bit words filled from bit 0. +#[derive(Default)] +struct Writer { + words: Vec<u32>, + cur: u64, + bits: u32, + /// Per open block: abbreviation width, index of its length word. + stack: Vec<(u32, usize)>, +} + +impl Writer { + fn width(&self) -> u32 { + self.stack.last().map_or(2, |b| b.0) + } + + fn emit(&mut self, v: u64, width: u32) { + debug_assert!(width == 64 || v >> width == 0); + self.cur |= v << self.bits; + self.bits += width; + while self.bits >= 32 { + self.words.push(self.cur as u32); + self.cur >>= 32; + self.bits -= 32; + } + } + + fn vbr(&mut self, mut v: u64, width: u32) { + let hi = 1u64 << (width - 1); + while v >= hi { + self.emit(v & (hi - 1) | hi, width); + v >>= width - 1; + } + self.emit(v, width); + } + + fn align(&mut self) { + if self.bits > 0 { + self.words.push(self.cur as u32); + self.cur = 0; + self.bits = 0; + } + } + + fn bytes(&mut self, b: &[u8]) { + for &x in b { + self.emit(u64::from(x), 8); + } + } + + fn enter(&mut self, id: u64, width: u32) { + self.emit(1, self.width()); // ENTER_SUBBLOCK + self.vbr(id, 8); + self.vbr(u64::from(width), 4); + self.align(); + self.words.push(0); + self.stack.push((width, self.words.len())); + } + + fn exit(&mut self) { + self.emit(0, self.width()); // END_BLOCK + self.align(); + let (_, start) = self.stack.pop().expect("open block"); + self.words[start - 1] = (self.words.len() - start) as u32; + } + + /// An unabbreviated record. + fn record(&mut self, code: u64, ops: &[u64]) { + self.emit(3, self.width()); + self.vbr(code, 6); + self.vbr(ops.len() as u64, 6); + for &o in ops { + self.vbr(o, 6); + } + } + + fn finish(mut self) -> Vec<u8> { + self.align(); + self.words.iter().flat_map(|w| w.to_le_bytes()).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vbr_and_blocks() { + let mut w = Writer::default(); + w.vbr(5, 6); + w.vbr(100, 6); // two chunks: 100 = 0b1100100 -> 0b100100 | 32, then 3 + assert_eq!(w.cur, 5 | (0b10_0100 << 6) | (3 << 12)); + let mut w = Writer::default(); + w.enter(8, 3); + w.record(1, &[1]); + w.exit(); + let bytes = w.finish(); + // header word, length word, one record word, end word. + assert_eq!(bytes.len() % 4, 0); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 1); + assert_eq!(signed(-3), 7); + assert_eq!(signed(2), 4); + } + + /// A structured shader's shape: `stages` if/else diamonds in a row, each + /// merge with one phi per register (as the lowering makes them), then a + /// loop, and a tail that reads only the first `read` registers. + fn synthetic(regs: usize, stages: usize, read: usize) -> Module { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t, i32t]); + let f = m.function("dx.op.synthetic", fty, Some(Attr::ReadNone), false); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let mut b = m.new_block(); + let mut cur: Vec<V> = (0..regs).map(|r| m.i32(r as u32)).collect(); + for s in 0..stages { + let c = m.cmp(b, pred::EQ, cur[0], cur[s % regs]); + let (t, e, j) = (m.new_block(), m.new_block(), m.new_block()); + m.terminate(b, Term::CondBr(c, t, e)); + let x = m.call(t, f, vec![cur[s % regs], cur[(s + 1) % regs]]); + m.terminate(t, Term::Br(j)); + m.terminate(e, Term::Br(j)); + cur = (0..regs) + .map(|r| { + let p = m.phi(j, i32t); + let tv = if r == s % regs { x } else { cur[r] }; + m.set_phi(p, vec![(tv, t), (cur[r], e)]); + p + }) + .collect(); + b = j; + } + // A loop: header phis fed back from an empty latch (which is folded). + let (head, body, latch, exit) = + (m.new_block(), m.new_block(), m.new_block(), m.new_block()); + m.terminate(b, Term::Br(head)); + let phis: Vec<V> = (0..regs).map(|_| m.phi(head, i32t)).collect(); + let one = m.i32(1); + let stepped: Vec<V> = phis + .iter() + .map(|&p| m.bin(body, Bin::Add, p, one)) + .collect(); + let c = m.cmp(body, pred::IULT, stepped[0], cur[0]); + m.terminate(head, Term::Br(body)); + m.terminate(body, Term::CondBr(c, latch, exit)); + m.terminate(latch, Term::Br(head)); + for r in 0..regs { + m.set_phi(phis[r], vec![(cur[r], b), (stepped[r], latch)]); + } + let mut acc = stepped[0]; + for &v in &stepped[1..read.max(1)] { + acc = m.bin(exit, Bin::Add, acc, v); + } + let _ = m.call(exit, f, vec![acc, cur[0]]); + m.terminate(exit, Term::Ret); + m + } + + /// FNV-1a, to pin a written module's exact bytes. + fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) + } + + /// Liveness as `write` computed it before the worklist: whole passes over + /// the instructions until one changes nothing. + fn live_by_passes(m: &Module) -> Vec<bool> { + let mut live = vec![false; m.insts.len()]; + for b in &m.blocks { + for &i in &b.body { + live[i as usize] = true; + } + if let Some(Term::CondBr(V::Inst(c), ..)) = b.term { + live[c as usize] = true; + } + } + let mut changed = true; + while changed { + changed = false; + for (i, inst) in m.insts.iter().enumerate() { + if live[i] { + for_each_operand(&inst.op, |v| { + if let V::Inst(j) = v + && !live[j as usize] + { + live[j as usize] = true; + changed = true; + } + }); + } + } + } + live + } + + #[test] + 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 live = m.live(); + assert_eq!(live, live_by_passes(&m), "{regs} regs x {stages} stages"); + } + } + + #[test] + fn unread_phis_are_dropped() { + let mut m = Module::default(); + let i32t = m.int(32); + let (entry, join) = (m.new_block(), m.new_block()); + let (a, b) = (m.i32(1), m.i32(2)); + m.terminate(entry, Term::Br(join)); + let read = m.phi(join, i32t); + let unread = m.phi(join, i32t); + // A cycle of phis that only feed each other stays dead. + let cyc_a = m.phi(join, i32t); + let cyc_b = m.phi(join, i32t); + m.set_phi(read, vec![(a, entry)]); + m.set_phi(unread, vec![(b, entry)]); + m.set_phi(cyc_a, vec![(cyc_b, entry)]); + m.set_phi(cyc_b, vec![(cyc_a, entry)]); + let sum = m.bin(join, Bin::Add, read, b); + m.terminate(join, Term::Ret); + let ids = |v: V| match v { + V::Inst(i) => i as usize, + _ => unreachable!(), + }; + 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 successors_of_each_terminator() { + assert!(successors(None).is_empty()); + assert!(successors(Some(Term::Ret)).is_empty()); + assert_eq!(&*successors(Some(Term::Br(7))), &[7]); + assert_eq!(&*successors(Some(Term::CondBr(V::Const(0), 3, 5))), &[3, 5]); + } + + /// The written bytes are pinned to what the writer produced before the + /// worklist and the reused record buffers. + #[test] + fn written_bytes_unchanged() { + for ((regs, stages, read), len, hash) in [ + ((64, 64, 64), 38_916, 0x9586_730c_f953_4a45), + ((128, 256, 32), 295_952, 0x89e5_de2d_64f0_8785), + ] { + let bytes = synthetic(regs, stages, read).write(); + assert_eq!((bytes.len(), fnv(&bytes)), (len, hash), "{regs}x{stages}"); + } + } + + #[test] + #[ignore = "benchmark: cargo test --release -p victory-shader bitcode -- --ignored --nocapture"] + fn bench_write() { + for (regs, stages, read) in [(64, 64, 64), (128, 256, 32), (256, 512, 256)] { + let m = synthetic(regs, stages, read); + let bytes = m.write(); + let runs = 5; + let t = std::time::Instant::now(); + for _ in 0..runs { + std::hint::black_box(m.write()); + } + let per = t.elapsed() / runs; + println!( + "write {regs} regs x {stages} stages ({} insts): {per:?}, {} bytes, fnv {:#018x}", + m.insts.len(), + bytes.len(), + fnv(&bytes) + ); + } + } +} 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 000000000..03eeccfd7 --- /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<Vec<(usize, u64, Census)>> = 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<bool> = 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<Census> { + 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<usize> = 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<Term> = 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 000000000..13551c371 --- /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<V>), + Gep(Ty, V, Vec<V>), + 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<usize>, + children: Vec<Vec<usize>>, + /// Per block: the reached blocks that branch to it, once per edge. + preds: Vec<Vec<usize>>, +} + +/// 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<V, bool>, + 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<V>, + 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<V>], 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<Effect> { + self.funcs.iter().map(effect).collect() + } + + /// The blocks reached from the entry. + pub(super) fn reached(&self) -> Vec<bool> { + 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<u32> { + 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<V> { + 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<Key> { + 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<Option<V>> = 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<Key, V> = HashMap::new(); + // The reads of the block being walked since its last store. + let mut read: HashMap<Key, V> = HashMap::new(); + let mut facts = Facts::default(); + let (yes, no) = (self.bool(true), self.bool(false)); + enum Step { + Enter(usize), + Leave(Vec<Key>, 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<Vec<(usize, V)>, 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<u32> = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec<u32>, 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<bool> = 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<bool> = 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<Vec<V>> { + 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<u64>)> { + let mut vals: Vec<Option<u64>> = vec![None; m.insts.len()]; + let mut memory = [0u64; 16]; + let mut trace = Vec::new(); + let eval = |vals: &[Option<u64>], 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<u64> = 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<V>, + conds: Vec<V>, + 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<V> = (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<Vec<u32>> = (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/container.rs b/crates/victory-shader/src/emit/container.rs new file mode 100644 index 000000000..3c346d9a6 --- /dev/null +++ b/crates/victory-shader/src/emit/container.rs @@ -0,0 +1,419 @@ +//! 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 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)] +pub(crate) struct SigElement { + pub name: String, + pub index: u32, + /// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...). + pub kind: u8, + /// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1). + pub comp: u8, + /// DXIL interpolation mode (0 for none). + pub interp: u8, + /// Start row, if the element has a register. + pub row: Option<u32>, + pub col: u8, + pub cols: u8, + /// Components read (inputs) or written (outputs), relative to `col`. + pub usage: u8, + /// 16-bit on the console (declared 32-bit here). + pub half: bool, +} + +impl SigElement { + fn system_value(&self) -> u32 { + match self.kind { + 1 => 6, // vertex id + 2 => 8, // instance id + 3 => 1, // position + 4 => 4, // render target array index + 5 => 5, // viewport array index + 6 => 2, // clip distance + 7 => 3, // cull distance + 10 => 7, // primitive id + 12 => 10, + 13 => 9, // front face + 14 => 66, + 15 => 70, + 16 => 64, // target + 17 => 65, // depth + 18 => 68, + 19 => 67, + 20 => 69, + 28 => 23, // barycentrics + 30 => 25, // cull primitive + _ => 0, + } + } + + fn sig_comp(&self) -> u32 { + match self.comp { + 1 | 5 => 1, // bool and u32 + 4 => 2, + 9 => 3, + _ => 0, + } + } + + fn mask(&self) -> u8 { + ((1u8 << self.cols) - 1) << self.col + } +} + +/// `ISG1`/`OSG1`: 32-byte rows, then the names. +pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> { + let mut out = Vec::new(); + out.extend((elements.len() as u32).to_le_bytes()); + out.extend(8u32.to_le_bytes()); + // 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). + let mut offsets: Vec<u32> = Vec::new(); + let mut next = 8 + 32 * elements.len() as u32; + let mut names = Vec::new(); + for (i, e) in elements.iter().enumerate() { + let shared = (e.kind != 0) + .then(|| (0..i).find(|&j| elements[j].kind == e.kind)) + .flatten(); + match shared { + Some(j) => offsets.push(offsets[j]), + None => { + offsets.push(next); + next += e.name.len() as u32 + 1; + names.push(&e.name); + } + } + } + let mut order: Vec<usize> = (0..elements.len()).collect(); + 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; + let rw = if input { used } else { !used & 0xf }; + for v in [ + 0, + offset, + e.index, + e.system_value(), + e.sig_comp(), + e.row.unwrap_or(u32::MAX), + ] { + out.extend(v.to_le_bytes()); + } + out.extend([e.mask(), rw, 0, 0]); + out.extend(0u32.to_le_bytes()); + } + for name in names { + out.extend(name.as_bytes()); + out.push(0); + } + out +} + +/// The most a mesh shader's outputs may take, in bytes (D3D12). +pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024; + +/// A mesh shader's output size as the DXIL validator measures it against +/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element +/// and primitive element, times the maxima rounded up to multiples of 32. +pub(crate) fn mesh_output_bytes( + vertex: &[SigElement], + primitive: &[SigElement], + max_vertices: u32, + max_primitives: u32, +) -> u64 { + let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::<u64>(); + let align = |n: u32| u64::from(n).next_multiple_of(32); + 4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives)) +} + +/// A resource bound by register, as `PSV0` lists it. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Binding { + /// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV. + pub kind: u32, + pub space: u32, + pub register: u32, + /// DXIL resource kind (13 cbuffer, 14 sampler). + pub dxil_kind: u32, +} + +pub(crate) struct Psv<'a> { + /// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute. + pub stage: u8, + /// Vertex: writes `SV_Position`. Pixel: writes depth. + pub flag: bool, + pub inputs: &'a [SigElement], + pub outputs: &'a [SigElement], + /// Mesh: per-primitive outputs. + pub prims: &'a [SigElement], + /// Mesh: its state and the group-shared bytes it declares. + pub mesh: Option<(super::shader::Mesh, u32)>, + /// Geometry (triangles in, triangle strips out on stream 0): its + /// maximum vertex count. `flag`: writes `SV_Position`. + pub geometry: Option<u32>, + pub bindings: &'a [Binding], + /// Compute: thread-group size and required wave size. + pub threads: [u32; 3], + pub wave_size: Option<u32>, +} + +/// `PSV0` with runtime info version 2 (validator 1.6). +pub(crate) fn psv(p: &Psv) -> Vec<u8> { + let vectors = |els: &[SigElement]| { + els.iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0) + }; + let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs)); + let mut out = Vec::new(); + let u32s = |out: &mut Vec<u8>, vs: &[u32]| { + for v in vs { + out.extend(v.to_le_bytes()); + } + }; + 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 + // sample index. + info[1] = u8::from( + p.inputs + .iter() + .any(|e| matches!(e.interp, 6 | 7) || e.kind == 12), + ); + } + let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n)); + info[16..20].copy_from_slice(&min.to_le_bytes()); + info[20..24].copy_from_slice(&max.to_le_bytes()); + info[24] = p.stage; + for (k, n) in p.threads.into_iter().enumerate() { + info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes()); + } + info[28] = p.inputs.len() as u8; + info[29] = p.outputs.len() as u8; + info[31] = in_vectors as u8; + info[32] = out_vectors as u8; + if let Some((mesh, shared)) = p.mesh { + info[0..4].copy_from_slice(&shared.to_le_bytes()); + info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes()); + info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes()); + info[26] = vectors(p.prims) as u8; + info[27] = mesh.topology; + info[30] = p.prims.len() as u8; + } + if let Some(max_vertices) = p.geometry { + // Input primitive (3: triangles), output topology (5: triangle + // strips), stream mask, position written; the vertex maximum. + info[0..4].copy_from_slice(&3u32.to_le_bytes()); + info[4..8].copy_from_slice(&5u32.to_le_bytes()); + info[8..12].copy_from_slice(&1u32.to_le_bytes()); + info[12] = u8::from(p.flag); + info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes()); + } + out.extend(info); + u32s(&mut out, &[p.bindings.len() as u32]); + if !p.bindings.is_empty() { + u32s(&mut out, &[24]); + for b in p.bindings { + u32s( + &mut out, + &[b.kind, b.space, b.register, b.register, b.dxil_kind, 0], + ); + } + } + // Names of arbitrary semantics (system values use ""), then indices. + let mut strings = vec![0u8]; + let mut indices: Vec<u32> = 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 needle: Vec<u8> = e.name.bytes().chain([0]).collect(); + match find(&strings, &needle) { + Some(at) => at, + None => { + strings.extend(&needle); + strings.len() - needle.len() + } + } + } else { + 0 + }; + let index = match indices.iter().position(|&i| i == e.index) { + Some(at) => at, + None => { + indices.push(e.index); + indices.len() - 1 + } + }; + let (start, alloc) = match e.row { + Some(r) => (r as u8, 0x40 | (e.col << 4)), + None => (0, 0), + }; + elements.push((name as u32, index as u32, start, e.cols | alloc, e)); + } + strings.resize(strings.len().next_multiple_of(4), 0); + u32s(&mut out, &[strings.len() as u32]); + out.extend(&strings); + u32s(&mut out, &[indices.len() as u32]); + u32s(&mut out, &indices); + if !elements.is_empty() { + u32s(&mut out, &[16]); + for (name, index, start, cols, e) in elements { + u32s(&mut out, &[name, index]); + out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]); + } + } + // Input-to-output dependencies, as the view-id state declares them: + // every output scalar on every input scalar. + if in_vectors > 0 && out_vectors > 0 { + let scalars = |els: &[SigElement]| { + els.iter() + .filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols))) + .max() + .unwrap_or(0) + }; + let (ni, no) = (scalars(p.inputs), scalars(p.outputs)); + let per = (out_vectors * 4).div_ceil(32); + for i in 0..in_vectors * 4 { + for k in 0..per { + let bits = if i < ni { + no.saturating_sub(32 * k).min(32) + } else { + 0 + }; + let mask = if bits == 32 { + u32::MAX + } else { + (1u32 << bits) - 1 + }; + u32s(&mut out, &[mask]); + } + } + } + out +} + +fn find(hay: &[u8], needle: &[u8]) -> Option<usize> { + hay.windows(needle.len()).position(|w| w == needle) +} + +/// The container: parts in order, hashed. +pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> { + let table = 0x20 + 4 * parts.len(); + let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>(); + let mut out = Vec::with_capacity(total); + out.extend(b"DXBC"); + out.extend([0; 16]); + out.extend(1u16.to_le_bytes()); + out.extend(0u16.to_le_bytes()); + out.extend((total as u32).to_le_bytes()); + out.extend((parts.len() as u32).to_le_bytes()); + let mut offset = table; + for (_, d) in parts { + out.extend((offset as u32).to_le_bytes()); + offset += 8 + d.len(); + } + for (fourcc, d) in parts { + out.extend(*fourcc); + out.extend((d.len() as u32).to_le_bytes()); + out.extend(*d); + } + let digest = hash(&out[20..]); + out[4..20].copy_from_slice(&digest); + out +} + +/// The container hash D3D12 checks: MD5 whose last block carries the bit +/// count first and `2 × bytes + 1` last instead of standard padding. +pub(crate) fn hash(data: &[u8]) -> [u8; 16] { + let len = data.len(); + let left = len % 64; + let mut tail = Vec::with_capacity(128); + if left < 56 { + tail.extend(((len as u32) << 3).to_le_bytes()); + tail.extend(&data[len - left..]); + tail.push(0x80); + tail.resize(60, 0); + } else { + tail.extend(&data[len - left..]); + tail.push(0x80); + tail.resize(64, 0); + tail.extend(((len as u32) << 3).to_le_bytes()); + tail.resize(124, 0); + } + tail.extend(((len as u32) << 1 | 1).to_le_bytes()); + let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476]; + for block in data[..len - left] + .as_chunks::<64>() + .0 + .iter() + .chain(tail.as_chunks::<64>().0) + { + md5_block(&mut state, block); + } + let mut out = [0; 16]; + for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) { + o.copy_from_slice(&s.to_le_bytes()); + } + out +} + +fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { + const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]; + let x: Vec<u32> = block + .as_chunks::<4>() + .0 + .iter() + .map(|c| u32::from_le_bytes(*c)) + .collect(); + let [mut a, mut b, mut c, mut d] = *state; + for i in 0..64 { + let (f, g) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32; + let rotated = a + .wrapping_add(f) + .wrapping_add(k) + .wrapping_add(x[g]) + .rotate_left(S[(i / 16) * 4 + i % 4]); + (a, b, c, d) = (d, b.wrapping_add(rotated), b, c); + } + for (s, v) in state.iter_mut().zip([a, b, c, d]) { + *s = s.wrapping_add(v); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn md5_core_matches_the_standard() { + // Standard MD5 of "abc" with standard padding, through md5_block. + let mut block = b"abc".to_vec(); + block.push(0x80); + block.resize(56, 0); + block.extend(24u64.to_le_bytes()); + let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476]; + md5_block(&mut state, block.as_slice().try_into().unwrap()); + let hex: String = state + .iter() + .flat_map(|s| s.to_le_bytes()) + .map(|b| format!("{b:02x}")) + .collect(); + assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72"); + } +} diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs new file mode 100644 index 000000000..fdc02aa11 --- /dev/null +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -0,0 +1,1287 @@ +//! Differential tests: HLSL compiled by the console's shader compiler and +//! translated, against the same HLSL compiled for PC, both drawn (or +//! dispatched) on the host GPU with the same inputs. +//! +//! Needs `VICTORY_CONSOLE_DXC` (the console SDK's `dxc.exe`) and a PC +//! `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's); skipped +//! without them. Set `VICTORY_WARP=1` to draw on WARP. + +use std::path::{Path, PathBuf}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::host::{Draw, Host, Root}; +use super::{HostShader, RootType, translate}; + +const RS: &str = "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), \ + RootConstants(num32BitConstants=4, b0), \ + DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), \ + StaticSampler(s1, filter=FILTER_MIN_MAG_MIP_POINT, \ + addressU=TEXTURE_ADDRESS_WRAP, addressV=TEXTURE_ADDRESS_MIRROR), \ + StaticSampler(s2, filter=FILTER_MIN_MAG_LINEAR_MIP_POINT, \ + addressU=TEXTURE_ADDRESS_BORDER, addressV=TEXTURE_ADDRESS_CLAMP, \ + borderColor=STATIC_BORDER_COLOR_OPAQUE_WHITE, mipLODBias=0.5)"; + +const COMMON: &str = r#" +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +SamplerState smp : register(s0); +struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float4 col : COLOR0; }; +[RootSignature(RS)] +V vs(float4 p : POSITION, float2 uv : TEXCOORD0) { + V o; + o.pos = p; + o.uv = uv; + o.col = float4(uv * k.xy, p.x * k.z, 1); + return o; +} +"#; + +/// Pixel shaders, each `ps`. +const CASES: &[(&str, &str)] = &[ + ( + "constant", + "[RootSignature(RS)] float4 ps(V i) : SV_Target { return float4(0.25, 0.5, 1, 0.75); }", + ), + ( + "interpolated", + "[RootSignature(RS)] float4 ps(V i) : SV_Target { return i.col * 2 - float4(i.uv, 0, 0); }", + ), + ( + "sample and branch", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + float4 t = tex.Sample(smp, i.uv); + float4 r = t * i.col + k.w; + if (i.uv.x > 0.5) r.xy = sin(r.yx * 3.0); + else r.z = rcp(r.z + 2.0); + return r; + }"#, + ), + // A wave-wide range scalarises a per-pixel loop (as the title's light + // lists do): the console's 64-lane sections become host wave operations; + // the result is the same for any wave the pixel lands in. + ( + "wave range", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint idx = uint(i.pos.x * 0.37 + i.pos.y * 0.21) & 15; + uint lo = WaveActiveMin(idx), hi = WaveActiveMax(idx); + float s = 0; + for (uint n = lo; n <= hi; n++) if (n == idx) s += n * k.x; + return float4(s, lo <= idx, hi >= idx, WaveActiveCountBits(true) > 0); + }"#, + ), + ( + "uniform loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + float s = 0; + for (uint n = 0; n < (asuint(k.x) & 7); n++) s += i.uv.y * n; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "bit loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = p.y; + for (uint n = 0; n < (p.x & 7); n++) s = (s ^ (s << 3)) + n; + return float4(s & 255, 0, 0, 1); + }"#, + ), + ( + "integer loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += n; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "discard", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + return i.col; + }"#, + ), + ( + "immediate samplers", + r#"SamplerState point_wrap : register(s1); + SamplerState linear_border : register(s2); + [RootSignature(RS)] float4 ps(V i) : SV_Target { + return tex.Sample(point_wrap, i.uv * 3 - 1) + 2 * tex.Sample(linear_border, i.uv * 2.5 - 0.7); + }"#, + ), + ( + "loop, discard and loads", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + float4 t = tex.Load(int3(p & 3, 0)); + return float4(s, frac(i.uv.x * 7.3), max(t.x, t.y) * k.y, sqrt(abs(i.col.x)) + exp2(i.uv.y)); + }"#, + ), + ( + "level of detail", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + return float4(tex.CalculateLevelOfDetail(smp, i.uv * 4), + tex.CalculateLevelOfDetailUnclamped(smp, i.uv * 7), 0, 1); + }"#, + ), + // 16-bit outputs and inputs (one value per dword with the 2020 + // compiler; Grand Theft Auto VI's two per dword cannot be compiled + // here) and the front face. + ( + "16-bit varyings and front face", + r#"struct V16 { float4 pos : SV_Position; half2 uv : TEXCOORD0; float4 col : COLOR0; half4 h : TEXCOORD1; }; + [RootSignature(RS)] V16 vs16(float4 p : POSITION, float2 uv : TEXCOORD0) { + V16 o; + o.pos = p; + o.uv = half2(uv * k.xy); + o.col = float4(uv, p.x * k.z, 1); + o.h = half4(uv.yx * 3 - 1, k.w, p.y); + return o; + } + [RootSignature(RS)] float4 ps(V16 i, bool f : SV_IsFrontFace) : SV_Target { + float4 c = i.col * float4(i.uv, i.h.xy) + float4(i.h.zw, 0, 0); + return f ? c : -c; + }"#, + ), +]; + +const CS_RS: &str = "RootConstants(num32BitConstants=4, b0), \ + DescriptorTable(SRV(t0, numDescriptors=4)), DescriptorTable(Sampler(s0)), \ + DescriptorTable(UAV(u0, numDescriptors=4)), CBV(b1), SRV(t4), \ + DescriptorTable(SRV(t0, space=2, numDescriptors=9)), \ +\ + StaticSampler(s3, filter=FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, \ + comparisonFunc=COMPARISON_LESS_EQUAL, \ + addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)"; + +const CS_COMMON: &str = r#" +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +Buffer<float4> typed : register(t1); +struct S { float a; uint b; float2 c; }; +StructuredBuffer<S> structured : register(t2); +ByteAddressBuffer raw : register(t3); +SamplerState smp : register(s0); +SamplerComparisonState cmp : register(s3); +RWByteAddressBuffer outb : register(u0); +RWTexture2D<float4> outt : register(u1); +cbuffer R : register(b1) { float4 table[16]; }; +ByteAddressBuffer rootraw : register(t4); +// `raw`'s bytes in typed views (the formats the console's typed loads name). +Buffer<float4> unorm8x4 : register(t0, space2); +Buffer<float4> snorm16x2 : register(t1, space2); +Buffer<uint4> uint8x4 : register(t2, space2); +Buffer<float4> unorm10x3_2 : register(t3, space2); +Buffer<uint4> uint16x4 : register(t4, space2); +Buffer<float> unorm8 : register(t5, space2); +Buffer<float> half16 : register(t6, space2); +Buffer<float4> snorm8x4 : register(t7, space2); +RWTexture2D<uint> ut : register(u2); +TextureCube cubet : register(t8, space2); +#define FMT(numeric, data) ((numeric) << 4 | (data)) +#define CS [RootSignature(RS)] [numthreads(8, 8, 1)] \ + void cs(uint3 g : SV_GroupID, uint3 t : SV_GroupThreadID, \ + uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) +"#; + +/// Compute shaders, each `cs`, dispatched as 2×2 groups of 8×8 threads +/// over a 16×16 texture and a 256-dword buffer. +const CS_CASES: &[(&str, &str)] = &[ + ( + "ids and stores", + r#"CS { + outb.Store(4 * (d.y * 16 + d.x), asuint(d.x * k.x + d.y)); + outt[d.xy] = float4(g.x, g.y, t.x, t.y + i); + }"#, + ), + ( + "shared memory and barrier", + r#"groupshared float lds[64]; + groupshared uint cnt; + CS { + if (i == 0) cnt = 0; + lds[i] = d.x * k.x + d.y; + GroupMemoryBarrierWithGroupSync(); + InterlockedAdd(cnt, i); + float v = lds[63 - i] + lds[(i + 9) & 63]; + GroupMemoryBarrierWithGroupSync(); + outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + outt[d.xy] = float4(v, cnt, 0, 1); + }"#, + ), + ( + "sample and divergent store", + r#"CS { + float4 s = tex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + if ((d.x ^ d.y) & 1) outt[d.xy] = s * k.y; + else outb.Store(4 * (d.y * 16 + d.x), asuint(s.x + s.w)); + }"#, + ), + ( + "buffers and root views", + r#"CS { + float4 a = typed[i & 15]; + S s = structured[(i * 3) & 7]; + uint r = raw.Load(4 * (i & 31)); + float4 c = table[d.x & 15]; + uint q = rootraw.Load(4 * ((i + 5) & 31)); + outb.Store(4 * (d.y * 16 + d.x), asuint(a.x + a.w * s.a) ^ s.b ^ r ^ q); + outt[d.xy] = c + float4(s.c, a.yz); + }"#, + ), + // (The 2020 compiler branches around every narrowed region, so these + // become branches, not guards.) + ( + "conditional memory access", + r#"CS { + float v = d.x * k.x + d.y; + if (i & 1) v = v * 3 + 1; + if (i & 4) v += tex.Load(int3(d.xy & 3, 0)).y; + if (i & 2) outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + if (i & 8) outt[d.xy] = float4(v, 0, 0, 1); + }"#, + ), + // Each side of a per-group branch leaves a compare in VCC; the select + // after the join reads the joined mask (as `postfx_splines` does). + ( + "select on joined compares", + r#"CS { + float v = d.x * k.x + d.y; + float r; + bool ok; + [branch] if ((g.x ^ g.y) & 1) { + r = sqrt(v) * k.z + sin(v * k.w); + ok = r < 5; + } else { + r = v * k.y + 1; + ok = r > -4; + } + float o = ok ? r : -1; + outb.Store(4 * (d.y * 16 + d.x), asuint(o)); + outt[d.xy] = float4(o, r, v, 1); + }"#, + ), + // One host wave of 32 lanes holds the group, as the console's wave of 64 + // does, so lane numbers agree with the PC compile. + ( + "lane reads", + r#"[RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID) { + float v = d.x * k.x + d.y; + float w = WaveReadLaneAt(v, 5); + uint lane = WaveGetLaneIndex(); + uint q = QuadReadAcrossX(lane * 10) + QuadReadAcrossDiagonal(lane); + outb.Store(4 * (d.y * 16 + d.x), q); + outt[d.xy] = float4(v, w, QuadReadAcrossY(v), lane); + }"#, + ), + // Bytes and halves: SDWA operand and result selection, byte permutes, + // f16 conversions. + ( + "sub-dword operations", + r#"CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + float a = float(x >> 16) + float((y >> 8) & 255) * k.x; + float b = f16tof32(x >> 16) + f16tof32(y); + uint p = (x & 0xff) | ((y & 0xff) << 8) | (x & 0xff0000) | ((y >> 8) << 24); + uint q = f32tof16(a) | (f32tof16(b) << 16); + int s = int(x << 24) >> 24; + uint u = (x & 0xffff) + (y >> 16) + ((x >> 24) ^ (y & 0xffff)) + asuint(k.w) * 1000 + 77; + outb.Store4(16 * n, uint4(asuint(a), asuint(b) ^ p, q, asuint(float(s)) + u)); + }"#, + ), + // 64-bit additions (VALU carries as lane masks) and explicit gradients. + ( + "carries and gradients", + r#"CS { + uint n = d.y * 16 + d.x; + uint64_t a = (uint64_t(raw.Load(4 * (n & 31))) << 32) | raw.Load(4 * ((n * 3) & 31)); + uint64_t b = (uint64_t(raw.Load(4 * ((n * 5) & 31))) << 32) | raw.Load(4 * ((n * 7) & 31)); + uint64_t s = a + b, u = a - b; + float4 gr = tex.SampleGrad(smp, (d.xy + 0.5) / 16.0, float2(k.x, 0) * 0.1, float2(0, k.z) * 0.1); + outb.Store4(16 * n, uint4(uint(s), uint(s >> 32) ^ uint(u), uint(u >> 32), asuint(gr.x + gr.y * 3))); + }"#, + ), + // Comparison sampling at level 0 with an immediate comparison sampler. + ( + "comparison sampling", + r#"CS { + float r = tex.SampleCmpLevelZero(cmp, (d.xy + 0.25) / 15.0, k.x * d.x / 16.0); + outb.Store(4 * (d.y * 16 + d.x), asuint(r)); + }"#, + ), + // 16-bit texture results, two channels per register (`d16`). + ( + "16-bit texture reads", + r#"Texture2D<half4> htex : register(t0); + CS { + half4 a = htex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + half3 b = htex.Load(int3(d.xy & 3, 0)).xyz; + outb.Store4(16 * (d.y * 16 + d.x), uint4(asuint(float(a.x) + a.w), + asuint(float(a.y) * a.z), asuint(float(b.x)), asuint(float(b.y) - b.z))); + }"#, + ), + // Sizes: the console compiler computes them from descriptor bits + // (width, height, levels, record counts). + ( + "sizes from descriptors", + r#"CS { + uint w, h, l, n, b, ns, st; + tex.GetDimensions(0, w, h, l); + typed.GetDimensions(n); + raw.GetDimensions(b); + structured.GetDimensions(ns, st); + // Read too: the translation takes the views' kinds from those reads. + float r = tex.Load(int3(d.xy & 3, 0)).x + typed[i & 15].y + structured[i & 7].a; + outb.Store4(16 * (d.y * 16 + d.x), + 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 + // 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. + ( + "typed loads", + r#"CS { + uint n = d.y * 16 + d.x, e = n & 31, f = n >> 5; + uint4 a, b, c, dd, ee, ff, gg, hh; + #ifdef CONSOLE + a = raw.XB_TypedLoad4(4 * e, FMT(0, 10)); + b = raw.XB_TypedLoad4(4 * e, FMT(1, 5)); + c = raw.XB_TypedLoad4(4 * e, FMT(4, 10)); + dd = raw.XB_TypedLoad4(4 * e, FMT(0, 9)); + ee = raw.XB_TypedLoad4(8 * (e & 15), FMT(4, 12)); + ff = uint4(raw.XB_TypedLoad((3 * e) & 127, FMT(0, 1)), 0, 0, 0); + gg = uint4(raw.XB_TypedLoad2(2 * e, FMT(7, 2)), 0, 0); + hh = raw.XB_TypedLoad4(4 * e, FMT(1, 10)); + #else + a = asuint(unorm8x4[e]); + b = asuint(snorm16x2[e]); + c = uint8x4[e]; + dd = asuint(unorm10x3_2[e]); + ee = uint16x4[e & 15]; + ff = uint4(asuint(unorm8[(3 * e) & 127]), 0, 0, 0); + gg = uint4(asuint(half16[e]), 0, 0, 0); + hh = asuint(snorm8x4[e]); + #endif + uint4 v = f == 0 ? a : f == 1 ? b : f == 2 ? c : f == 3 ? dd + : f == 4 ? ee : f == 5 ? ff : f == 6 ? gg : hh; + outb.Store4(16 * n, v); + }"#, + ), + // Wave operations: the console expands them into whole-wave sections + // (DPP, `v_permlanex16`, lane reads) and lane masks read as numbers + // (`s_bcnt1`, `s_ff1`, `v_mbcnt`). 32 threads: one wave on the console + // (lanes 32-63 inactive) and on the host; the branch leaves lanes out. + ( + "wave operations", + r#"[RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) { + uint n = d.y * 16 + d.x; + float v = d.x * k.x + d.y; + uint u = raw.Load(4 * (i & 31)); + uint4 o = 0; + if (u & 3) { + o.x = WaveActiveSum(u >> 8) + WaveActiveCountBits((u & 4) != 0); + o.y = asuint(WaveActiveMax(v)) ^ WaveActiveMin(u) ^ WaveActiveBitOr(u) + ^ WaveActiveBitAnd(u | 1) ^ asuint(WaveActiveMin(v)) ^ WaveActiveMax(int(u)); + o.z = WavePrefixSum(u & 255) + WavePrefixCountBits(v > 2) * 1000; + // (The PC compile evaluates a wave operation in a `?:` arm + // in that arm's lanes only, so it stays outside.) + o.w = asuint(WaveActiveSum(v)) + (WaveIsFirstLane() ? WaveReadLaneFirst(u) : 0); + } + outb.Store4(16 * n, o); + }"#, + ), + // Atomics the console aggregates per wave (one add of the lane count, + // each lane's offset from `v_mbcnt`), and texture atomics. Results + // that depend on the lanes' order are left out. + ( + "aggregated and texture atomics", + r#"CS { + uint u = raw.Load(4 * (i & 31)), r, q; + outb.InterlockedAdd(0, 1, r); + outb.InterlockedAdd(4 * (1 + r % 8), 1); + if (u & 1) outb.InterlockedAdd(64, u & 255); + uint2 p = d.xy & 3; + InterlockedMax(ut[p], u); + InterlockedOr(ut[p + uint2(4, 0)], u >> (i & 7)); + InterlockedMin(ut[p + uint2(8, 0)], u); + InterlockedAdd(ut[p + uint2(12, 0)], u & 15, q); + InterlockedXor(ut[p + uint2(0, 4)], u); + }"#, + ), + // A loop whose count comes from a view that reads zeros (as a null or + // not yet mirrored one does) runs four billion times on the console; + // the translation leaves it after `LOOP_LIMIT` iterations. Run on WARP + // only (`VICTORY_WARP=1`), ours only: without the limit it would hang + // the GPU. + ( + "terminates on zero data", + r#"CS { + uint cnt = outb.Load(4 * 1000), s = d.x; + for (uint j = 0; j != cnt - 1; j++) s = s * 3 + raw.Load(4 * (j & 31)); + outb.Store(4 * (d.y * 16 + d.x), s); + }"#, + ), + // Cube sampling: the console computes face coordinates (`v_cube*`) + // and samples the face; the host samples the direction rebuilt from + // them. Every face and texel: a major axis of ±2 and the others at + // texel centres, so both sides compute them exactly. + ( + "cube sampling", + r#"CS { + float sg = (i & 8) ? -2 : 2; + float a = (d.x & 3) - 1.5, b = (d.y & 3) - 1.5; + uint ax = i % 3; + float3 dir = ax == 0 ? float3(sg, a, b) : ax == 1 ? float3(a, sg, b) : float3(a, b, sg); + float4 p = cubet.SampleLevel(smp, dir, 0); + float4 q = cubet.SampleLevel(smp, -dir.zxy, 0); + outb.Store4(16 * (d.y * 16 + d.x), asuint(p + q * 3)); + }"#, + ), + // A local array indexed per lane (M0-relative VGPR moves), bit fields + // and first bits from the top. + ( + "indexed registers and bit fields", + r#"CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 5) & 31)); + uint arr[24]; + [unroll] for (uint j = 0; j < 24; j++) arr[j] = x ^ (j * 0x01010101); + [loop] for (uint m = 0; m < (y & 3); m++) arr[(y >> (m * 5)) % 24] = y + m; + uint v = arr[(x >> 3) % 24]; + uint w = asuint(k.x) & 31, o = n & 15; + uint bf = (x & ((1u << w) - 1)) << o; + uint fb = firstbithigh(asuint(k.y)) + firstbithigh(x) * 3 + firstbithigh(int(y)) * 7; + outb.Store4(16 * n, uint4(v, bf, fb, arr[n % 24])); + }"#, + ), + // Size queries at a level known per lane (`image_get_resinfo`). + ( + "size queries", + r#"CS { + uint w, h, l, cw, ch, cl; + tex.GetDimensions(d.x >> 4, w, h, l); + cubet.GetDimensions(d.y >> 4, cw, ch, cl); + float r = tex.Load(int3(d.xy & 3, 0)).x; + outb.Store4(16 * (d.y * 16 + d.x), uint4(w * 7 + h, l + asuint(r), cw * 3 + ch, cl)); + }"#, + ), + // Gathers with offsets computed per lane (programmable offsets). + ( + "gather with offsets", + r#"CS { + int2 o = int2(int(d.x & 7) - 4, int(d.y % 5) - 2); + float4 r = tex.GatherRed(smp, (d.xy + 0.5) / 16.0, o); + float4 q = tex.GatherGreen(smp, (d.yx + 0.25) / 16.0, -o); + outb.Store4(16 * (d.y * 16 + d.x), asuint(r + q * 3)); + }"#, + ), + // Constant arrays: the console compiler appends them to the code and + // reads them through `s_getpc_b64` (scalar loads for a uniform index, + // global loads per lane, 16-bit ones too). + ( + "constant tables", + r#"static const uint tbl[16] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3 }; + static const float ftbl[8] = { 0.5, -1, 2.25, 3, -4.5, 6, 7.75, -8 }; + // (16-bit types: compiled with half precision enabled.) + static const uint16_t stbl[12] = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 65535 }; + CS { + uint n = d.y * 16 + d.x; + uint u = asuint(k.x) & 15; + uint a = tbl[i & 15] ^ tbl[u] << 8; + float f = ftbl[(i * 3) & 7] * ftbl[u & 7]; + uint h = stbl[(n * 5) % 12] + stbl[u % 12]; + outb.Store4(16 * n, uint4(a, asuint(f), h, tbl[(n + u) & 15])); + }"#, + ), + // 16-bit arithmetic (scalar and packed), 16-bit compares, typed stores + // of halves (`buffer_store_format_d16`), 64-bit shifts and compares. + ( + "16-bit and 64-bit arithmetic", + r#"RWBuffer<half4> hb : register(u3); + CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + half a = half(d.x * k.x - 2), b = half(d.y + k.y), c = half(k.z); + half2 p = half2(a, b) * half2(b, c) + half2(c, a); + half m = max(a, b) - min(a, c) * a; + bool lt = a < b, ge = p.x >= p.y; + hb[n] = half4(p.x, m, lt ? a : b, ge ? p.y : a - b); + uint64_t q = (uint64_t(x) << (n & 31)) | y, w = uint64_t(y) << 3; + uint z = q < w ? 1 : q == w ? 2 : 3; + outb.Store2(8 * n, uint2(uint(q >> 7) ^ z, uint(w >> (n & 15)))); + }"#, + ), +]; + +const MS_COMMON: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0)" +cbuffer K : register(b0) { float4 k; }; +struct V { float4 pos : SV_Position; float4 col : COLOR0; float2 uv : TEXCOORD0; }; +[RootSignature(RS)] float4 mps(V i) : SV_Target { return i.col + float4(i.uv, 0, 0); } +#define MS_ATTR [RootSignature(RS)] [outputtopology("triangle")] +"#; + +/// Mesh shaders, each `ms` (the console runs one thread per output lane, so +/// groups of 32 run as 64 lanes there), with their group counts. Drawn +/// with `mps` into 16×16 targets. The 2020 compiler's containers do not +/// record the thread count, so cases reading the group id keep +/// max(threads, vertices, primitives) at the lane count (see `emit`). +const MS_CASES: &[(&str, u32, &str)] = &[ + ( + "one triangle", + 1, + r#"MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[3], out indices uint3 tris[1]) { + SetMeshOutputCounts(3, 1); + if (i < 3) { + verts[i].pos = float4(i == 1 ? 3 : -1, i == 2 ? 3 : -1, 0.5, 1); + verts[i].col = float4(k.x * i, k.y, k.z * (i == 2), 1); + verts[i].uv = float2(i * 0.5, k.w); + } + if (i == 0) tris[0] = uint3(0, 1, 2); + }"#, + ), + // A quad per group in its quadrant; a run-time vertex count, and a + // primitive count per group whose third triangle is culled. + ( + "groups, counts and culling", + 4, + r#"struct P { bool cull : SV_CullPrimitive; }; + MS_ATTR [numthreads(64, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[8], + out indices uint3 tris[4], out primitives P prims[4]) { + uint nv = 4 + (k.z > 1); + uint np = 2 + (g.x & 1); + SetMeshOutputCounts(nv, np); + float2 o = float2(g.x & 1, g.x >> 1) - 1; + if (i < nv) { + float2 p = i < 4 ? float2(i & 1, i >> 1) : float2(-0.75, 0.5); + verts[i].pos = float4(o + p, 0.5, 1); + verts[i].col = float4(k.x * i, g.x * 0.25, k.z, 1); + verts[i].uv = float2(i, g.x); + } + if (i < np) { + tris[i] = i == 0 ? uint3(0, 1, 2) : i == 1 ? uint3(1, 3, 2) : uint3(1, 4, 3); + prims[i].cull = i == 2; + } + }"#, + ), + // Two waves per group, as Grand Theft Auto VI's mesh programs run: the + // second wave's lanes are threads 64-127. + ( + "two waves", + 1, + r#"MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(p.x * k.x, p.y, (i & 7) * 0.125, 1); + verts[i].uv = float2(i, k.y); + } + uint c = i / 2 % 8 + i / 16 * 9; + 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 + // tessellating mesh programs swizzle within quads too). + ( + "quad reads", + 1, + r#"MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + float w = i * k.x + k.y; + float a = QuadReadLaneAt(w, 0); + float b = QuadReadLaneAt(w, 2); + float c = QuadReadAcrossX(w); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(a, b, c, 1); + verts[i].uv = float2(i, k.y); + } + uint cc = i / 2 % 8 + i / 16 * 9; + tris[i] = i & 1 ? uint3(cc + 1, cc + 10, cc + 9) : uint3(cc, cc + 1, cc + 9); + }"#, + ), + // Vertices and indices written by other threads than their lanes: the + // console passes them through shared memory, with a loop and barriers. + ( + "grid through shared memory", + 2, + r#"MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[36], + out indices uint3 tris[64]) { + SetMeshOutputCounts(36, 50); + for (uint v = i; v < 36; v += 32) { + float2 p = float2(v % 6, v / 6) / 5.0; + verts[v].pos = float4(p.x - g.x, p.y * 2 - 1, 0.5, 1); + verts[v].col = float4(p * k.x, k.z * g.x, 1); + verts[v].uv = float2(v, k.y); + } + if (i < 25) { + uint c = i % 5 + i / 5 * 6; + tris[2 * i] = uint3(c, c + 1, c + 6); + tris[2 * i + 1] = uint3(c + 1, c + 7, c + 6); + } + }"#, + ), +]; + +fn tools() -> Option<(PathBuf, PathBuf)> { + let console = PathBuf::from(std::env::var_os("VICTORY_CONSOLE_DXC")?); + let pc = match std::env::var_os("VICTORY_PC_DXC") { + Some(p) => PathBuf::from(p), + None => super::validator::Validator::default_path()?.with_file_name("dxc.exe"), + }; + (console.exists() && pc.exists()).then_some((console, pc)) +} + +fn compile(dxc: &Path, dir: &Path, src: &str, entry: &str, profile: &str) -> Vec<u8> { + let input = dir.join("t.hlsl"); + let output = dir.join(format!("{entry}.bin")); + let text = if entry == "cs" { + format!("#define RS \"{CS_RS}\"\n{CS_COMMON}\n{src}\n") + } else if entry.starts_with('m') { + format!("{MS_COMMON}\n{src}\n") + } else { + format!("#define RS \"{RS}\"\n{COMMON}\n{src}\n") + }; + std::fs::write(&input, text).unwrap(); + let out = std::process::Command::new(dxc) + .args(["-T", profile, "-E", entry, "-Fo"]) + .arg(&output) + .arg(&input) + .args(src.contains("half").then_some("-enable-16bit-types")) + // `CONSOLE` marks the console compile (cases spell console-only + // intrinsics there). + .args( + std::env::var_os("VICTORY_CONSOLE_DXC") + .is_some_and(|c| Path::new(&c) == dxc) + .then_some("-DCONSOLE"), + ) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + std::fs::read(output).unwrap() +} + +/// Root arguments for a translated stage: user data from the root values. +fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec<u32> { + let mut data = vec![0; (s.user_data_dwords() as usize).max(1)]; + for u in &s.user_data { + data[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => k[u.dword as usize], + // The texture and sampler tables start at heap index 1, the UAV + // table (compute) at 5, in the console's units. + (RootType::Table, 1) => 32, + (RootType::Table, 2) => 16, + (RootType::Table, 3) => 5 * 32, + // The typed views of `raw` (compute) from 9. + (RootType::Table, 6) => 9 * 32, + other => panic!("unexpected user data {other:?}"), + }; + } + data +} + +#[test] +fn translated_shaders_draw_as_pc_ones() { + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-diff-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let texels: Vec<[f32; 4]> = (0..16) + .map(|i| { + [ + i as f32 / 16.0, + (i % 4) as f32 * 0.3, + 1.0 - i as f32 / 20.0, + 0.5, + ] + }) + .collect(); + let dummy = [[9.0f32; 4]]; + let sampler = |filter, address| D3D12_SAMPLER_DESC { + Filter: filter, + AddressU: address, + AddressV: address, + AddressW: address, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }; + let samplers = [ + sampler( + D3D12_FILTER_MIN_MAG_MIP_POINT, + D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ), + sampler( + D3D12_FILTER_MIN_MAG_MIP_LINEAR, + D3D12_TEXTURE_ADDRESS_MODE_WRAP, + ), + ]; + // A full-screen triangle: POSITION (4 floats), TEXCOORD0 (2 floats). + let vertices = [ + -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, // + -1.0, 3.0, 0.5, 1.0, 0.0, -1.0, // + 3.0, -1.0, 0.5, 1.0, 2.0, 1.0, + ]; + let textures: [(u32, u32, &[[f32; 4]]); 2] = [(1, 1, &dummy), (4, 4, &texels)]; + let draw = |roots| Draw { + roots, + textures: &textures, + samplers: &samplers, + vertices: &vertices, + stride: 24, + size: (16, 16), + mesh_groups: 0, + }; + let mut failures = Vec::new(); + let only = std::env::var("VICTORY_DIFF_ONLY").ok(); + for (name, src) in CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + { + // A case may bring its own vertex shader. + let vs = if src.contains(" vs16(") { "vs16" } else { "vs" }; + let vs_c = translate(&compile(&console, &dir, src, vs, "vs_6_5")).unwrap(); + let ps_c = match translate(&compile(&console, &dir, src, "ps", "ps_6_5")) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write( + format!("{out}/{stem}.ps.cdxil"), + compile(&console, &dir, src, "ps", "ps_6_5"), + ) + .unwrap(); + std::fs::write(format!("{out}/{stem}.ps.dxil"), &ps_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + for s in [&vs_c, &ps_c] { + v.validate(&mut s.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + let (root_t, pso_t) = host.pipeline(&vs_c, &ps_c).unwrap(); + let ours = host + .draw( + &root_t, + &pso_t, + &draw(vec![ + (0, Root::Constants(user_data(&vs_c, &k))), + (1, Root::Constants(user_data(&ps_c, &k))), + ]), + ) + .unwrap(); + + let (vs_p, ps_p) = ( + compile(&pc, &dir, src, vs, "vs_6_5"), + compile(&pc, &dir, src, "ps", "ps_6_5"), + ); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &ps_p) }.unwrap(); + let pso_p = host.pipeline_with(&root_p, &vs_p, &ps_p).unwrap(); + let theirs = host + .draw( + &root_p, + &pso_p, + &draw(vec![ + (0, Root::Constants(k.to_vec())), + ( + 1, + Root::Table { + sampler: false, + index: 1, + }, + ), + ( + 2, + Root::Table { + sampler: true, + index: 1, + }, + ), + ]), + ) + .unwrap(); + + let worst = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b)) + .max_by(|x, y| x.0.total_cmp(&y.0)) + .unwrap(); + eprintln!( + "{name}: worst relative difference {:.2e} (at {}: {} vs {})", + worst.0, worst.1, worst.2, worst.3 + ); + if worst.0.is_nan() || worst.0 > 1e-3 { + failures.push(format!("{name}: {worst:?}")); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +#[test] +fn translated_mesh_shaders_draw_as_pc_ones() { + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-diff-ms-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let draw = |roots, mesh_groups| Draw { + roots, + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups, + }; + let mut failures = Vec::new(); + let only = std::env::var("VICTORY_DIFF_ONLY").ok(); + for &(name, groups, src) in MS_CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + { + let console_ms = compile(&console, &dir, src, "ms", "ms_6_5"); + let ms_c = match translate(&console_ms) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + let ps_c = translate(&compile(&console, &dir, src, "mps", "ps_6_5")).unwrap(); + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.ms.cdxil"), &console_ms).unwrap(); + std::fs::write(format!("{out}/{stem}.ms.dxil"), &ms_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut ms_c.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + let (root_t, pso_t) = host.mesh_pipeline(&ms_c, &ps_c).unwrap(); + let ours = host + .draw( + &root_t, + &pso_t, + &draw( + vec![ + (0, Root::Constants(user_data(&ms_c, &k))), + (1, Root::Constants(user_data(&ps_c, &k))), + ], + groups, + ), + ) + .unwrap(); + let (ms_p, ps_p) = ( + compile(&pc, &dir, src, "ms", "ms_6_5"), + compile(&pc, &dir, src, "mps", "ps_6_5"), + ); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &ms_p) }.unwrap(); + let pso_p = host.mesh_pipeline_with(&root_p, &ms_p, &ps_p).unwrap(); + let theirs = host + .draw( + &root_p, + &pso_p, + &draw(vec![(0, Root::Constants(k.to_vec()))], groups), + ) + .unwrap(); + let worst = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b)) + .max_by(|x, y| x.0.total_cmp(&y.0)) + .unwrap(); + let drawn = theirs.iter().filter(|t| t[3] != 0.0).count(); + eprintln!( + "{name}: {drawn} texels drawn; worst relative difference {:.2e} (at {}: {} vs {})", + worst.0, worst.1, worst.2, worst.3 + ); + if worst.0.is_nan() || worst.0 > 1e-3 || drawn == 0 { + // Which texels each drew (alpha set), row by row. + for (o, t) in ours.chunks(16).zip(theirs.chunks(16)) { + let row = |r: &[[f32; 4]]| -> String { + r.iter() + .map(|x| if x[3] != 0.0 { '#' } else { '.' }) + .collect() + }; + eprintln!(" {} {}", row(o), row(t)); + } + failures.push(format!("{name}: {worst:?}")); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// Where PC code and the console differ by design, the translation must +/// give the console's results: float-to-int conversions saturate and give +/// 0 for NaN (`v_cvt_i32/u32_f32`), the legacy multiply the compiler +/// uses for `*` gives 0 for 0 × NaN, `frac` never reaches 1.0 (it gives +/// the largest value below; some hosts' own `frac` gives 1.0), and sine +/// and cosine take turns: the sine of a half turn and the cosine of a +/// quarter turn are exactly +0 (the host's functions of the rounded angle +/// give about 1e-7). The compiler takes whole turns off itself, so large +/// angles cannot be tried from here. +#[test] +fn float_semantics_are_the_consoles() { + use super::host::{Dispatch, View}; + let Some((console, _)) = tools() else { + eprintln!("no console compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-float-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let src = r#"[RootSignature(RS)] [numthreads(4, 1, 1)] + void cs(uint i : SV_GroupIndex) { + float x = i == 0 ? k.x : i == 1 ? -k.x : i == 2 ? k.y : k.z; + outb.Store(4 * i, asuint(int(x))); + outb.Store(16 + 4 * i, uint(x)); + outb.Store(32 + 4 * i, asuint(x * k.w)); + float y = i == 0 ? k.w - 1e-10 : i == 1 ? k.z : i == 2 ? k.w - 1e-8 : k.z + 0.25; + outb.Store(48 + 4 * i, asuint(frac(y))); + float r = i == 0 ? k.w + 3.14159274 : i == 1 ? k.w + 1.0 + : i == 2 ? k.w - 3.14159274 : k.w + 1.57079637; + outb.Store(64 + 4 * i, asuint(i == 3 ? cos(r) : sin(r))); + }"#; + let cs = translate(&compile(&console, &dir, src, "cs", "cs_6_5")).unwrap(); + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + // 1e30, NaN, 3.5, 0. + let k = [1e30f32.to_bits(), 0x7FC0_0000, 3.5f32.to_bits(), 0]; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::RawUav(20), + View::TextureUav(1, 1), + ]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(user_data(&cs, &k)))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!( + out[0][..16], + [ + 0x7FFF_FFFF, + 0x8000_0000, + 0, + 3, // int + u32::MAX, + 0, + 0, + 3, // uint + 0, + 0, + 0, + 0, // x * 0, NaN included + 0x3F7F_FFFF, + 0.5f32.to_bits(), + 0x3F7F_FFFF, + 0.75f32.to_bits(), // frac + ] + ); + // sin(pi), sin(-pi) and cos(pi/2): the compiler turns radians into + // exactly 0.5, -0.5 and 0.25 turns. + assert_eq!([out[0][16], out[0][18], out[0][19]], [0, 0, 0]); + // An ordinary angle is untouched: sin(1 rad). + let one = f32::from_bits(out[0][17]); + assert!((one - 0.841_470_96).abs() < 1e-4, "{one}"); +} + +/// Equal bits, both zero (the console's legacy multiply gives +0 where PC +/// code gives -0), or two normal floats within 1e-3 relative. +fn close(a: u32, b: u32) -> bool { + let (x, y) = (f32::from_bits(a), f32::from_bits(b)); + a == b + || x == 0.0 && y == 0.0 + || x.is_normal() && y.is_normal() && (x - y).abs() <= 1e-3 * y.abs().max(1.0) +} + +#[test] +fn translated_compute_matches_pc() { + use super::host::{Dispatch, Stride, View}; + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-diff-cs-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let texels: Vec<[f32; 4]> = (0..16) + .map(|i| [i as f32 / 16.0, (i % 4) as f32 * 0.3, 0.5, 1.0]) + .collect(); + let dummy = [[9.0f32; 4]]; + let cube_texels: Vec<[f32; 4]> = (0..96) + .map(|i| { + [ + (i / 16) as f32, + (i % 4) as f32 * 0.25, + (i / 4 % 4) as f32 * 0.25, + 1.0, + ] + }) + .collect(); + // Buffers: 16 float4, 8 structures of 16 bytes, 32 raw dwords; the + // root CBV's 16 float4 and the root SRV's 32 dwords. + let floats = |n: usize, scale: f32| -> Vec<u32> { + (0..n).map(|i| (i as f32 * scale - 3.0).to_bits()).collect() + }; + let typed_data = floats(64, 0.25); + let structured_data: Vec<u32> = (0..32u32) + .map(|i| { + if i % 4 == 1 { + i * 0x0101_0101 + } else { + (i as f32 * 0.5).to_bits() + } + }) + .collect(); + let raw_data: Vec<u32> = (0..32u32).map(|i| i.wrapping_mul(0x9E37_79B9)).collect(); + let views = [ + View::Texture(1, 1, &dummy), + View::Texture(4, 4, &texels), + View::Buffer { + data: &typed_data, + stride: Stride::Typed, + }, + View::Buffer { + data: &structured_data, + stride: Stride::Structured(16), + }, + View::Buffer { + data: &raw_data, + stride: Stride::Raw, + }, + View::RawUav(1024), + View::TextureUav(16, 16), + View::UintTextureUav(16, 16), + View::HalfUav(256), + ]; + let typed_view = |format, bytes| View::Buffer { + data: &raw_data, + stride: Stride::Format(format, bytes), + }; + let views: Vec<View> = views + .into_iter() + .chain([ + typed_view(DXGI_FORMAT_R8G8B8A8_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16_SNORM, 4), + typed_view(DXGI_FORMAT_R8G8B8A8_UINT, 4), + typed_view(DXGI_FORMAT_R10G10B10A2_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16B16A16_UINT, 8), + typed_view(DXGI_FORMAT_R8_UNORM, 1), + typed_view(DXGI_FORMAT_R16_FLOAT, 2), + typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4), + View::Cube(4, &cube_texels), + ]) + .collect(); + let root_cbv = floats(64, -0.125); + let root_srv: Vec<u32> = (0..32u32).map(|i| i * 0x0001_0003 + 7).collect(); + 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() + }; 2]; + let dispatch = |roots| Dispatch { + roots, + views: &views, + samplers: &samplers, + groups: [2, 2, 1], + }; + let mut failures = Vec::new(); + let only = std::env::var("VICTORY_DIFF_ONLY").ok(); + let warp = std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1"); + for (name, src) in CS_CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + .filter(|c| warp || !c.0.starts_with("terminates")) + { + let console_cs = compile(&console, &dir, src, "cs", "cs_6_5"); + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.cs.cdxil"), &console_cs).unwrap(); + } + let cs_c = match translate(&console_cs) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.cs.dxil"), &cs_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut cs_c.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + let (root_t, pso_t) = match host.compute_pipeline(&cs_c) { + Ok(p) => p, + // WARP runs no fixed wave size of 64. + Err(e) if std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1") => { + eprintln!("{name}: skipped on WARP ({e})"); + continue; + } + Err(e) => panic!("{name}: {e}"), + }; + // Our root views follow the user data in root parameter order. + let mut roots = vec![(0, Root::Constants(user_data(&cs_c, &k)))]; + let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); + root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); + root_views.sort_unstable(); + for (n, (slot, srv)) in root_views.into_iter().enumerate() { + assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); + let data = if srv { + root_srv.clone() + } else { + root_cbv.clone() + }; + roots.push((1 + n as u32, Root::View { srv, data })); + } + let ours = host.dispatch(&root_t, &pso_t, &dispatch(roots)); + if name.starts_with("terminates") { + match ours { + Ok(_) => eprintln!("{name}: finished"), + Err(e) => failures.push(format!("{name}: {e}")), + } + continue; + } + let ours = ours.unwrap(); + let cs_p = compile(&pc, &dir, src, "cs", "cs_6_5"); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &cs_p) }.unwrap(); + let pso_p = host.compute_pipeline_with(&root_p, &cs_p).unwrap(); + let table = |sampler, index| Root::Table { sampler, index }; + let theirs = host + .dispatch( + &root_p, + &pso_p, + &dispatch(vec![ + (0, Root::Constants(k.to_vec())), + (1, table(false, 1)), + (2, table(true, 1)), + (3, table(false, 5)), + ( + 4, + Root::View { + srv: false, + data: root_cbv.clone(), + }, + ), + ( + 5, + Root::View { + srv: true, + data: root_srv.clone(), + }, + ), + (6, table(false, 9)), + ]), + ) + .unwrap(); + let mismatch = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .find(|(_, (a, b))| !close(**a, **b)); + match mismatch { + None => eprintln!("{name}: equal"), + Some((at, (a, b))) => failures.push(format!( + "{name}: word {at}: {a:#x} ({}) vs {b:#x} ({})", + f32::from_bits(*a), + f32::from_bits(*b) + )), + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs new file mode 100644 index 000000000..8f5407a97 --- /dev/null +++ b/crates/victory-shader/src/emit/host.rs @@ -0,0 +1,1453 @@ +//! Host D3D12 checks for emitted shaders: pipeline creation and, for +//! tests, drawing a full-screen triangle and reading the target back. + +use std::ffi::CString; + +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::{Interface, PCSTR}; + +use super::HostShader; +use super::container::SigElement; +use crate::dxbc::{Container, FourCC}; + +pub struct Host { + pub device: ID3D12Device, +} + +/// What the stage declares that a pipeline must match. +fn sig(dxil: &[u8], fourcc: FourCC) -> Result<Vec<SigElement>, String> { + let c = Container::parse(dxil).map_err(|e| e.to_string())?; + match c.part(fourcc) { + Some(p) => super::signature(p.data).map_err(|e| e.to_string()), + None => Ok(Vec::new()), + } +} + +fn format(e: &SigElement) -> DXGI_FORMAT { + let i = usize::from(e.cols.clamp(1, 4)) - 1; + match e.comp { + 9 => [ + DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R32G32B32A32_FLOAT, + ][i], + 4 => [ + DXGI_FORMAT_R32_SINT, + DXGI_FORMAT_R32G32_SINT, + DXGI_FORMAT_R32G32B32_SINT, + DXGI_FORMAT_R32G32B32A32_SINT, + ][i], + _ => [ + DXGI_FORMAT_R32_UINT, + DXGI_FORMAT_R32G32_UINT, + DXGI_FORMAT_R32G32B32_UINT, + DXGI_FORMAT_R32G32B32A32_UINT, + ][i], + } +} + +fn target_format(e: &SigElement) -> DXGI_FORMAT { + match e.comp { + 9 => DXGI_FORMAT_R32G32B32A32_FLOAT, + 4 => DXGI_FORMAT_R32G32B32A32_SINT, + _ => DXGI_FORMAT_R32G32B32A32_UINT, + } +} + +fn err(e: windows::core::Error) -> String { + e.message().to_string() +} + +impl Host { + /// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`). + pub fn new(warp: bool) -> Result<Self, String> { + let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1"); + // SAFETY: plain D3D12/DXGI calls with valid out pointers. + unsafe { + // `VICTORY_D3D12_DEBUG`: the debug layer, whose messages a + // refused pipeline's error then carries. + if std::env::var_os("VICTORY_D3D12_DEBUG").is_some() { + let mut debug: Option<ID3D12Debug> = None; + if D3D12GetDebugInterface(&mut debug).is_ok() + && let Some(debug) = debug + { + debug.EnableDebugLayer(); + } + } + let mut device: Option<ID3D12Device> = None; + if warp { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; + } else { + 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, + // whose first adapter is a display stub that cannot make a + // device): that is no hardware device, and the tests that + // ask for one skip it, as they do where there is none. + if let Some(made) = &device { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + if let Ok(adapter) = factory.EnumAdapterByLuid::<IDXGIAdapter1>(made.GetAdapterLuid()) + && let Ok(desc) = adapter.GetDesc1() + && (desc.Flags & 2 != 0 || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) + { + return Err("the default device is the software adapter".to_owned()); + } + } + } + let device = device.ok_or("no device")?; + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut sm).cast(), + size_of_val(&sm) as u32, + ) + .map_err(err)?; + if sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return Err(format!( + "the device supports SM {:#x} only", + sm.HighestShaderModel.0 + )); + } + Ok(Host { device }) + } + } + + /// The root signature translated shaders expect: user data per stage + /// at `b0`, immediate samplers per stage at `s<n>`, heaps directly + /// indexed. + pub fn root_signature( + &self, + vs: &HostShader, + ps: &HostShader, + ) -> Result<ID3D12RootSignature, String> { + self.root_signature_for(&[ + (vs, D3D12_SHADER_VISIBILITY_VERTEX), + (ps, D3D12_SHADER_VISIBILITY_PIXEL), + ]) + } + + /// The root signature for these stages: user data of stage k is root + /// parameter k, root views follow. + pub fn root_signature_for( + &self, + stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], + ) -> Result<ID3D12RootSignature, String> { + let mut params: Vec<D3D12_ROOT_PARAMETER1> = stages + .iter() + .map(|&(s, vis)| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: super::USER_DATA_SPACE, + Num32BitValues: s.user_data_dwords().max(1), + }, + }, + ShaderVisibility: vis, + }) + .collect(); + // By slot, then kind: 0 CBV, 1 SRV, 2 UAV. + let mut views: Vec<(u8, u8)> = stages + .iter() + .flat_map(|(s, _)| { + let cbvs = s.root_cbvs.iter().map(|&r| (r, 0)); + let srvs = s.root_srvs.iter().map(|&r| (r, 1)); + cbvs.chain(srvs).chain(s.root_uavs.iter().map(|&r| (r, 2))) + }) + .collect(); + views.sort_unstable(); + views.dedup(); + for (slot, kind) in views { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: match kind { + 1 => D3D12_ROOT_PARAMETER_TYPE_SRV, + 2 => D3D12_ROOT_PARAMETER_TYPE_UAV, + _ => D3D12_ROOT_PARAMETER_TYPE_CBV, + }, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: super::ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + let mut samplers = Vec::new(); + for &(s, vis) in stages { + for (n, d) in s.static_samplers.iter().enumerate() { + let [u, v, w] = d.address.map(|a| D3D12_TEXTURE_ADDRESS_MODE(a as i32)); + samplers.push(D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(d.filter as i32), + AddressU: u, + AddressV: v, + AddressW: w, + MipLODBias: d.mip_lod_bias, + MaxAnisotropy: d.max_anisotropy, + ComparisonFunc: D3D12_COMPARISON_FUNC(d.comparison as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(d.border as i32), + MinLOD: d.min_lod, + MaxLOD: d.max_lod, + ShaderRegister: n as u32, + RegisterSpace: super::SAMPLER_SPACE, + ShaderVisibility: vis, + }); + } + } + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: samplers.len() as u32, + pStaticSamplers: samplers.as_ptr(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + // SAFETY: the description points at live arrays. + unsafe { + let mut blob = None; + let mut error = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) + .map_err(err)?; + let blob: ID3DBlob = blob.ok_or("no root signature blob")?; + let bytes = std::slice::from_raw_parts( + blob.GetBufferPointer().cast::<u8>(), + blob.GetBufferSize(), + ); + self.device.CreateRootSignature(0, bytes).map_err(err) + } + } + + /// A compute pipeline; user data is root parameter 0. + pub fn compute_pipeline( + &self, + cs: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature_for(&[(cs, D3D12_SHADER_VISIBILITY_ALL)])?; + let pso = self.compute_pipeline_with(&root, &cs.dxil)?; + Ok((root, pso)) + } + + pub fn compute_pipeline_with( + &self, + root: &ID3D12RootSignature, + cs: &[u8], + ) -> Result<ID3D12PipelineState, String> { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the descriptor never releases. + pRootSignature: unsafe { std::mem::transmute_copy(root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }; + // SAFETY: the description points at live data. + unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(|e| self.explained(e)) + } + + /// The error with the debug layer's messages since the last call, if + /// the layer is on (`VICTORY_D3D12_DEBUG`). + fn explained(&self, e: windows::core::Error) -> String { + let mut text = err(e); + let Ok(queue) = self.device.cast::<ID3D12InfoQueue>() else { + return text; + }; + // SAFETY: each message is read into a buffer of the size the queue + // asks for, aligned for the message header. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut len = 0usize; + let _ = queue.GetMessage(i, None, &mut len); + let mut buffer = vec![0u64; len.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>(); + 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)); + text.push_str(" | "); + text.push_str(&String::from_utf8_lossy(bytes)); + } + } + queue.ClearStoredMessages(); + } + text + } + + /// A graphics pipeline from a vertex and a pixel shader, with float or + /// integer 32-bit targets as the pixel shader writes them. + pub fn pipeline( + &self, + vs: &HostShader, + ps: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature(vs, ps)?; + let pso = self.pipeline_with(&root, &vs.dxil, &ps.dxil)?; + Ok((root, pso)) + } + + /// A graphics pipeline with the given root signature; vertex inputs + /// packed in register order. + pub fn pipeline_with( + &self, + root: &ID3D12RootSignature, + vs: &[u8], + ps: &[u8], + ) -> Result<ID3D12PipelineState, String> { + self.pipeline_with_gs(root, vs, None, ps) + } + + /// As [`Host::pipeline_with`], with a geometry shader between the two + /// (the rectangle stage, `rect_list_gs`). + pub fn pipeline_with_gs( + &self, + root: &ID3D12RootSignature, + vs: &[u8], + gs: Option<&[u8]>, + ps: &[u8], + ) -> Result<ID3D12PipelineState, String> { + let inputs = sig(vs, FourCC::ISG1)?; + let names: Vec<CString> = inputs + .iter() + .map(|e| CString::new(e.name.clone()).unwrap()) + .collect(); + let layout: Vec<D3D12_INPUT_ELEMENT_DESC> = inputs + .iter() + .zip(&names) + .filter(|(e, _)| e.kind == 0) + .map(|(e, n)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(n.as_ptr().cast()), + SemanticIndex: e.index, + Format: format(e), + InputSlot: 0, + AlignedByteOffset: D3D12_APPEND_ALIGNED_ELEMENT, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }) + .collect(); + let outputs = sig(ps, FourCC::OSG1)?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the descriptor never releases. + pRootSignature: unsafe { std::mem::transmute_copy(root) }, + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + 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 { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: layout.as_ptr(), + NumElements: layout.len() as u32, + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + for rt in &mut desc.BlendState.RenderTarget { + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + } + for o in outputs.iter().filter(|o| o.kind == 16) { + let n = o.row.unwrap_or(0) as usize; + desc.RTVFormats[n] = target_format(o); + desc.NumRenderTargets = desc.NumRenderTargets.max(n as u32 + 1); + } + if outputs.iter().any(|o| matches!(o.kind, 17..=19)) { + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.DepthStencilState.DepthEnable = true.into(); + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + if outputs.iter().any(|o| o.kind == 20) { + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + desc.DepthStencilState.StencilEnable = true.into(); + } + // SAFETY: the description points at live data. + let pso = unsafe { self.device.CreateGraphicsPipelineState(&desc) }; + pso.map_err(err) + } + + /// A mesh pipeline from a mesh and a pixel shader (user data of the mesh + /// stage is root parameter 0, the pixel stage's 1). + pub fn mesh_pipeline( + &self, + ms: &HostShader, + ps: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature_for(&[ + (ms, D3D12_SHADER_VISIBILITY_MESH), + (ps, D3D12_SHADER_VISIBILITY_PIXEL), + ])?; + let pso = self.mesh_pipeline_with(&root, &ms.dxil, &ps.dxil)?; + Ok((root, pso)) + } + + /// A mesh pipeline with the given root signature: the pipeline-state + /// stream form, with the targets [`Host::pipeline_with`] would use. + pub fn mesh_pipeline_with( + &self, + root: &ID3D12RootSignature, + ms: &[u8], + ps: &[u8], + ) -> Result<ID3D12PipelineState, String> { + /// A stream subobject: its type, then its description, pointer-aligned. + #[repr(C, align(8))] + struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub<D3D12_SHADER_BYTECODE>, + ps: Sub<D3D12_SHADER_BYTECODE>, + blend: Sub<D3D12_BLEND_DESC>, + mask: Sub<u32>, + raster: Sub<D3D12_RASTERIZER_DESC>, + depth: Sub<D3D12_DEPTH_STENCIL_DESC>, + targets: Sub<D3D12_RT_FORMAT_ARRAY>, + dsv: Sub<DXGI_FORMAT>, + samples: Sub<DXGI_SAMPLE_DESC>, + } + let outputs = sig(ps, FourCC::OSG1)?; + let mut blend = D3D12_BLEND_DESC::default(); + for rt in &mut blend.RenderTarget { + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + } + let mut targets = D3D12_RT_FORMAT_ARRAY::default(); + for o in outputs.iter().filter(|o| o.kind == 16) { + let n = o.row.unwrap_or(0) as usize; + targets.RTFormats[n] = target_format(o); + targets.NumRenderTargets = targets.NumRenderTargets.max(n as u32 + 1); + } + let mut depth = D3D12_DEPTH_STENCIL_DESC::default(); + let mut dsv = DXGI_FORMAT_UNKNOWN; + if outputs.iter().any(|o| matches!(o.kind, 17..=19)) { + dsv = DXGI_FORMAT_D32_FLOAT; + depth.DepthEnable = true.into(); + depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + if outputs.iter().any(|o| o.kind == 20) { + dsv = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + depth.StencilEnable = true.into(); + } + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.as_ptr().cast(), + BytecodeLength: b.len(), + }; + let mut stream = Stream { + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(ms)), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(ps)), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, u32::MAX), + raster: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + ), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, depth), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + targets, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + dsv, + ), + samples: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::<Stream>(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let device: ID3D12Device2 = self.device.cast().map_err(err)?; + // SAFETY: the stream points at live data and outlives the call. + unsafe { device.CreatePipelineState(&desc) }.map_err(err) + } +} + +/// A vertex shader that feeds `ps`'s inputs (zeros) and a position. +pub fn stub_vs(ps: &HostShader) -> Result<HostShader, String> { + let inputs = sig(&ps.dxil, FourCC::ISG1)?; + let mut outputs: Vec<SigElement> = inputs + .into_iter() + .filter(|e| matches!(e.kind, 0 | 3 | 6 | 7)) + .collect(); + if !outputs.iter().any(|e| e.kind == 3) { + let row = outputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + outputs.push(SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: false, + }); + } + Ok(stub(false, outputs)) +} + +/// A pixel shader that reads nothing and writes target 0. +pub fn stub_ps() -> HostShader { + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }; + stub(true, vec![target]) +} + +fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(pixel); + let b = s.entry; + for (id, e) in outputs.iter().enumerate() { + for col in 0..e.cols { + let (suffix, zero) = if e.comp == 9 { + (".f32", s.m.f32(0)) + } else { + (".i32", s.m.i32(0)) + }; + let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(col), zero]; + s.op( + b, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &args, + ); + } + } + s.outputs = outputs + .into_iter() + .map(|mut e| { + e.usage = (1 << e.cols) - 1; + e + }) + .collect(); + s.m.terminate(b, Term::Ret); + HostShader { + stage: if pixel { + crate::native::HwStage::Ps + } else { + crate::native::HwStage::Vs + }, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + } +} + +/// A root argument for [`Host::draw`]. +#[cfg(test)] +pub enum Root { + Constants(Vec<u32>), + /// A table starting at this heap index. + Table { + sampler: bool, + index: usize, + }, + /// A root CBV (or with `srv`, a root SRV) over a buffer of these + /// dwords ([`Host::dispatch`] only). + View { + srv: bool, + data: Vec<u32>, + }, +} + +/// Bindings for [`Host::draw`]: root arguments and the heap contents. +#[cfg(test)] +pub struct Draw<'a> { + pub roots: Vec<(u32, Root)>, + /// RGBA32F textures (width, height, texels) at view-heap indices 0.. + pub textures: &'a [(u32, u32, &'a [[f32; 4]])], + /// Samplers at sampler-heap indices 0.. + pub samplers: &'a [D3D12_SAMPLER_DESC], + /// Three vertices of stride bytes (none for position-free layouts). + pub vertices: &'a [f32], + pub stride: u32, + pub size: (u32, u32), + /// Mesh thread groups to dispatch instead of drawing (0: draw). + pub mesh_groups: u32, +} + +#[cfg(test)] +impl Host { + /// Draws one triangle into an RGBA32F target and returns its texels. + pub fn draw( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Draw, + ) -> Result<Vec<[f32; 4]>, String> { + let dev = &self.device; + let (w, h) = d.size; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // are kept alive until the fence says the GPU is done. + 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, pso) + .map_err(err)?; + let tex_desc = |w: u32, h: u32, flags| 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: flags, + ..Default::default() + }; + let buf_desc = |size: u64| 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, + ..Default::default() + }; + let heap = |t| D3D12_HEAP_PROPERTIES { + Type: t, + ..Default::default() + }; + let make = |props: D3D12_HEAP_TYPE, + desc: &D3D12_RESOURCE_DESC, + state, + clear: Option<&D3D12_CLEAR_VALUE>| { + let mut r: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &heap(props), + 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(w, h, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + 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: d.textures.len().max(1) as u32, + 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: d.samplers.len().max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + let view_size = dev + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + let sampler_size = + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + let mut keep = Vec::new(); + for (i, &(tw, th, texels)) in d.textures.iter().enumerate() { + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &tex_desc(tw, th, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let pitch = (tw as usize * 16).next_multiple_of(256); + let upload = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc((pitch * th as usize) as u64), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(err)?; + for y in 0..th as usize { + let row = &texels[y * tw as usize..(y + 1) * tw as usize]; + std::ptr::copy_nonoverlapping( + row.as_ptr().cast::<u8>(), + p.cast::<u8>().add(y * pitch), + row.len() * 16, + ); + } + upload.Unmap(0, None); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&tex), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + 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: tw, + Height: th, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + dev.CreateShaderResourceView(&tex, None, at); + keep.push(tex); + keep.push(upload); + } + for (i, s) in d.samplers.iter().enumerate() { + let mut at = sampler_heap.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev.CreateSampler(s, at); + } + let vb = if d.vertices.is_empty() { + None + } else { + let bytes = d.vertices.len() * 4; + let vb = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc(bytes as u64), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + vb.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping( + d.vertices.as_ptr().cast::<u8>(), + p.cast::<u8>(), + bytes, + ); + vb.Unmap(0, None); + Some(vb) + }; + list.SetDescriptorHeaps(&[Some(views.clone()), Some(sampler_heap.clone())]); + list.SetGraphicsRootSignature(root); + for (param, arg) in &d.roots { + match arg { + Root::Constants(data) => list.SetGraphicsRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::Table { sampler, index } => { + let (heap, size) = if *sampler { + (&sampler_heap, sampler_size) + } else { + (&views, view_size) + }; + let mut at = heap.GetGPUDescriptorHandleForHeapStart(); + at.ptr += (index * size) as u64; + list.SetGraphicsRootDescriptorTable(*param, at); + } + Root::View { .. } => return Err("root views in a draw".into()), + } + } + 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); + if let Some(vb) = &vb { + list.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: vb.GetGPUVirtualAddress(), + SizeInBytes: (d.vertices.len() * 4) as u32, + StrideInBytes: d.stride, + }]), + ); + } + if d.mesh_groups > 0 { + let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(err)?; + list6.DispatchMesh(d.mesh_groups, 1, 1); + } else { + list.DrawInstanced(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_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 dev.GetDeviceRemovedReason().is_err() { + return Err(format!( + "device removed: {}", + err(dev.GetDeviceRemovedReason().unwrap_err()) + )); + } + 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::<u8>().add(y * pitch).cast::<[f32; 4]>(), + w as usize, + ); + out.extend_from_slice(row); + } + readback.Unmap(0, None); + drop(keep); + Ok(out) + } + } +} + +#[cfg(test)] +fn transition( + r: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(r) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// A view in the heap for [`Host::dispatch`]. +#[cfg(test)] +pub enum View<'a> { + /// An RGBA32F texture SRV (width, height, texels). + Texture(u32, u32, &'a [[f32; 4]]), + /// An RGBA32F cube SRV (face size, texels of faces +x -x +y -y +z -z). + Cube(u32, &'a [[f32; 4]]), + /// A raw buffer UAV of this many dwords, zeroed. + RawUav(u32), + /// An RGBA32F texture UAV (width, height), zeroed. + TextureUav(u32, u32), + /// An R32_UINT texture UAV (width, height), zeroed (atomics). + UintTextureUav(u32, u32), + /// A typed RGBA16F buffer UAV of this many elements, zeroed. + HalfUav(u32), + /// A constant buffer of these dwords. + Cbv(&'a [u32]), + /// A buffer SRV over these dwords. + Buffer { data: &'a [u32], stride: Stride }, +} + +/// How [`View::Buffer`] is viewed. +#[cfg(test)] +#[derive(Clone, Copy)] +pub enum Stride { + Raw, + /// RGBA32F elements. + Typed, + /// Structured, elements of this many bytes. + Structured(u32), + /// Typed, elements in this format of this many bytes. + Format(DXGI_FORMAT, u32), +} + +/// Bindings for [`Host::dispatch`]: root arguments, the view heap in order, +/// the sampler heap, and the group counts. +#[cfg(test)] +pub struct Dispatch<'a> { + pub roots: Vec<(u32, Root)>, + pub views: &'a [View<'a>], + pub samplers: &'a [D3D12_SAMPLER_DESC], + pub groups: [u32; 3], +} + +#[cfg(test)] +impl Host { + /// Runs a compute pipeline and returns each UAV's contents in heap + /// order (texels as float bits, row by row). + pub fn dispatch( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Dispatch, + ) -> Result<Vec<Vec<u32>>, String> { + let dev = &self.device; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // stay alive until the fence says the GPU is done. + 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, pso) + .map_err(err)?; + let make = |heap: D3D12_HEAP_TYPE, desc: &D3D12_RESOURCE_DESC, state| { + let mut r: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + desc, + state, + None, + &mut r, + ) + .map_err(err)?; + r.ok_or_else(|| "no resource".to_string()) + }; + let sample = DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }; + let texture_as = |w: u32, h: u32, flags, format| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(w), + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: sample, + Flags: flags, + ..Default::default() + }; + let texture = |w, h, flags| texture_as(w, h, flags, DXGI_FORMAT_R32G32B32A32_FLOAT); + let buffer = |size: u64, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: sample, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + // Texel words: 4 for RGBA32F, 1 for R32_UINT. + let footprint_as = + |r: &ID3D12Resource, w: u32, h: u32, words: u32| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(r), + 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: if words == 1 { + DXGI_FORMAT_R32_UINT + } else { + DXGI_FORMAT_R32G32B32A32_FLOAT + }, + Width: w, + Height: h, + Depth: 1, + RowPitch: (w * 4 * words).next_multiple_of(256), + }, + }, + }, + }; + let footprint = |r: &ID3D12Resource, w: u32, h: u32| footprint_as(r, w, h, 4); + let subresource = |r: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(r), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let heap = |ty, n: usize| -> Result<ID3D12DescriptorHeap, String> { + dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: ty, + NumDescriptors: n.max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err) + }; + // An upload buffer holding `data` (sized for a constant buffer). + let upload = |data: &[u32]| -> Result<ID3D12Resource, String> { + let size = (data.len() * 4).next_multiple_of(256); + let b = make( + D3D12_HEAP_TYPE_UPLOAD, + &buffer(size as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; + 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::<u32>(), data.len()); + b.Unmap(0, None); + Ok(b) + }; + let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, d.views.len())?; + let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, d.samplers.len())?; + let view_size = dev + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + let sampler_size = + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + let mut keep = Vec::new(); + // UAVs: (resource, dwords or texture size, readback buffer). + let mut uavs = Vec::new(); + for (i, v) in d.views.iter().enumerate() { + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + match *v { + View::Texture(..) | View::Cube(..) => { + let (w, h, texels, faces) = match *v { + View::Texture(w, h, t) => (w, h, t, 1), + View::Cube(n, t) => (n, n, t, 6), + _ => unreachable!(), + }; + let mut desc = texture(w, h, D3D12_RESOURCE_FLAG_NONE); + desc.DepthOrArraySize = faces as u16; + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + let pitch = (w as usize * 16).next_multiple_of(256); + for face in 0..faces as usize { + let upload = make( + D3D12_HEAP_TYPE_UPLOAD, + &buffer((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(err)?; + let texels = &texels[face * (w * h) as usize..]; + for y in 0..h as usize { + let row = &texels[y * w as usize..(y + 1) * w as usize]; + std::ptr::copy_nonoverlapping( + row.as_ptr().cast::<u8>(), + p.cast::<u8>().add(y * pitch), + row.len() * 16, + ); + } + upload.Unmap(0, None); + let mut at_face = subresource(&tex); + at_face.Anonymous.SubresourceIndex = face as u32; + list.CopyTextureRegion( + &at_face, + 0, + 0, + 0, + &footprint(&upload, w, h), + None, + ); + keep.push(upload); + } + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + let cube = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURECUBE, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + TextureCube: D3D12_TEXCUBE_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + dev.CreateShaderResourceView( + &tex, + (faces == 6).then_some(&cube as *const _), + at, + ); + keep.push(tex); + } + View::RawUav(_) | View::HalfUav(_) => { + // (dwords, format, elements, flags) + let (n, format, elements, flags) = match *v { + View::HalfUav(e) => ( + 2 * e, + DXGI_FORMAT_R16G16B16A16_FLOAT, + e, + D3D12_BUFFER_UAV_FLAG_NONE, + ), + View::RawUav(n) => { + (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) + } + _ => unreachable!(), + }; + let bytes = u64::from(n) * 4; + let b = make( + D3D12_HEAP_TYPE_DEFAULT, + &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + )?; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: elements, + Flags: flags, + ..Default::default() + }, + }, + }; + dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((b, None, n, rb)); + } + View::TextureUav(w, h) => { + let t = make( + D3D12_HEAP_TYPE_DEFAULT, + &texture(w, h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )?; + dev.CreateUnorderedAccessView(&t, None, None, at); + let pitch = (w * 16).next_multiple_of(256); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(u64::from(pitch * h), D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((t, Some((w, h)), 4, rb)); + } + View::UintTextureUav(w, h) => { + let t = make( + D3D12_HEAP_TYPE_DEFAULT, + &texture_as( + w, + h, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + DXGI_FORMAT_R32_UINT, + ), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )?; + dev.CreateUnorderedAccessView(&t, None, None, at); + let pitch = (w * 4).next_multiple_of(256); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(u64::from(pitch * h), D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((t, Some((w, h)), 1, rb)); + } + View::Cbv(data) => { + let b = upload(data)?; + dev.CreateConstantBufferView( + Some(&D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: b.GetGPUVirtualAddress(), + SizeInBytes: (data.len() * 4).next_multiple_of(256) as u32, + }), + at, + ); + keep.push(b); + } + View::Buffer { data, stride } => { + let b = upload(data)?; + let (format, elements, stride, flags) = match stride { + Stride::Raw => ( + DXGI_FORMAT_R32_TYPELESS, + data.len(), + 0, + D3D12_BUFFER_SRV_FLAG_RAW, + ), + Stride::Typed => ( + DXGI_FORMAT_R32G32B32A32_FLOAT, + data.len() / 4, + 0, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + Stride::Structured(s) => ( + DXGI_FORMAT_UNKNOWN, + data.len() * 4 / s as usize, + s, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + Stride::Format(f, bytes) => ( + f, + data.len() * 4 / bytes as usize, + 0, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 0, + NumElements: elements as u32, + StructureByteStride: stride, + Flags: flags, + }, + }, + }; + dev.CreateShaderResourceView(&b, Some(&desc), at); + keep.push(b); + } + } + } + for (i, s) in d.samplers.iter().enumerate() { + let mut at = samplers.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev.CreateSampler(s, at); + } + list.SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]); + list.SetComputeRootSignature(root); + for (param, arg) in &d.roots { + match arg { + Root::Constants(data) => list.SetComputeRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::Table { sampler, index } => { + let (h, size) = if *sampler { + (&samplers, sampler_size) + } else { + (&views, view_size) + }; + let mut at = h.GetGPUDescriptorHandleForHeapStart(); + at.ptr += (index * size) as u64; + list.SetComputeRootDescriptorTable(*param, at); + } + Root::View { srv, data } => { + let b = upload(data)?; + let va = b.GetGPUVirtualAddress(); + if *srv { + list.SetComputeRootShaderResourceView(*param, va); + } else { + list.SetComputeRootConstantBufferView(*param, va); + } + keep.push(b); + } + } + } + let [x, y, z] = d.groups; + list.Dispatch(x, y, z); + for (r, size, n, rb) in &uavs { + // (Buffers were promoted from the common state by the dispatch.) + list.ResourceBarrier(&[transition( + r, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + match size { + Some((w, h)) => list.CopyTextureRegion( + &footprint_as(rb, *w, *h, *n), + 0, + 0, + 0, + &subresource(r), + None, + ), + None => list.CopyBufferRegion(rb, 0, r, 0, u64::from(*n) * 4), + } + } + 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(); + } + let mut out = Vec::new(); + for (_, size, n, rb) in &uavs { + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(err)?; + let words = match size { + Some((w, h)) => { + let words = *n as usize; + let pitch = (*w as usize * 4 * words).next_multiple_of(256); + (0..*h as usize) + .flat_map(|y| { + std::slice::from_raw_parts( + p.cast::<u8>().add(y * pitch).cast::<u32>(), + *w as usize * words, + ) + .to_vec() + }) + .collect() + } + None => std::slice::from_raw_parts(p.cast::<u32>(), *n as usize).to_vec(), + }; + rb.Unmap(0, None); + out.push(words); + } + drop(keep); + Ok(out) + } + } +} diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs new file mode 100644 index 000000000..78a1d99ed --- /dev/null +++ b/crates/victory-shader/src/emit/intersect.rs @@ -0,0 +1,557 @@ +//! The console's ray-tracing node test, `image_bvh_intersect_ray` and +//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction +//! that tests one ray against one node of the title's own structures. +//! +//! [`crate::bvh`] says what the instruction computes and is the reference: +//! the code made here does the same float operations in the same order +//! (DXIL float operations carry no fast-math flags, so the host may not +//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on +//! the card against the reference. +//! +//! The title's nodes are in title memory, named by address: they are read +//! through the host's copies of title memory ([`Lower::memory`]), one look +//! in its directory per node (two for a 128-byte box node). +//! +//! Shape of the code, under the instruction's lane guard: +//! +//! ```text +//! kind = pointer & 7 +//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4); +//! four slab tests; the sorting network +//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test +//! other (6, 7): a triangle miss +//! ``` +//! +//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit +//! box node, 16 for a 16-bit one, 10 for a triangle. + +use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred}; +use crate::bvh; +use crate::resource::BvhNodes; + +#[cfg(test)] +thread_local! { + /// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a + /// heap slot holding a raw buffer, and the title address of its first + /// byte. (The card tests have no host to keep copies of title memory + /// and their directory.) + pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> = + const { std::cell::Cell::new(None) }; +} + +/// Where the instruction's node is. +#[derive(Clone, Copy)] +enum NodeAt { + /// At this byte of a raw buffer of the host. + Buffer { handle: V, byte: V }, + /// In title memory: the raw view of the host copy holding the node's + /// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]), + /// and the node's address, for the second half of a 128-byte node. + Memory { handle: V, byte: V, low: V, high: V }, +} + +/// The ray operands, as floats. +struct Ray { + extent: V, + origin: [V; 3], + direction: [V; 3], + inverse: [V; 3], +} + +impl<'a> Lower<'a> { + /// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`. + pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Image { + data, + addr, + rsrc, + dmask, + a16, + d16, + tfe, + lwe, + .. + } = &inst.fields + else { + unreachable!() + }; + if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf { + return Err("a ray-tracing node test with 16-bit operands or a partial result"); + } + let wide = inst.name() == "image_bvh64_intersect_ray"; + // Operand VGPRs in order: the node pointer (two dwords in the + // 64-bit form), the ray's extent, origin, direction and inverse + // direction. + let mut regs = Vec::new(); + for a in addr { + if let Operand::Vector { reg, dwords } = *a { + regs.extend((0..dwords).map(|k| reg + k)); + } + } + if regs.len() != if wide { 12 } else { 11 } { + return Err("a ray-tracing node test's operands"); + } + let Operand::Vector { reg: dst, .. } = *data else { + return Err("a ray-tracing node test's result"); + }; + let site = (b, i); + let nodes = self + .x + .res + .bvh + .iter() + .find(|n| n.0 == site) + .map(|n| n.1) + .ok_or("an untracked ray-tracing structure")?; + let (sort, barycentrics) = match nodes { + BvhNodes::Resource => (true, true), + BvhNodes::Memory { word1, word3 } => ( + word1 & bvh::BOX_SORT != 0, + word3 & bvh::RETURN_BARYCENTRICS != 0, + ), + }; + if !barycentrics { + // Mode 0 returns a triangle id and a hit status in the last two + // dwords; no program of the title asks for it. + return Err("a ray-tracing structure that returns triangle ids"); + } + let guard = self.guard(b, i)?; + let mut x = Vec::with_capacity(regs.len()); + for &r in ®s { + let v = inst.read(Reg::V(r)).ok_or("an unread operand")?; + x.push(self.i32_of(v)?); + } + let pointer = x[0]; + let pointer_high = wide.then(|| x[1]); + let f: Vec<V> = x[1 + usize::from(wide)..] + .iter() + .map(|&v| self.as_float(v)) + .collect(); + let ray = Ray { + extent: f[0], + origin: [f[1], f[2], f[3]], + direction: [f[4], f[5], f[6]], + inverse: [f[7], f[8], f[9]], + }; + let c = self.cur; + let at = match nodes { + BvhNodes::Resource => { + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked ray-tracing structure")?; + let handle = self.handle(site, src, false, (11, 0))?; + // (pointer >> 3) << 6 from the buffer's start. + let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3)); + let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits); + let byte = self.s.m.bin(c, Bin::Shl, byte, k3); + NodeAt::Buffer { handle, byte } + } + BvhNodes::Memory { .. } => { + let Operand::Scalar { code, .. } = *rsrc else { + return Err("a ray-tracing structure descriptor not in SGPRs"); + }; + let mut words = [pointer; 2]; + for (k, w) in words.iter_mut().enumerate() { + let v = inst + .read(Reg::S(code + k as u8)) + .ok_or("an unread operand")?; + *w = self.i32_of(v)?; + } + let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high); + // One look for the node's copy, before the branches: a + // node is 64 bytes on 64, so its first half lies in one + // 64 KiB page whatever its kind. + let (handle, byte) = self.bvh_memory(low, high, guard); + NodeAt::Memory { + handle, + byte, + low, + high, + } + } + }; + let zero = self.s.m.i32(0); + let gate = self.begin_guarded(guard); + let head = self.cur; + let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7)); + let kind = self.s.m.bin(head, Bin::And, pointer, k7); + let pair = self.s.m.bin(head, Bin::And, pointer, k6); + let is_box = self.s.m.cmp(head, pred::EQ, pair, k4); + let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4); + let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block()); + let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block()); + self.s + .m + .terminate(head, Term::CondBr(is_box, box_block, leaf_block)); + self.s + .m + .terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join)); + self.cur = box_block; + let boxes = self.bvh_boxes(at, kind, &ray, sort); + let box_end = self.cur; + self.s.m.terminate(box_end, Term::Br(join)); + self.cur = triangle_block; + let triangle = self.bvh_triangle(at, kind, &ray); + let triangle_end = self.cur; + self.s.m.terminate(triangle_end, Term::Br(join)); + self.cur = join; + // Kinds 6 and 7 (an instance, a procedural primitive): not known + // what the console returns; the title's programs do not read it. + let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits())); + let i32t = self.s.t.i32; + let mut results = Vec::with_capacity(4); + for k in 0..4 { + let phi = self.s.m.phi(join, i32t); + self.s.m.set_phi( + phi, + vec![ + (boxes[k], box_end), + (triangle[k], triangle_end), + (other[k], leaf_block), + ], + ); + results.push((phi, zero)); + } + let results = self.end_guarded(gate, &results); + for (k, &r) in results.iter().enumerate() { + self.write(inst, Reg::V(dst + k as u8), r, guard); + } + Ok(()) + } + + /// Title memory at `low`/`high` for a node's bytes: the raw view of the + /// host copy holding the address and the byte in that view + /// ([`Lower::memory`]: a page the host has no copy of reads zeros and + /// is left for the host to fetch, for lanes that run). + fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) { + #[cfg(test)] + if let Some((slot, base)) = TEST_MEMORY.get() { + // The buffer at heap slot `slot` holds the bytes from title + // address `base` on; any other address reads past its end, + // which is zeros. + let c = self.cur; + let slot = self.s.m.i32(slot); + let handle = self.s.heap_handle(c, slot, false, false, (11, 0)); + let (base_low, base_high) = + (self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32)); + let at = self.s.m.bin(c, Bin::Sub, low, base_low); + let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low); + let in_high = self.s.m.cmp(c, pred::EQ, high, base_high); + let inside = self.s.m.bin(c, Bin::And, in_low, in_high); + let outside = self.s.m.i32(0xffff_ff00); + let at = self.s.m.select(c, inside, at, outside); + return (handle, at); + } + self.memory(low, high, guard) + } + + /// `count` dwords of the node from its byte `base` + `offset` (`base` + /// computed, `offset` fixed; none of the node's bytes past 127), read + /// four at a time. + fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> { + let c = self.cur; + let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + // The second half of a 128-byte node may lie in the next 64 KiB + // page, which may be in another copy: its own look, made once. + let mut second = None; + let mut out = Vec::with_capacity(count as usize); + for start in (0..count).step_by(4) { + let n = (count - start).min(4); + let node_byte = offset + 4 * start; + let (handle, mut byte) = match at { + NodeAt::Buffer { handle, byte } => (handle, byte), + NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte), + NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| { + let (low, high) = self.address_plus(low, high, 64); + // Every lane in this block runs the instruction. + let (handle, byte) = self.bvh_memory(low, high, None); + let k64 = self.s.m.i32(64); + (handle, self.s.m.bin(c, Bin::Sub, byte, k64)) + }), + }; + if let Some(b) = base { + byte = self.s.m.bin(c, Bin::Add, byte, b); + } + let k = self.s.m.i32(node_byte); + let byte = self.s.m.bin(c, Bin::Add, byte, k); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[handle, byte, undef, mask, align], + ); + for k in 0..n { + let f = self.s.m.extract(c, r, k); + out.push(self.as_int(f)); + } + } + out + } + + /// The node's title address, [`bvh::node_address`]: the descriptor's + /// base (dword 0 and the low byte of dword 1, in 256-byte units) plus + /// `(pointer >> 3) << 6`. + fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) { + let c = self.cur; + let i64t = self.s.m.int(64); + let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff)); + let base_high = self.s.m.bin(c, Bin::And, word1, byte); + let base = self.join64(word0, base_high); + let k8 = self.s.m.int_const(i64t, 8); + let base = self.s.m.bin(c, Bin::Shl, base, k8); + let p = self.join64(pointer, pointer_high.unwrap_or(zero)); + let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6)); + let p = self.s.m.bin(c, Bin::LShr, p, k3); + let p = self.s.m.bin(c, Bin::Shl, p, k6); + let a = self.s.m.bin(c, Bin::Add, base, p); + self.s.flags |= flags::INT64; + self.split64(a) + } + + /// The box test ([`bvh::boxes`]): four result dwords. Starts in the + /// current block and leaves `self.cur` at the block it ends in. + fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] { + let head = self.cur; + let children = self.bvh_node_words(at, None, 0, 4); + let k5 = self.s.m.i32(5); + let wide = self.s.m.cmp(head, pred::EQ, kind, k5); + let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block()); + let join = self.s.m.new_block(); + self.s + .m + .terminate(head, Term::CondBr(wide, wide_block, half_block)); + // 32-bit floats: 24 dwords from byte 16. + self.cur = wide_block; + let k16 = self.s.m.i32(16); + let words = self.bvh_node_words(at, None, 16, 24); + let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect(); + self.s.m.terminate(wide_block, Term::Br(join)); + // 16-bit floats: 24 halves in 12 dwords from byte 16, the low half + // of a dword first. + self.cur = half_block; + let words = self.bvh_node_words(at, None, 16, 12); + let f32t = self.s.t.f32; + let mut halves = Vec::with_capacity(24); + for n in 0..24 { + let mut h = words[n / 2]; + if n % 2 == 1 { + h = self.s.m.bin(half_block, Bin::LShr, h, k16); + } + // The conversion reads the low 16 bits. + halves.push(self.s.op( + half_block, + "legacyF16ToF32", + Attr::ReadNone, + f32t, + 131, + &[h], + )); + } + self.s.m.terminate(half_block, Term::Br(join)); + self.cur = join; + let mut coords = Vec::with_capacity(24); + for n in 0..24 { + let phi = self.s.m.phi(join, f32t); + self.s + .m + .set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]); + coords.push(phi); + } + // The inverse direction held finite ([`bvh::boxes`]). + let (most, least) = ( + self.s.m.f32(f32::MAX.to_bits()), + self.s.m.f32((-f32::MAX).to_bits()), + ); + let inverse = ray.inverse.map(|x| { + let x = self.binary(35, x, least); + self.binary(36, x, most) + }); + let c = join; + let (none, infinity, fzero) = ( + self.s.m.i32(bvh::NONE), + self.s.m.f32(f32::INFINITY.to_bits()), + self.s.m.f32(0), + ); + let mut ids = [none; 4]; + let mut distances = [infinity; 4]; + for n in 0..4 { + let bx = &coords[6 * n..6 * n + 6]; + let (mut near, mut far) = ([fzero; 3], [fzero; 3]); + for a in 0..3 { + let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]); + let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]); + let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]); + let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]); + near[a] = self.binary(36, low, high); + far[a] = self.binary(35, low, high); + } + let enter = self.binary(35, near[0], near[1]); + let enter = self.binary(35, enter, near[2]); + let leave = self.binary(36, far[0], far[1]); + let leave = self.binary(36, leave, far[2]); + let from = self.binary(35, enter, fzero); + // Ordered compares: a NaN anywhere is a miss. + let through = self.s.m.cmp(c, pred::OGE, leave, from); + let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent); + let off = self.is_nan_f32(bx[0]); + let on = self.s.m.bool(true); + let on = self.s.m.bin(c, Bin::Xor, off, on); + let hit = self.s.m.bin(c, Bin::And, through, before); + let hit = self.s.m.bin(c, Bin::And, hit, on); + ids[n] = self.s.m.select(c, hit, children[n], none); + distances[n] = self.s.m.select(c, hit, enter, infinity); + } + if sort { + for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] { + let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]); + let (da, db) = (distances[a], distances[b]); + distances[a] = self.s.m.select(c, swap, db, da); + distances[b] = self.s.m.select(c, swap, da, db); + let (ia, ib) = (ids[a], ids[b]); + ids[a] = self.s.m.select(c, swap, ib, ia); + ids[b] = self.s.m.select(c, swap, ia, ib); + } + } + ids + } + + /// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]): + /// four result dwords, made in the current block. + fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + // The triangle's byte of the dword at byte 60: which of its + // vertices barycentric I and J weigh. + let id = self.bvh_node_words(at, None, 60, 1)[0]; + let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15)); + let shift = self.s.m.bin(c, Bin::Shl, kind, k3); + let id = self.s.m.bin(c, Bin::LShr, id, shift); + let i = self.s.m.bin(c, Bin::And, id, k3); + let j = self.s.m.bin(c, Bin::LShr, id, k2); + let j = self.s.m.bin(c, Bin::And, j, k3); + let first = self.s.m.bin(c, Bin::Sub, k3, i); + let first = self.s.m.bin(c, Bin::Sub, first, j); + let first = self.s.m.bin(c, Bin::And, first, k3); + // The node's vertices the triangle is made of, four bits each. + let (k0, k1) = (k(self, 0), k(self, 1)); + let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32))); + let (is0, is1, is2) = ( + self.s.m.cmp(c, pred::EQ, kind, k0), + self.s.m.cmp(c, pred::EQ, kind, k1), + self.s.m.cmp(c, pred::EQ, kind, k2), + ); + let map = self.s.m.select(c, is2, maps[2], maps[3]); + let map = self.s.m.select(c, is1, maps[1], map); + let map = self.s.m.select(c, is0, maps[0], map); + let mut p = Vec::with_capacity(3); + for n in [first, i, j] { + let nibble = self.s.m.bin(c, Bin::Shl, n, k2); + let vertex = self.s.m.bin(c, Bin::LShr, map, nibble); + let vertex = self.s.m.bin(c, Bin::And, vertex, k15); + let byte = self.s.m.bin(c, Bin::Mul, vertex, k12); + let words = self.bvh_node_words(at, Some(byte), 0, 3); + // Relative to the ray's origin. + let r: Vec<V> = (0..3) + .map(|a| { + let f = self.as_float(words[a]); + self.s.m.bin(c, Bin::Sub, f, ray.origin[a]) + }) + .collect(); + p.push([r[0], r[1], r[2]]); + } + // The ray's largest axis z, and x and y after it in an order that + // keeps the winding. + let fzero = self.s.m.f32(0); + let size = ray.direction.map(|d| self.unary(6, d)); + let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]); + let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]); + let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]); + let z0 = self.s.m.bin(c, Bin::And, xy, xz); + let on = self.s.m.bool(true); + let not_xy = self.s.m.bin(c, Bin::Xor, xy, on); + let z1 = self.s.m.bin(c, Bin::And, not_xy, yz); + // Component (kz + n) % 3 of `q`. + let pick = |l: &mut Self, q: [V; 3], n: usize| { + let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]); + l.s.m.select(c, z0, q[n % 3], rest) + }; + let dz = pick(self, ray.direction, 0); + let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero); + // (x, y, z) of `q`: the two after the largest axis, swapped for a + // ray that runs backwards along it. + let axes = |l: &mut Self, q: [V; 3]| { + let (x, y) = (pick(l, q, 1), pick(l, q, 2)); + [ + l.s.m.select(c, backwards, y, x), + l.s.m.select(c, backwards, x, y), + pick(l, q, 0), + ] + }; + let d = axes(self, ray.direction); + let sz = pick(self, ray.inverse, 0); + let sx = self.s.m.bin(c, Bin::Mul, d[0], sz); + let sy = self.s.m.bin(c, Bin::Mul, d[1], sz); + let mut sheared = Vec::with_capacity(3); + for r in p { + let r = axes(self, r); + let x = self.s.m.bin(c, Bin::Mul, sx, r[2]); + let x = self.s.m.bin(c, Bin::Sub, r[0], x); + let y = self.s.m.bin(c, Bin::Mul, sy, r[2]); + let y = self.s.m.bin(c, Bin::Sub, r[1], y); + let z = self.s.m.bin(c, Bin::Mul, sz, r[2]); + sheared.push((x, y, z)); + } + let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else { + unreachable!() + }; + // p * q - r * s. + let cross = |l: &mut Self, p: V, q: V, r: V, s: V| { + let a = l.s.m.bin(c, Bin::Mul, p, q); + let b = l.s.m.bin(c, Bin::Mul, r, s); + l.s.m.bin(c, Bin::Sub, a, b) + }; + let u = cross(self, cx, by, cy, bx); + let v = cross(self, ax, cy, ay, cx); + let w = cross(self, bx, ay, by, ax); + let any = |l: &mut Self, p: u8| { + let a = l.s.m.cmp(c, p, u, fzero); + let b = l.s.m.cmp(c, p, v, fzero); + let d = l.s.m.cmp(c, p, w, fzero); + let a = l.s.m.bin(c, Bin::Or, a, b); + l.s.m.bin(c, Bin::Or, a, d) + }; + let behind = any(self, pred::OLT); + let before = any(self, pred::OGT); + let outside = self.s.m.bin(c, Bin::And, behind, before); + let inside = self.s.m.bin(c, Bin::Xor, outside, on); + let det = self.s.m.bin(c, Bin::Add, v, w); + let det = self.s.m.bin(c, Bin::Add, u, det); + let t = self.s.m.bin(c, Bin::Mul, u, az); + let t2 = self.s.m.bin(c, Bin::Mul, v, bz); + let t = self.s.m.bin(c, Bin::Add, t, t2); + let t2 = self.s.m.bin(c, Bin::Mul, w, cz); + let t = self.s.m.bin(c, Bin::Add, t, t2); + // The distance is not negative: the numerator has the + // denominator's sign (or is 0). Ordered compares: a denominator + // of 0 or a NaN is a miss. + let front = self.s.m.cmp(c, pred::OGT, det, fzero); + let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero); + let front = self.s.m.bin(c, Bin::And, front, front_ahead); + let back = self.s.m.cmp(c, pred::OLT, det, fzero); + let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero); + let back = self.s.m.bin(c, Bin::And, back, back_ahead); + let ahead = self.s.m.bin(c, Bin::Or, front, back); + let hit = self.s.m.bin(c, Bin::And, inside, ahead); + let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits())); + let out = [t, det, v, w]; + std::array::from_fn(|n| { + let f = self.s.m.select(c, hit, out[n], miss[n]); + self.as_int(f) + }) + } +} diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs new file mode 100644 index 000000000..0266579ac --- /dev/null +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -0,0 +1,690 @@ +//! The ray-tracing node test end to end: a synthetic compute program that +//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread, +//! lowered to DXIL, validated by `dxil.dll` when present, run on the host +//! GPU and WARP, and compared dword for dword with the CPU reference +//! ([`crate::bvh`]). +//! +//! The nodes are in a raw buffer. Two ways to name it are run: the +//! buffer's descriptor from the program's table (a resource of the host, +//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a +//! descriptor of numbers over title memory with the structure's address in +//! the node pointer or in the descriptor. These tests have no host that +//! keeps copies of title memory and their directory, so for the second +//! they put a stand-in under the node reader +//! (`lower::intersect::TEST_MEMORY`); without it the same program reads +//! through the directory, which is only checked to lower and validate. + +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::lower::intersect::TEST_MEMORY; +use super::{HostShader, lower, validator}; +use crate::bvh::{self, Ray, tests as nodes}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::resource::BvhNodes; +use crate::{ShaderError, io, ir, resource, structure}; + +/// Threads of one group, each with its own record. +const THREADS: u32 = 32; +/// Bytes of a thread's record: the node pointer (two dwords), the ray's +/// extent, origin, direction and inverse direction, and whether the +/// thread runs the instruction. +const RECORD: u32 = 64; +/// Where the nodes start in the buffer. +const NODES: u32 = THREADS * RECORD; +/// What the result registers hold before the instruction. +const BEFORE: [u32; 4] = [1, 2, 3, 4]; + +/// How the program names the nodes' memory. +#[derive(Clone, Copy, PartialEq)] +enum Descriptor { + /// The buffer's descriptor from the table. + Table, + /// Numbers, as the title builds it: dwords 0 and 1 (the base address + /// in 256-byte units and the box sorting bit); the size and the rest of + /// the flags as the title sets them. + Numbers(u32, u32), +} + +/// The descriptor the title builds for the 64-bit form: the whole address +/// space, sorted boxes, barycentrics returned. +const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT); + +/// The program: per thread, the record's twelve operand dwords in v1-v12, +/// the instruction's result in v13-v16 (under a lane mask of the threads +/// whose record says so), stored to the UAV at 16 bytes a thread. +fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> { + let mut 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 + 0x3428_0086, // v_lshlrev_b32 v20, 6, v0 + 0xE038_1000, + 0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen + 0xE038_1010, + 0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16 + 0xE038_1020, + 0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32 + 0xE030_1030, + 0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48 + ]; + for k in 0..4u32 { + // v_mov_b32 v13+k, 1+k + w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k)); + } + let rsrc = match descriptor { + Descriptor::Table => 8, + Descriptor::Numbers(word0, word1) => { + // s_mov_b32 s24, word0 + w.extend([0xBE98_03FF, word0]); + if word1 == bvh::BOX_SORT { + // As the title makes it. + w.push(0xBE99_0B81); // s_brev_b32 s25, 1 + } else { + w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1 + } + w.extend([ + 0xBE9A_03C1, // s_mov_b32 s26, -1 + 0xBE9B_03FF, + 0x8900_03FF, // s_mov_b32 s27, 0x890003ff + ]); + 24 + } + }; + w.extend([ + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17 + ]); + let first = 0x0000_0D01 | (rsrc >> 2) << 16; + if wide { + // image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3] + w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]); + } else { + // image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3] + w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]); + } + w.extend([ + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0x342A_0084, // v_lshlrev_b32 v21, 4, v0 + 0xE078_1000, + 0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen + 0xBF81_0000, // s_endpgm + ]); + w +} + +fn native(words: &[u32]) -> NativeProgram { + 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, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 22, + 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: [THREADS, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// Lowers the program; the DXIL is validated when the validator is there. +fn build( + wide: bool, + descriptor: Descriptor, +) -> Result<(HostShader, resource::Resources), ShaderError> { + let native = native(&program(wide, descriptor)); + 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))?; + 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, + })?; + 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, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + }; + 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"); + } + Ok((shader, res)) +} + +/// One thread's test: a node (by its index in the node list), the kind its +/// pointer carries, and the ray; `None` leaves the thread masked out. +type Case = Option<(usize, u32, Ray)>; + +/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and +/// where each node starts, in dwords from the first node. +struct Scene { + words: Vec<u32>, + starts: Vec<usize>, +} + +impl Scene { + fn new() -> Self { + Self { + words: Vec::new(), + starts: Vec::new(), + } + } + + /// Adds a node of `dwords` (16 or 32) and returns its index. + fn add(&mut self, node: [u32; 28], dwords: usize) -> usize { + self.starts.push(self.words.len()); + let mut padded = [0u32; 32]; + padded[..28].copy_from_slice(&node); + // Bytes the instruction must not read as part of the node: what + // follows a 64-byte node, and a box node's last 16 bytes. + for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) { + *w = 0x7fc0_dead; + } + self.words.extend(&padded[..dwords]); + self.starts.len() - 1 + } + + /// The pointer of node `n` with `kind`, counted from the first node. + fn pointer(&self, n: usize, kind: u32) -> u32 { + (4 * self.starts[n] as u32) >> 3 | kind + } + + /// What the instruction reads of node `n`. + fn node(&self, n: usize) -> [u32; 28] { + std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0)) + } +} + +/// A small generator of repeatable numbers. +struct Numbers(u64); + +impl Numbers { + fn next(&mut self) -> u32 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 33) as u32 + } + + /// A float in -1..1 in steps of 1/4096 (exactly representable). + fn unit(&mut self) -> f32 { + (self.next() % 8193) as f32 / 4096.0 - 1.0 + } + + fn vector(&mut self, scale: f32) -> [f32; 3] { + [ + self.unit() * scale, + self.unit() * scale, + self.unit() * scale, + ] + } +} + +/// The scene and batches of cases over it. +fn scene() -> (Scene, Vec<Vec<Case>>) { + let mut s = Scene::new(); + let mut g = Numbers(0x5eed); + const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]; + let moved = + |b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) }; + let off = [f32::NAN; 6]; + let mut box_nodes = Vec::new(); + // The boxes of the reference's own tests, in both widths. + let lined = [ + moved(UNIT, [30.0, 0.0, 0.0]), + moved(UNIT, [10.0, 0.0, 0.0]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.0, 0.0, 0.0]), + ]; + let ids = [0x105, 0x20c, 0x304, 0x400]; + box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5)); + box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4)); + // Boxes around the origin, one switched off, one child missing. + let around = [ + UNIT, + moved(UNIT, [0.5, 0.5, 0.5]), + off, + [-4.0, -0.25, -0.25, 4.0, 0.25, 0.25], + ]; + let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc]; + box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5)); + box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4)); + // Random boxes. + for n in 0..6 { + let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| { + let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs)); + std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] }) + }); + let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5); + if n % 2 == 0 { + box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5)); + } else { + box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4)); + } + } + // Triangles: one of the reference's tests, a pair as the title's + // builder stores it, all four triangles of a full node with turned + // ids, random ones. + let mut triangle_nodes = Vec::new(); + let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]]; + triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0)); + let pair = s.add( + nodes::triangles( + &[front[0], front[1], front[2], [2.0, 2.0, 5.0]], + 9 | 0x80 | 6 << 8, + ), + 16, + ); + triangle_nodes.extend([(pair, 0), (pair, 1)]); + let five = [ + [-3.0, -1.0, 6.0], + [-1.0, 2.0, 6.5], + [1.0, -1.0, 6.0], + [3.0, 2.0, 6.5], + [5.0, -1.0, 7.0], + ]; + // I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2). + let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16); + triangle_nodes.extend((0..4).map(|k| (full, k))); + for _ in 0..5 { + let c = g.vector(6.0); + let v: [[f32; 3]; 3] = std::array::from_fn(|_| { + let d = g.vector(3.0); + [c[0] + d[0], c[1] + d[1], c[2] + d[2]] + }); + triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0)); + } + let mut cases: Vec<Case> = Vec::new(); + // Rays of the reference's tests against the lined-up boxes. + for &(n, kind) in &box_nodes[..2] { + for (origin, direction, extent) in [ + ([0.0; 3], [1.0, 0.0, 0.0], 1000.0), + ([0.0; 3], [1.0, 0.0, 0.0], 19.5), + ([0.0; 3], [1.0, 0.0, 0.0], 19.0), + ([0.0; 3], [-1.0, 0.0, 0.0], 1000.0), + ([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0), + ([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0), + ([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0), + ([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0), + ([0.0; 3], [0.0; 3], 1000.0), + ] { + cases.push(Some((n, kind, Ray::new(origin, direction, extent)))); + } + } + // Random rays at every box node, half of them aimed at a box. + for &(n, kind) in &box_nodes { + let words = s.node(n); + let boxes = if kind == 5 { + bvh::boxes32(&words) + } else { + bvh::boxes16(&words) + }; + for k in 0..12 { + let origin = g.vector(12.0); + let direction = if k % 2 == 0 { + let b = boxes[(k / 2) % 4]; + if b[0].is_nan() { + g.vector(1.0) + } else { + std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0) + } + } else { + g.vector(1.0) + }; + let extent = if k % 3 == 0 { 6.0 } else { 100.0 }; + cases.push(Some((n, kind, Ray::new(origin, direction, extent)))); + } + } + // Rays at every triangle: aimed inside, at an edge, at a vertex, past + // it, from both sides, along each axis. + for &(n, kind) in &triangle_nodes { + let p = bvh::triangle_vertices(&s.node(n), kind); + let at = |w: [f32; 3]| -> [f32; 3] { + std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a]) + }; + for (k, w) in [ + [0.5, 0.25, 0.25], + [0.125, 0.75, 0.125], + [0.5, 0.5, 0.0], + [0.0, 0.5, 0.5], + [1.0, 0.0, 0.0], + [0.75, 0.75, -0.5], + [-0.25, 0.5, 0.75], + [0.25, 0.25, 0.5], + ] + .into_iter() + .enumerate() + { + let target = at(w); + let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) }; + let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]); + if k == 7 { + // The triangle lies behind. + direction = direction.map(|d| -d); + } + cases.push(Some((n, kind, Ray::new(origin, direction, 100.0)))); + } + for axis in 0..3 { + for sign in [1.0f32, -1.0] { + let target = at([0.25, 0.5, 0.25]); + let mut origin = target; + origin[axis] -= 8.0 * sign; + let mut direction = [0.0; 3]; + direction[axis] = sign; + cases.push(Some((n, kind, Ray::new(origin, direction, 100.0)))); + } + } + } + // Kinds the instruction does not read, and threads masked out. + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + cases.extend([ + Some((triangle_nodes[0].0, 6, ray)), + Some((triangle_nodes[0].0, 7, ray)), + None, + Some(( + box_nodes[0].0, + 5, + Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0), + )), + None, + ]); + let batches = cases + .chunks(THREADS as usize) + .map(<[Case]>::to_vec) + .collect(); + (s, batches) +} + +/// The buffer for one batch: the threads' records, then the nodes. Node +/// pointers count from `base` before the first node, in bytes. +fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> { + let mut data = vec![0u32; (NODES / 4) as usize]; + for (t, case) in batch.iter().enumerate() { + let Some((n, kind, ray)) = case else { continue }; + let r = &mut data[t * (RECORD / 4) as usize..][..13]; + let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind)); + (r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32); + r[2] = ray.extent.to_bits(); + for a in 0..3 { + r[3 + a] = ray.origin[a].to_bits(); + r[6 + a] = ray.direction[a].to_bits(); + r[9 + a] = ray.inverse[a].to_bits(); + } + r[12] = 1; + } + data.extend(&scene.words); + data +} + +fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] { + match case { + Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort), + None => BEFORE, + } +} + +/// Sets the tests' title memory for this thread until dropped. +struct Memory; + +impl Memory { + fn at(base: u64) -> Self { + // Heap slot 0: the buffer of records and nodes. + TEST_MEMORY.set(Some((0, base))); + Self + } +} + +impl Drop for Memory { + fn drop(&mut self) { + TEST_MEMORY.set(None); + } +} + +/// Runs every batch on the hardware adapter and WARP and compares with +/// the reference. `pointers` is what node pointers count from, in bytes +/// before the first node. +fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) { + let (shader, res) = build(wide, descriptor).expect("the program lowers"); + assert_eq!(res.bvh.len(), 1); + let (scene, batches) = scene(); + // The reference must see a bit of everything, or the comparison + // proves little. + let all: Vec<&Case> = batches.iter().flatten().collect(); + let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect(); + let boxes = |hits: usize| { + all.iter() + .zip(&results) + .filter(|(c, r)| { + matches!(c, Some((_, 4 | 5, _))) + && r.iter().filter(|&&x| x != bvh::NONE).count() == hits + }) + .count() + }; + let triangles = |hit: bool| { + all.iter() + .zip(&results) + .filter(|(c, r)| { + matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit + }) + .count() + }; + assert!( + boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0, + "box cases" + ); + assert!( + triangles(true) > 30 && triangles(false) > 30, + "triangle cases" + ); + // Sorting must matter to some case, or the unsorted run proves nothing. + assert!( + all.iter() + .any(|c| expected(&scene, c, true) != expected(&scene, c, false)), + "no case tells sorted from unsorted" + ); + 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 (b, batch) in batches.iter().enumerate() { + let data = buffer(&scene, batch, pointers); + 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(4 * THREADS), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + for t in 0..THREADS as usize { + let case = batch.get(t).copied().flatten(); + let want = match batch.get(t) { + Some(c) => expected(&scene, c, sort), + // A thread past the batch: its record is zeros, so it + // is masked out. + None => BEFORE, + }; + let got = &out[0][4 * t..4 * t + 4]; + assert_eq!( + got, + want, + "{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}", + got, + got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(), + want, + want.map(f32::from_bits), + ); + } + } + ran += 1; + } + assert!(ran > 0, "no SM 6.6 device available"); +} + +#[test] +fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + // Pointers count from the buffer's start. + run(true, Descriptor::Table, u64::from(NODES), true); + assert_eq!( + build(true, Descriptor::Table).unwrap().1.bvh[0].1, + BvhNodes::Resource + ); +} + +#[test] +fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + run(false, Descriptor::Table, u64::from(NODES), true); +} + +/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes. +const BASE: u64 = 0x12_3456_7800; + +#[test] +fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's way: one descriptor for all of memory, the structure's + // address folded into a 64-bit pointer. + let _memory = Memory::at(BASE); + run(true, WHOLE, BASE + u64::from(NODES), true); +} + +#[test] +fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's other way: the structure's address in the descriptor + // (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with + // an address past 2^40 bytes, and without box sorting. + let base = 0x312_3456_7800u64; + let structure = base + u64::from(NODES); + let _memory = Memory::at(base); + let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32); + run(false, descriptor, 0, false); + // And sorted. + let descriptor = Descriptor::Numbers( + (structure >> 8) as u32, + (structure >> 40) as u32 | bvh::BOX_SORT, + ); + run(false, descriptor, 0, true); +} + +#[test] +fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() { + for wide in [true, false] { + let native = native(&program(wide, WHOLE)); + 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("tracked"); + // The flags the title sets: sorted boxes, barycentrics, a + // ray-tracing structure. No resource is taken for it: the buffer + // loads' and the store's descriptors are all there is. + assert_eq!(res.bvh.len(), 1); + assert_eq!( + res.bvh[0].1, + BvhNodes::Memory { + word1: 0x8000_0000, + word3: 0x8900_03ff + } + ); + assert_eq!(res.descriptors.len(), 5); + // Without the tests' stand-in the nodes are read as the title's + // programs will read them: through the host's directory of title + // memory. The program lowers and validates, and asks the host for + // the directory and for the list of pages it found no copy of. + let (shader, _) = build(wide, WHOLE).expect("lowers through the directory"); + assert!(shader.root_srvs.contains(&super::SLOT_MEMORY)); + assert!(shader.root_uavs.contains(&super::SLOT_FAULTS)); + } +} + +#[test] +fn a_structure_that_returns_triangle_ids_is_refused_by_name() { + // Triangle return mode 0 (bit 24 of dword 3 clear): the last two + // result dwords would be a triangle id and a hit status. + let mut words = program(true, WHOLE); + let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap(); + words[flags] = 0x8800_03FF; + let native = native(&words); + 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("tracked"); + let io = io::raise(&p, &native).expect("io::raise"); + let r = 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, + }); + match r { + Err(ShaderError::Unsupported { what, .. }) => { + assert_eq!(what, "a ray-tracing structure that returns triangle ids"); + } + other => panic!("{:?}", other.map(|_| ())), + } +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs new file mode 100644 index 000000000..dac5f2585 --- /dev/null +++ b/crates/victory-shader/src/emit/lower.rs @@ -0,0 +1,11475 @@ +//! IR to DXIL, one machine instruction at a time (decision 0003). +//! +//! Every register dword is an `i32` (SCC an `i1`); float operations bitcast +//! their operands. Lane masks exist only as the per-lane booleans of +//! structurisation; branches and guards are built from them. A value the +//! emitter cannot express is `Missing` with a reason, and only fails the +//! program when something with an effect (an export, a branch) needs it. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use super::UserData; +use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred}; +use super::container::SigElement; +use super::shader::{Shader, flags}; +use crate::ShaderError; +use crate::gfx10::{Dpp, Fields, NULL, Operand}; +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, LaneExit, Structured}; + +/// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so +/// it shares the emitter's state. +#[path = "intersect.rs"] +pub(super) mod intersect; + +type Why = &'static str; + +/// How an interpolation evaluates an input channel. +#[derive(Debug, Clone, Copy)] +enum Eval { + /// Loaded with this DXIL interpolation mode (1: constant, P0). + Mode(u8), + /// From the vertex values of a constant element: P0 when `p0`, plus + /// i (P1 - P0), plus j (P2 - P0), weights as floats. + Weights { + p0: bool, + i: Option<V>, + j: Option<V>, + }, +} + +#[derive(Debug, Clone, Copy)] +enum Val { + I32(V), + Bit(V), + Missing(Why), +} + +pub(crate) struct Lowered { + pub dxil: Vec<u8>, + /// Bit n: immediate sampler n is used for comparisons. + pub cmp_samplers: u64, + pub root_cbvs: Vec<u8>, + pub root_srvs: Vec<u8>, + pub root_uavs: Vec<u8>, + pub user_data: Vec<UserData>, + pub samplers: Vec<[u32; 4]>, + /// The wave size the shader requires of the host, if any. + pub wave_size: Option<u32>, + /// Heap handles made with a non-uniform index. + #[cfg(test)] + pub nonuniform_handles: u32, + /// Whether the program uses wave operations. + #[cfg(test)] + pub wave_ops: bool, +} + +pub(crate) struct Parts<'a> { + pub native: &'a NativeProgram, + pub p: &'a Program, + pub st: &'a Structured, + pub io: &'a Io, + pub res: &'a Resources, + pub inputs: Vec<SigElement>, + pub outputs: Vec<SigElement>, + pub prims: Vec<SigElement>, + /// Mesh: what the group id arrives multiplied by. + pub mesh_stride: u32, +} + +enum Stop { + /// A phi whose incoming value has no DXIL form was read: redo with it missing. + Retry(Value, Why), + Fail(ShaderError), +} + +pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> { + let mut bad = HashMap::new(); + loop { + match Lower::new(parts, &bad).run() { + Ok(l) => return Ok(l), + Err(Stop::Retry(v, why)) => { + if bad.insert(v, why).is_some() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a phi that does not settle", + }); + } + } + Err(Stop::Fail(e)) => return Err(e), + } + } +} + +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; + +/// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, +/// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)). +fn inline_f16(c: u8) -> u32 { + [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)] +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Numeric { + Unorm, + Snorm, + Uscaled, + Sscaled, + Uint, + Sint, + Float, +} + +/// A GFX10 buffer format (the unified format of typed buffer loads): the +/// channel widths from the lowest bits up, and how the channels convert. +/// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names +/// list channels from the highest bits), each with its numeric formats in +/// the order unorm, snorm, uscaled, sscaled, uint, sint, float. +fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> { + use Numeric::*; + const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint]; + const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float]; + const WIDE: &[Numeric] = &[Uint, Sint, Float]; + // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10 + // buffer formats have no 5_9_9_9. Channel order from Mesa + // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has + // its 2-bit channel in the lowest bits. + const FAMILIES: [(&[u32], &[Numeric]); 14] = [ + (&[8], NORM), + (&[16], ALL), + (&[8, 8], NORM), + (&[32], WIDE), + (&[16, 16], ALL), + (&[11, 11, 10], ALL), // 10_11_11 + (&[10, 11, 11], ALL), // 11_11_10 + (&[2, 10, 10, 10], NORM), // 10_10_10_2 + (&[10, 10, 10, 2], NORM), // 2_10_10_10 + (&[8, 8, 8, 8], NORM), + (&[32, 32], WIDE), + (&[16, 16, 16, 16], ALL), + (&[32, 32, 32], WIDE), + (&[32, 32, 32, 32], WIDE), + ]; + let mut n = usize::from(format.checked_sub(1)?); + for (bits, numerics) in FAMILIES { + if n < numerics.len() { + return Some((bits, numerics[n])); + } + n -= numerics.len(); + } + None +} + +/// How far a float channel of `width` bits (16, or the unsigned 11- and +/// 10-bit floats of the packed formats) shifts up to be a half: +/// the small floats are a half's exponent (5 bits, biased 15) and the top +/// of its mantissa, without the sign, so `legacyF16ToF32` widens them +/// exactly, denormals, infinities and NaNs included. +fn half_shift(width: u32) -> u32 { + debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float"); + if width == 16 { 0 } else { 15 - width } +} + +struct Lower<'a> { + s: Shader, + x: &'a Parts<'a>, + bad: &'a HashMap<Value, Why>, + lane_fail: HashMap<Value, Why>, + vals: HashMap<Value, Val>, + floats: HashMap<Value, V>, + /// DXIL block per IR block (unreachable: none). + block: Vec<Option<usize>>, + cur: usize, + bools: HashMap<(usize, Bool), V>, + lane_bits: HashMap<Value, V>, + /// IR phi location by value. + phi_at: HashMap<Value, (usize, usize)>, + /// Descriptor dwords with no host value (addresses, formats, all of a constant + /// buffer's): no program reads them as numbers ([`Self::dead`]). + stale: HashSet<Value>, + mask_phis: HashMap<Value, V>, + pending_masks: Vec<(V, usize, usize)>, + data_phis: Vec<(V, usize, usize)>, + read_phis: HashSet<Value>, + params: HashMap<Value, (usize, u32)>, + user_data: Option<V>, + user_reads: BTreeMap<u32, UserData>, + samplers: Vec<[u32; 4]>, + descriptors: HashMap<(Site, bool), &'a Source>, + scalar: HashMap<Site, Address>, + exports: HashMap<Site, &'a Export>, + interps: HashMap<Site, &'a Interp>, + 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>, + /// 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. + exported: Vec<bool>, + /// Reverse-postorder index per IR block. + rpo: Vec<usize>, + /// DXIL block each IR block ends in (guarded stores split blocks). + tail: Vec<Option<usize>>, + /// The program writes UAVs: barriers fence them too. + writes_uavs: bool, + /// src0 of the current instruction as DPP fetched it. + src0: Option<V>, + /// Compute code that reads other lanes: thread ids follow the host + /// lanes, so lane n is console lane n. + console_lanes: bool, + /// Mesh: the thread index in the group (made in the entry block). + flat: Option<V>, + /// Mesh: IR blocks whose `s_barrier` is left out. + no_barrier: HashSet<usize>, + /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane + /// branch lies between the entry and the block, or the program has a + /// loop a lane can be cut out of): the barrier there keeps its fences + /// and does not wait for the group ([`super::group_sync`]). + fence_only: HashSet<usize>, + /// A group barrier before every LDS access (a console wave run as two host waves). + 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`]). + lds_meet: Option<(Vec<bool>, 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 + /// IR block whether every lane runs it (exchanges need both halves there). + exchange: Option<(u32, bool, Vec<bool>)>, + /// With `exchange`: nothing is exchanged, each host wave acts as a wave + /// of its own ([`with_local_waves`]). + local: bool, + /// The instruction being lowered may read a lane mask as a number under + /// `local` (a bit count, a first set bit, `v_mbcnt`). + local_ok: bool, + /// With `local`: every mask read and lane read is taken per host wave + /// ([`with_local_waves_any`]). + local_any: bool, + /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane + /// read of one needs nothing from the other host wave. + uniform: HashSet<Value>, + /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which + /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]). + own_bits: super::own_bits::OwnBits, + /// The console lane (0..63) of this thread, made in the entry block. + clane: Option<V>, + /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]). + pair: Option<V>, + /// A console wave64 program in host waves of 32: the LDS dword counting the console threads + /// handed to host waves (`wave_base`), and the base made in the entry block. + halves: Option<u32>, + wave_base: Option<V>, + /// Vertex and mesh outputs holding 16-bit values: row, whether two per + /// dword, and the row packed after it. + half_outputs: HashMap<u8, (bool, Option<u8>)>, + /// How lane masks become data. + mask_data: MaskData, + /// The instruction being lowered may read lane masks as data. + mask_ok: bool, + /// Ballots of masks read as data, by low dword: (low, high). + ballots: HashMap<Value, (V, V)>, + /// 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. + balloting: HashSet<Value>, + /// Block writing each value. + def_block: HashMap<Value, usize>, + /// IR block being lowered. + cur_ir: usize, + /// Whole-wave sections by block and start index. + sections: HashMap<usize, HashMap<usize, super::wave::Section>>, + /// Values written in a section that code outside it reads. + section_out: HashSet<Value>, + /// The program's constant table (the code from the first byte read + /// through `s_getpc_b64` on): global, first byte, dwords. + code_table: Option<(V, u32, u32)>, + /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by + /// IR block, and its incoming (value, DXIL block) pairs. + counters: HashMap<usize, (V, Vec<(V, usize)>)>, + /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. + abort: Option<usize>, +} + +/// Iterations after which a loop is left (per entry into it), unless +/// [`super::loop_limit`] says otherwise. The console runs a loop as long as +/// its data says; data the host has not mirrored yet (a null view reads +/// zeros) can make that four billion iterations, which hangs the host GPU +/// 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. +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 +/// mask is written: structurisation's `active` masks hold only lanes that +/// reach that block, so the ballot misses none. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MaskData { + /// Compute: host lane n is console lane n (the program declares the + /// console's wave size), so ballots are the console's masks bit for bit + /// and any use is exact. + Console, + /// Pixel and vertex programs: ballots over the host's wave, whatever its + /// size. Only uses that mean the same on any wave are allowed: counts, + /// the first lane, the count below a lane, equality (the HLSL wave + /// operations the console compiler expands). Lane numbers stay host + /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane). + Host, + /// Mesh programs: their lanes and waves (LDS per console wave) are the + /// console's but no host wave size can be declared. + None, +} + +/// What a value holding a lane mask read as a number stops with. +pub(super) const LANE_MASK: Why = "a lane mask read as data"; +/// A mask with lanes outside EXEC where it is written, read as a number where the lanes that +/// run that block are not all of the wave. +pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; + +/// Instructions that read a lane mask (not EXEC implicitly, not a lane's +/// bit) as a number. +/// Per IR block: every lane of the wave that started the program runs it – no per-lane branch +/// separates it from the entry (it lies in no lane branch's region: the blocks reachable from +/// the branch that do not post-dominate it). None with an indirect exit (not followed). +fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> { + let n = st.exits.len(); + let mut all = vec![true; n]; + for (_, region) in lane_regions(st)? { + for b in (0..n).filter(|&b| region[b]) { + all[b] = false; + } + } + Some(all) +} + +/// Every per-lane branch (by its block) with its region: the blocks reachable from it that do +/// not post-dominate it, which only some lanes run. Not the branches the wave takes together +/// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit. +fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> { + let n = st.exits.len(); + let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n]; + for (b, e) in st.exits.iter().enumerate() { + match *e { + LaneExit::Jump(t) => succ[b].push(t), + LaneExit::Branch { taken, not_taken, .. } => { + succ[b].push(taken); + succ[b].push(not_taken); + } + LaneExit::End => {} + LaneExit::Indirect => return None, + } + } + // 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<Vec<u64>> = (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; + for b in (0..n).rev() { + if succ[b].is_empty() { + continue; + } + let mut v = full.clone(); + for &t in &succ[b] { + for w in 0..words { + v[w] &= pdom[t][w]; + } + } + v[b / 64] |= 1 << (b % 64); + if v != pdom[b] { + pdom[b] = v; + changed = true; + } + } + } + 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(_))) { + 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 + let mut seen = vec![false; n]; + let mut stack: Vec<usize> = succ[d].clone(); + while let Some(b) = stack.pop() { + if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 { + continue; + } + seen[b] = true; + stack.extend(succ[b].iter().copied()); + } + regions.push((d, seen)); + } + Some(regions) +} + +/// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two +/// host waves must meet, [`take_needs`]): the ones to take wave-wide +/// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one +/// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]). +pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> { + let mut out = Vec::new(); + for (d, region) in lane_regions(st)? { + if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) { + st.wave_any.get(d).copied().flatten()?; + out.push(d); + } + } + Some(out) +} + +/// Whether a refusal is of code that needs every lane of the wave where it stands (two host +/// waves meeting there), which the other forms of the program may give it. +pub(super) fn needs_every_lane(what: &str) -> bool { + what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE +} + +/// The blocks where the last lowering on this thread wanted every lane and did not have it +/// (its "... where not every lane runs" refusals), which it forgets. +pub(super) fn take_needs() -> Vec<usize> { + NEEDS.take() +} + +fn need(block: usize) { + NEEDS.with_borrow_mut(|n| { + if !n.contains(&block) { + n.push(block); + } + }); +} + +/// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]): +/// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, +/// constants and such values; or loaded from an address made of them. The compiler keeps +/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. +/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes +/// run (no lane branch can have split the arriving lanes); loop-carried values never do. +fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let mut same: HashSet<Value> = 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)); + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { + same.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + let ops: Vec<Operand> = match &inst.fields { + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && !name.starts_with("v_mbcnt") + && !name.starts_with("v_cmpx") + && !name.contains("lane") => + { + v.src.clone() + } + _ => continue, + }; + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } + 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<Value> = + 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)) + } + _ => true, + }); + if alike { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + } + } + } + same +} + +/// What a register value holds, for [`wave_local`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Wave { + /// Nothing that depends on how the threads are divided into waves. + Plain, + /// The number of the wave's first lane in a mask (`s_ff1`). + First, + /// A reduction over the wave's lanes: a count, a sum, a minimum... + Total(super::wave::Op), + /// A count or sum over the lanes below this one. + Prefix, + /// Derived from what a first-lane atomic returned: the slots the wave reserved. + Base, + /// A mix the idiom does not make. + Mixed, +} + +/// Whether a console wave64 program may run with each host wave as a wave of its own +/// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses +/// them, which does not care how the threads are divided into waves. A first-lane number only +/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; +/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. +/// Anything else done with them takes one wave to be the whole thread group (a tile's result, +/// say) and is refused, with the offset and what was found. +/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections +/// are stopped by the lowering itself. +// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this +// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is +// the only mix of old and new lanes that is looked at. +pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { + use super::wave::{Op, Shape}; + const FIRST: Why = "a wave's first-lane number used as data"; + const TOTAL: Why = "a count or sum over the wave used as data"; + const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; + const MIXED: Why = "a value that depends on the wave on some paths only"; + const EFFECT: Why = "a write by the wave's first lane other than its reservation"; + fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave { + v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) + } + fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) { + if k == Wave::Plain { + kind.remove(&v); + } else { + kind.insert(v, k); + } + } + let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); + let why = |k: Wave| match k { + Wave::First => FIRST, + Wave::Total(_) => TOTAL, + Wave::Prefix => PREFIX, + _ => MIXED, + }; + // a mask (by its low dword) under which only a wave's first lane runs + let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| { + m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { + st.bools + .support(b) + .iter() + .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) + }) + }; + // 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<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> { + let name = inst.name(); + let val = |op: &Operand| match *op { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let ops: Vec<Operand> = match &inst.fields { + Fields::Valu(v) => v.src.clone(), + Fields::Sop { dst, src, .. } => { + let mut o = src.clone(); + if matches!(name, "s_addk_i32" | "s_mulk_i32") { + o.extend(dst.iter().copied()); + } + o + } + Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { + data.iter().copied().collect() + } + _ => Vec::new(), + }; + let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect(); + // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide + // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it + // writes, which only the lanes outside EXEC keep. + let named: Vec<Value> = ops.iter().filter_map(&val).collect(); + for &(r, v) in &inst.reads { + let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); + if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { + continue; + } + let k = of(kind, Some(v)); + if wild(k) { + return Err(why(k)); + } + } + 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_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { + Wave::Total(Op::AddU) + } + // bits of a mask below the lane; with -1 for the mask, the lane's number + ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { + match (matches!(ops[0], Operand::Scalar { .. }), *b) { + (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, + (false, Wave::Plain | Wave::Base) => Wave::Plain, + (_, k) => return Err(why(k)), + } + } + // 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 } + } + ("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]) => { + // the lane whose own number is the first lane's + let lane = match (*a, *b) { + (Wave::First, k) if !wild(k) => &ops[1], + (k, Wave::First) if !wild(k) => &ops[0], + _ => return Err(why(w)), + }; + if !matches!(lane, Operand::Vector { .. }) { + return Err(FIRST); + } + let mask = match &inst.fields { + _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), + Fields::Valu(v) => match v.dst { + Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), + _ => None, + }, + _ => None, + }; + firsts.extend(mask); + Wave::Plain + } + ("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, + (x, y) if sum(x) && sum(y) => x, + _ => return Err(why(w)), + }, + ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { + (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain) => Wave::Prefix, + (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, + _ => return Err(why(w)), + }, + ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { + (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, + _ => return Err(why(w)), + }, + ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) + if sum(*x) || *x == Wave::Prefix => + { + *x + } + ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { + 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_") => { + let want = match op { + Op::AddU => "buffer_atomic_add", + Op::MinU => "buffer_atomic_umin", + Op::MaxU => "buffer_atomic_umax", + Op::MinI => "buffer_atomic_smin", + Op::MaxI => "buffer_atomic_smax", + Op::Or => "buffer_atomic_or", + Op::And => "buffer_atomic_and", + Op::Xor => "buffer_atomic_xor", + _ => "", + }; + if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err(TOTAL); + } + reserved = true; + Wave::Base + } + _ => return Err(why(w)), + }; + Ok((out, reserved)) + }; + 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<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> { + for &b in &order { + let block = &p.blocks[b]; + for phi in &block.phis { + let mut k = Wave::Plain; + for (n, &a) in phi.args.iter().enumerate() { + let x = of(kind, Some(a)); + k = match (k, x) { + _ if n == 0 => x, + (k, x) if k == x => k, + (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) + | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, + _ => Wave::Mixed, + }; + } + put(kind, phi.value, k); + } + for (i, inst) in block.insts.iter().enumerate() { + // inside a whole-wave section: what the simulation found each value to be + if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { + for &(_, w) in &inst.writes { + let k = match sec.shapes.get(&w) { + None => Wave::Mixed, + Some(&Shape::K(_)) => Wave::Plain, + Some(&Shape::Value(v)) => of(kind, Some(v)), + Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), + Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Total(op), + // the first lane's own sum of a total is that total + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), + _ => Wave::Mixed, + }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, + _ => Wave::Mixed, + }, + Some(_) => Wave::Mixed, + }; + put(kind, w, k); + } + continue; + } + let name = inst.name(); + if name.starts_with("s_cbranch") { + continue; // with the block's exit, below + } + let (k, reserved) = match step(inst, kind, firsts) { + Ok(r) => r, + Err(why) if check => return Err((inst.machine.offset, why)), + Err(_) => (Wave::Mixed, false), + }; + // 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_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err((inst.machine.offset, EFFECT)); + } + let guarded = st.guards[b][i].is_some(); + for &(r, w) in &inst.writes { + 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 } + } + _ => k, + }; + // a guarded write leaves the old value in the lanes outside EXEC + if guarded + && matches!(r, Reg::V(_)) + && kw == Wave::Plain + && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) + { + kw = Wave::Mixed; + } + put(kind, w, kw); + } + } + // a branch on "some lane is counted": fine where the structure made it the lane's + // own bit (the mask is EXEC under a scalar condition) + if check + && let Some(last) = block.insts.last() + && last.name().starts_with("s_cbranch_scc") + && let Some(scc) = last.read(Reg::Scc) + && wild(of(kind, Some(scc))) + { + let own = matches!(st.exits[b], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); + if !own { + return Err((last.machine.offset, TOTAL)); + } + } + } + Ok(()) + }; + let mut kind: HashMap<Value, Wave> = HashMap::new(); + let mut firsts: HashSet<Value> = HashSet::new(); + // to a fixpoint (values carried around loops), then once more to say what is wrong + let mut settled = false; + for _ in 0..16 { + let before = (kind.clone(), firsts.len()); + pass(&mut kind, &mut firsts, false)?; + if (&before.0, before.1) == (&kind, firsts.len()) { + settled = true; + break; + } + } + if !settled { + return Err((0, MIXED)); + } + pass(&mut kind, &mut firsts, true) +} + +/// The mode of a group barrier the translation adds (host waves meeting): +/// a wait for the group with a shared-memory fence; the fence alone with +/// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]). +fn meeting_mode() -> u32 { + if super::group_sync() == 0 { 8 } else { 1 | 8 } +} + +/// LDS accesses of a console wave run as two host waves, where some sit in blocks that only +/// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a +/// group barrier) at its start and before its exit. `None` if barriers cannot keep the +/// console's order. +/// +/// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two +/// host waves keep that order if they meet between any two accesses of which one writes. A +/// barrier must be run by every thread, so it cannot stand in a lane branch's region; but +/// every way into and out of such a region passes a block all lanes run, and the waves meet +/// there: before the exit of an all-lane block into a region with LDS accesses, and at the +/// start of an all-lane block entered from one. Accesses in all-lane blocks get their own +/// 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<Vec<(bool, bool)>> { + let n = st.exits.len(); + let succ = |b: usize| -> Vec<usize> { + match st.exits[b] { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken], + LaneExit::End | LaneExit::Indirect => Vec::new(), + } + }; + // regions: blocks not every lane runs, joined by the edges between them + let mut region: Vec<usize> = (0..n).collect(); + fn find(region: &mut [usize], mut b: usize) -> usize { + while region[b] != b { + region[b] = region[region[b]]; + b = region[b]; + } + b + } + for b in 0..n { + for t in succ(b) { + if !all[b] && !all[t] { + let (x, y) = (find(&mut region, b), find(&mut region, t)); + region[x] = y; + } + } + } + // per region: LDS reads, LDS writes + let mut reads = vec![false; n]; + let mut writes = vec![false; n]; + for (b, block) in p.blocks.iter().enumerate().take(n) { + if all[b] { + continue; + } + 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") { + continue; + } + if name.starts_with("ds_read") { + reads[r] = true; + } else { + writes[r] = true; + } + } + } + if (0..n).any(|r| reads[r] && writes[r]) { + return None; + } + let mut meet = vec![(false, false); n]; + for b in 0..n { + for t in succ(b) { + if all[b] && !all[t] { + let r = find(&mut region, t); + meet[b].1 |= reads[r] || writes[r]; + } else if !all[b] && all[t] { + let r = find(&mut region, b); + meet[t].0 |= reads[r] || writes[r]; + } + } + } + Some(meet) +} + +/// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its +/// own bit by its console lane. +fn lane_constant_masks(st: &Structured) -> bool { + let whens = st.exits.iter().filter_map(|e| match *e { + LaneExit::Branch { when, .. } => Some(when), + _ => None, + }); + let mut work: Vec<Bool> = 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 + // a program still stops with "a constant lane mask" or "an opaque lane mask". + let (mut seen, mut joins) = (HashSet::new(), HashSet::new()); + while let Some(g) = work.pop() { + if !seen.insert(g) { + continue; + } + for a in st.bools.support(g) { + match a { + Atom::Opaque(_) | Atom::Constant(_) => return true, + Atom::Phi(id) if joins.insert(id) => { + if let Some(edges) = st.phi_masks.get(&id) { + work.extend(edges.iter().copied()); + } + } + _ => {} + } + } + } + false +} + +/// The widest wave the host GPU runs (0: not known – no host-specific forms); see +/// [`set_host_max_wave`]. +static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane +/// code stays inside 32-lane halves run in waves of 32 instead of being refused. +pub fn set_host_max_wave(lanes: u32) { + HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed); +} + +thread_local! { + /// See [`take_needs`]. + static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; + /// See [`with_local_waves`]. + static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// See [`with_local_waves_any`]. + static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// As [`with_local_waves`], with every other use of a lane mask as a number +/// and every lane read and write taken per host wave too: the program runs +/// as it would on a console of 32-lane waves, lanes numbered 0..31 or +/// 32..63 by half. Right for code that only relies on what HLSL's wave +/// operations promise; a program that takes one wave to be its whole +/// thread group gets per-half results. The last resort for programs that +/// do not translate otherwise. +pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R { + let was = LOCAL_ANY.replace(true); + let r = with_local_waves(f); + LOCAL_ANY.set(was); + r +} + +/// Runs `f` with console wave64 programs on 32-lane hosts lowered with each +/// host wave as a wave of its own ("local"): no exchange between the two +/// halves of a console wave, so no barriers and no need for every lane to +/// reach the code. What HLSL's wave operations promise holds for any +/// division of the threads into waves, and the idiom the title's compute +/// programs use them for does not care which wave a thread is in: count or +/// sum over the wave, the first lane reserves that many slots with an atomic +/// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix. +/// Each lane still gets a slot of its own; only the order differs. +/// Only that idiom's operations are lowered this way: a lane mask read as +/// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and +/// lane reads and writes outside whole-wave sections, stop the translation. +/// shortcut: where a count or sum goes is not checked. A program that uses +/// a wave-wide result as data for the whole console wave (a tile's maximum, +/// say, with one wave per thread group) gets its half's result. It is used +/// only for programs that do not translate otherwise. +pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R { + let was = LOCAL_WAVES.replace(true); + let r = f(); + LOCAL_WAVES.set(was); + r +} + +/// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`, +/// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them +/// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA: +/// the last place of a result that is not exact is then one lower than the console's). +/// Off by default: it is exact but untried in a game run, and adds instructions to every +/// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact. +fn f16_nearest_on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_F16_NEAREST.get() { + return on; + } + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1")) +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`f16_nearest_on`], for its thread only. + pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before +/// ([`super::own_bits`]). +fn own_bits_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) +} + +pub(super) fn host_max_wave() -> u32 { + #[cfg(test)] + if let Some(lanes) = TEST_HOST_WAVE.get() { + return lanes; + } + HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed) +} + +#[cfg(test)] +thread_local! { + /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's). + pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) }; +} + +pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let ops: Vec<&Operand> = match &i.fields { + // A mask operation (its result a mask) is no data use. + Fields::Sop { .. } + if i.writes + .iter() + .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) => + { + return false; + } + Fields::Sop { src, .. } => src.iter().collect(), + Fields::Valu(v) + if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") => + { + v.src.iter().collect() + } + _ => return false, + }; + ops.into_iter().any(|op| match *op { + Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask), + _ => false, + }) +} + +/// The parameters packing 16-bit rows two per dword and where each lays +/// its elements out: (first row, [(dword, register, column, columns)]). +/// +/// The console gives every 16-bit element whole dwords. A parameter leads +/// with the first element of its first row, then the first element of its +/// 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, +/// 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 +/// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of +/// TEXCOORD4's second dword stays zero. +type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>; + +fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout { + let of_row = |r: u8| { + let mut of: Vec<&SigElement> = elements + .iter() + .filter(|e| e.row == Some(u32::from(r))) + .collect(); + of.sort_by_key(|e| e.col); + of + }; + let mut packs = packs.to_vec(); + packs.sort_unstable(); + packs.dedup_by_key(|p| p.0); + // Per parameter: its first row, the dwords used, the elements. + let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new(); + let mut behind = Vec::new(); + for &(a, b) in &packs { + let mut placed = Vec::new(); + let mut at = 0u8; + if !of_row(a).is_empty() { + for r in [Some(a), b].into_iter().flatten() { + let of = of_row(r); + let Some((lead, more)) = of.split_first() else { + continue; + }; + placed.push((at, r, lead.col, lead.cols)); + at += lead.cols.div_ceil(2); + behind.extend(more.iter().map(|e| (r, e.col, e.cols))); + } + } + layout.push((a, at, placed)); + } + behind.sort_unstable(); + for (r, col, cols) in behind { + let need = cols.div_ceil(2); + if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) { + p.2.push((p.1, r, col, cols)); + p.1 += need; + } + } + layout.into_iter().map(|(a, _, of)| (a, of)).collect() +} + +/// Where half `h` (dword h / 2, the high half when odd) of the parameter +/// whose first 16-bit row is `a` comes from: a register and column of +/// `elements`, none for padding ([`packed_layout`]; `packs` lists every +/// parameter packing two 16-bit rows per dword). +fn packed_half( + elements: &[SigElement], + packs: &[(u8, Option<u8>)], + a: u8, + h: u8, +) -> Option<(u8, u8)> { + let layout = packed_layout(elements, packs); + let (_, of) = layout.iter().find(|p| p.0 == a)?; + of.iter().find_map(|&(dword, row, col, cols)| { + let k = h.checked_sub(2 * dword)?; + (k < cols).then_some((row, col + k)) + }) +} + +/// The pixel inputs packing two 16-bit rows per dword, as (first row, +/// second row) ([`packed_layout`]). +fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return Vec::new(); + }; + let partners = half_input_partners(io, inputs); + entries + .iter() + .filter(|i| i.fp16 && i.pack2) + .map(|i| { + let b = if i.row2 != i.row { + Some(i.row2) + } else { + partners.get(&i.row).copied() + }; + (i.row, b) + }) + .collect() +} + +/// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]): +/// a packed row's partner is the next 16-bit row of the signature that no +/// output entry names, taken in row order. +fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> { + let entries = match io { + StageIo::Vs { outputs, .. } => outputs, + StageIo::Ms(ms) => &ms.outputs, + _ => return HashMap::new(), + }; + let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0); + let mut free: Vec<u8> = outputs + .iter() + .filter(|e| e.half && e.kind == 0) + .filter_map(|e| u8::try_from(e.row?).ok()) + .filter(|&r| !per_vertex().any(|o| o.row == r)) + .collect(); + free.sort_unstable(); + free.dedup(); + let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect(); + halves.sort_by_key(|o| o.row); + halves + .into_iter() + .map(|o| { + let b = o + .pack2 + .then(|| free.iter().position(|&r| r > o.row)) + .flatten(); + (o.row, (o.pack2, b.map(|i| free.remove(i)))) + }) + .collect() +} + +/// Pixel inputs packing two 16-bit rows per dword whose second row the +/// metadata leaves out (`row2` = `row`): as for outputs +/// ([`half_outputs`]), the next 16-bit row of the signature that no input +/// entry names, taken in row order (rows the metadata does give are taken +/// first). +fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return HashMap::new(); + }; + let packed = || entries.iter().filter(|i| i.fp16 && i.pack2); + let mut free: Vec<u8> = inputs + .iter() + .filter(|e| e.half && e.kind == 0) + .filter_map(|e| u8::try_from(e.row?).ok()) + .filter(|&r| !entries.iter().any(|i| i.row == r)) + .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r)) + .collect(); + free.sort_unstable(); + free.dedup(); + let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect(); + missing.sort_by_key(|i| i.row); + let mut partners = HashMap::new(); + for i in missing { + if let Some(k) = free.iter().position(|&r| r > i.row) { + partners.insert(i.row, free.remove(k)); + } + } + partners +} + +fn unsupported(offset: usize, what: Why) -> Stop { + Stop::Fail(ShaderError::Unsupported { offset, what }) +} + +impl<'a> Lower<'a> { + fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self { + let p = x.p; + let mut phi_at = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, phi) in block.phis.iter().enumerate() { + phi_at.insert(phi.value, (b, i)); + } + } + let mut s = Shader::new(x.native.stage == HwStage::Ps); + s.inputs = x.inputs.clone(); + 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 { .. }) + && (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`) + let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None; + // a console wave64 program in two host waves of 32 (`exchange`) + let mut exchange: Option<(u32, bool, Vec<bool>)> = None; + // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter + let mut halves: Option<u32> = None; + if let StageIo::Cs(cs) = x.native.io { + s.threads = Some(cs.threads); + s.lds_dwords = cs.lds_bytes() / 4; + // Code reading other lanes needs the console's wave size and + // lane order; so do lane masks read as numbers, and LDS shared + // within one wave, where the console compiler leaves out barriers. + console_lanes = insts().any(|i| { + let n = i.name(); + n.starts_with("ds_swizzle") + || n.contains("permute") + || n.starts_with("v_mbcnt") + || 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) + }) || 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 }; + let group = cs.threads.iter().product::<u32>(); + let one_wave = group <= wave; + // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console + // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows, + // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs + // exactly in waves of 32: the thread relabelling makes each host wave one half of a + // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`, + // `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) { + let crosses = insts().any(|i| { + let n = i.name(); + n.starts_with("v_mbcnt") + || matches!(n, "v_readlane_b32" | "v_writelane_b32") + || n.starts_with("ds_permute") + || n.starts_with("ds_bpermute") + || reads_mask_as_data(x.st, i) + }) || lane_constant_masks(x.st) + || !x.st.wide.is_empty(); + if !crosses && (s.lds_dwords == 0 || group <= 32) { + wave = 32; + } else { + // (Groups of several console waves too: each console wave is two host + // waves, which exchange through their own pair of dwords.) + // LDS the console shares within its one wave without barriers: split into + // two waves of 32, a group barrier before every LDS access keeps their order + // – where every thread of the group gets there (no lane branch around it, + // no guard), else a barrier would hang the group + let lds = |i: &Inst| { + matches!(i.fields, Fields::Ds { .. }) + && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute")) + }; + 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) + }) + }); + let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok; + if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) { + lds_meet = Some((all.clone(), meet)); + lds_ok = true; + } + if !lds_ok { + // (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) { + need(b); + } + } + } + if lds_ok { + wave = 32; + split_lds = s.lds_dwords > 0 && group > 32; + if crosses { + // lanes 32..63 are the other host wave: masks, lane reads and lane + // numbers go through two exchange dwords past the program's LDS + exchange = Some((s.lds_dwords, group <= 32, all)); + s.lds_dwords += 2 * group.div_ceil(64); + } + } + } + } + // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason) + if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() { + let mut why: Vec<&str> = Vec::new(); + for i in insts() { + let n = i.name(); + let r = if n.starts_with("v_mbcnt") { + "v_mbcnt" + } else if n == "v_readlane_b32" { + "v_readlane" + } else if n == "v_writelane_b32" { + "v_writelane" + } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") { + "ds_(b)permute" + } else if reads_mask_as_data(x.st, i) { + "mask as data" + } else { + continue; + }; + if !why.contains(&r) { + why.push(r); + } + } + if lane_constant_masks(x.st) { + why.push("lane-constant mask"); + } + if s.lds_dwords > 0 && group > 32 { + why.push("LDS in a group over 32"); + match all_lane_blocks(x.st) { + None => why.push("an indirect exit"), + Some(all) if lds_meetings(p, x.st, &all).is_none() => { + why.push("an LDS read and write in one lane-branch region") + } + Some(_) => {} + } + } + why.sort_unstable(); + eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", ")); + } + } + if wave == 32 && x.native.wave64 { + // console threads go to host waves in the order the waves take them (`wave_base`) + halves = Some(s.lds_dwords); + s.lds_dwords += 1; + } + if console_lanes || one_wave && s.lds_dwords > 0 { + s.wave_size = Some(wave); + } + } + // The title's barriers a thread of the group may never reach, which + // leaves the others waiting on the host: those in blocks some lanes + // do not run, and all of them in a program with a loop closed by a + // plain jump (a lane still in it at the iteration limit leaves the + // program there, `abort_block`). + let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") { + let order = crate::ir::reverse_postorder(&p.blocks); + let mut place = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + place[b] = n; + } + let back = |from: usize, to: usize| { + 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 all = all_lane_blocks(x.st); + (0..p.blocks.len()) + .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier")) + .filter(|&b| { + cut_short + || all + .as_ref() + .is_none_or(|all| !all.get(b).copied().unwrap_or(false)) + }) + .collect() + } else { + HashSet::new() + }; + let mut no_barrier = HashSet::new(); + if let StageIo::Ms(ms) = &x.native.io { + s.prims = x.prims.clone(); + s.threads = Some([ms.threads, 1, 1]); + s.lds_dwords = ms.lds_bytes.div_ceil(4); + s.mesh = Some(super::shader::Mesh { + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + }); + // 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 + // counts out of range) runs in that lane alone, so its barrier + // would hang the host. + let order = crate::ir::reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + let idom = crate::ir::idoms(&p.blocks, &order, &index); + let alloc: Vec<usize> = (0..p.blocks.len()) + .filter(|&b| { + p.blocks[b].insts.iter().any(|i| { + i.name() == "s_sendmsg" + && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ) + }) + }) + .collect(); + for &b in &order { + let mut d = b; + let dominated = loop { + if alloc.contains(&d) { + break true; + } + if idom[d] == d || idom[d] == usize::MAX { + break false; + } + d = idom[d]; + }; + if ms.lds_bytes == 0 || dominated { + no_barrier.insert(b); + } + } + } + Lower { + s, + x, + bad, + lane_fail: HashMap::new(), + vals: HashMap::new(), + floats: HashMap::new(), + block: vec![None; p.blocks.len()], + cur: 0, + bools: HashMap::new(), + lane_bits: HashMap::new(), + phi_at, + mask_phis: HashMap::new(), + pending_masks: Vec::new(), + data_phis: Vec::new(), + read_phis: HashSet::new(), + stale: HashSet::new(), + params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), + user_data: None, + user_reads: BTreeMap::new(), + samplers: Vec::new(), + descriptors: x + .res + .descriptors + .iter() + .map(|d| ((d.site, d.role == Role::Sampler), &d.source)) + .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(), + handles: HashMap::new(), + strides: HashMap::new(), + edges: HashMap::new(), + exported: vec![false; p.blocks.len()], + rpo: vec![usize::MAX; p.blocks.len()], + tail: vec![None; p.blocks.len()], + writes_uavs, + src0: None, + console_lanes, + split_lds, + lds_meet, + local: exchange.is_some() && LOCAL_WAVES.get(), + local_ok: false, + local_any: LOCAL_ANY.get(), + uniform: match &exchange { + Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + _ => HashSet::new(), + }, + own_bits: match &exchange { + Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => { + super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some()) + } + _ => Default::default(), + }, + exchange, + clane: None, + pair: None, + halves, + wave_base: None, + flat: None, + no_barrier, + fence_only, + half_outputs: half_outputs(&x.native.io, &x.outputs), + mask_data: match x.native.stage { + HwStage::Cs => MaskData::Console, + HwStage::Ps | HwStage::Vs => MaskData::Host, + _ => MaskData::None, + }, + mask_ok: false, + ballots: HashMap::new(), + balloting: HashSet::new(), + def_block: p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .insts + .iter() + .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b))) + .chain(block.phis.iter().map(move |phi| (phi.value, b))) + }) + .collect(), + cur_ir: 0, + sections: HashMap::new(), + section_out: HashSet::new(), + code_table: None, + counters: HashMap::new(), + abort: None, + } + } + + /// The dword of the program's code at byte `byte` (a constant table + /// the compiler appends to the code), as an internal constant array. + // shortcut: an index outside the table reads its last dword (the + // console would read whatever memory follows the code). + fn code_dword(&mut self, byte: V) -> Result<V, Why> { + let (g, base, len) = match self.code_table { + Some(t) => t, + None => { + let first = self + .x + .res + .scalar + .iter() + .map(|s| s.1) + .chain(self.x.res.descriptors.iter().flat_map(|d| { + d.source.leaves().into_iter().filter_map(|l| match l { + Source::Built { address, .. } => Some(*address), + _ => None, + }) + })) + .filter(|a| a.param == CODE) + .map(|a| a.offset & !3) + .min() + .ok_or("a code table")?; + let code = &self.x.native.code; + let words: Vec<u32> = code + .get(first as usize..) + .ok_or("a code table past the code")? + .chunks(4) + .map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + }) + .collect(); + if words.is_empty() { + return Err("a code table past the code"); + } + let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect(); + let arr = self.s.m.array(words.len() as u32, self.s.t.i32); + let init = self.s.m.aggregate(arr, &elems); + let g = self.s.m.constant_global("code", init); + let t = (g, first, words.len() as u32); + self.code_table = Some(t); + t + } + }; + let c = self.cur; + let k = self.s.m.i32(base); + let rel = self.s.m.bin(c, Bin::Sub, byte, k); + let two = self.s.m.i32(2); + let index = self.s.m.bin(c, Bin::LShr, rel, two); + let last = self.s.m.i32(len - 1); + let over = self.s.m.cmp(c, pred::IUGT, index, last); + let index = self.s.m.select(c, over, last, index); + let at = self.s.m.element(c, g, index); + Ok(self.s.m.load(c, at)) + } + + /// A global memory load (`global_load_*`): from the program's constant + /// table, or from a root SRV at the address the title sets. + fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { dst, .. } = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) { + return self.memory_flat(inst, b, i); + } + let rest = name + .strip_prefix("global_load_") + .ok_or("a global memory write")?; + let (n, sub) = match rest { + "dword" => (1, None), + "dwordx2" => (2, None), + "dwordx3" => (3, None), + "dwordx4" => (4, None), + "ubyte" => (1, Some((8, false))), + "sbyte" => (1, Some((8, true))), + "ushort" => (1, Some((16, false))), + "sshort" => (1, Some((16, true))), + _ => return Err(name), + }; + let a = *self + .scalar + .get(&(b, i)) + .ok_or("an untracked global address")?; + let guard = self.guard(b, i)?; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let c = self.cur; + let mut off = self.s.m.i32(a.offset); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + off = self.s.m.bin(c, Bin::Add, off, d); + } + let h = if a.param == CODE { + None + } else { + let src = Source::Built { + address: a, + bits: 0, + words: [0, 0], + }; + if let Some(bias) = self.root_bias(a.param) { + off = self.s.m.bin(c, Bin::Add, off, bias); + } + Some(self.handle((b, i), &src, false, (11, 0))?) + }; + let dword = |l: &mut Self, byte: V| -> Result<V, Why> { + match h { + None => l.code_dword(byte), + Some(h) => { + let c = l.cur; + let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4)); + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, byte, u, mask, al], + ); + let x = l.s.m.extract(c, r, 0); + Ok(l.as_int(x)) + } + } + }; + for k in 0..n { + let x = match sub { + None => { + let four = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, off, four); + dword(self, at)? + } + Some((width, signed)) => { + // shortcut: the field is taken not to cross a dword. + let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3)); + let at = self.s.m.bin(c, Bin::And, off, not3); + let w = dword(self, at)?; + let byte = self.s.m.bin(c, Bin::And, off, 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); + self.s + .m + .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left) + } + }; + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + /// Finds the whole-wave sections and the values they leave. + fn find_sections(&mut self) { + let p = self.x.p; + let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new(); + for b in 0..p.blocks.len() { + let found = super::wave::sections(p, b); + for (&start, sec) in &found { + for i in start + 1..sec.end { + for &(_, w) in &p.blocks[b].insts[i].writes { + inside.insert(w, (b, start, sec.end)); + } + } + } + if !found.is_empty() { + self.sections.insert(b, found); + } + } + if inside.is_empty() { + return; + } + for (b, block) in p.blocks.iter().enumerate() { + for phi in &block.phis { + self.section_out + .extend(phi.args.iter().filter(|a| inside.contains_key(a))); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, r) in &inst.reads { + if let Some(&(sb, start, end)) = inside.get(&r) + && !(sb == b && i > start && i < end) + { + self.section_out.insert(r); + } + } + } + } + } + + /// An instruction inside a whole-wave section: the values that leave + /// the section are made from what the simulation found them to be. + fn section_inst(&mut self, b: usize, i: usize, start: usize) { + 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 { + 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) => Val::I32(x), + Err(why) => Val::Missing(why), + } + } else { + Val::Missing(UNKNOWN) + }; + self.vals.insert(w, val); + } + } + + /// A value a whole-wave section leaves, as DXIL wave operations over the + /// host's active lanes: the console's result with console lanes; on + /// another wave size, what the HLSL wave operation the console compiler + /// expanded gives on that wave. + /// + /// `own`: a wave OR that only steers a loop over each lane's own bits + /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is + /// this host wave's. + fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> { + use super::wave::{Op, Shape}; + let (op, src, mask, ident, prefix) = match shape { + 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::Masked(src, mask, ident) => { + 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 x = self.i32_of(src)?; + let id = self.s.m.i32(ident); + return Ok(self.s.m.select(c, on, x, id)); + } + Shape::Prefix(op, src, mask, ident, inclusive) => { + (op, src, mask, ident, Some(inclusive)) + } + }; + // Mesh: no host wave size can be declared, so a reduction is over this host wave + // only. A minimum or maximum is taken that way: the compiler's "next distinct + // value" loop (the wave's minimum, then the lanes that hold it) serves every + // lane however the lanes are divided into waves. A sum, a bit reduction or a + // prefix would be of part of a console wave: still refused. + if self.mask_data == MaskData::None + && (prefix.is_some() + || !matches!( + op, + Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF + )) + { + 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 x = self.i32_of(src)?; + let id = self.s.m.i32(ident); + let x = self.s.m.select(c, on, x, id); + self.s.flags |= flags::WAVE_OPS; + if op == Op::AddH { + return match prefix { + Some(_) => Err("a wave prefix of an operation other than a sum"), + None => self.half_sum(x), + }; + } + let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let arg = if float { self.as_float(x) } else { x }; + let ty = if float { f32t } else { i32t }; + let sfx = if float { "f32" } else { "i32" }; + let r = match (op, prefix) { + (Op::AddU | Op::AddF, Some(inclusive)) => { + let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1)); + let r = self.s.op( + c, + &format!("wavePrefixOp.{sfx}"), + Attr::NoUnwind, + ty, + 121, + &[arg, k0, k1], + ); + if inclusive { + self.s.m.bin(c, Bin::Add, r, arg) + } else { + r + } + } + (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"), + (Op::Or | Op::And | Op::Xor, None) => { + let k = self.s.m.i8(match op { + Op::And => 0, + Op::Or => 1, + _ => 2, + }); + self.s + .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k]) + } + (_, None) => { + let (code, unsigned) = match op { + Op::AddU => (0, 1), + Op::AddF => (0, 0), + Op::MinU => (2, 1), + Op::MaxU => (3, 1), + Op::MinI | Op::MinF => (2, 0), + _ => (3, 0), + }; + let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned)); + self.s.op( + c, + &format!("waveActiveOp.{sfx}"), + Attr::NoUnwind, + ty, + 119, + &[arg, k, u], + ) + } + }; + // two host waves of 32 hold the console's 64 lanes: their results combine + let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { + // this host wave's own result (and prefix): each wave on its own, or a group of + // 32 threads or fewer, which one host wave holds whole (combining with the 0 a + // missing half "gives" broke AND, MIN and signed MAX) + r + } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) { + // each thread walks the bits of this value and works only at its own, which the + // host wave's OR holds: the same run as with the console wave's OR + r + } else 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 bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v }; + let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v }; + match prefix { + 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 tb = bits(self, total); + let c = self.cur; + let (lo, _) = self.exchange_halves(c, tb); + let lo = back(self, lo); + 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 add = self.s.m.select(c, upper, lo, zero); + self.s.m.bin(c, Bin::Add, r, add) + } + None => { + let rb = bits(self, r); + let c = self.cur; + let (lo, hi) = self.exchange_halves(c, rb); + let (lo, hi) = (back(self, lo), back(self, hi)); + match op { + Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), + Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), + Op::And => self.s.m.bin(c, Bin::And, lo, hi), + Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), + _ => { + // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 + let code = match op { + Op::MaxF => 35, + Op::MinF => 36, + Op::MinU => 40, + Op::MaxU => 39, + Op::MinI => 38, + _ => 37, + }; + self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) + } + } + } + } + } else { + r + }; + Ok(if float { self.as_int(r) } else { r }) + } + + /// 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`]). + fn add_halves(&mut self, a: V, b: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let low = self.s.m.i32(0xFFFF); + let wide = |l: &mut Self, x: V| { + let h = l.s.m.bin(c, Bin::And, x, low); + l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]) + }; + let (fa, fb) = (wide(self, a), wide(self, b)); + let f = self.s.m.bin(c, Bin::Add, fa, fb); + self.f16_nearest(f) + } + + /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the + /// 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 + /// 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. + /// That needs every lane of a full wave there to be read: refused where not every lane + /// runs, in a thread group that does not fill its waves, and for each half-wave on its + /// own (half a sum is no sum). + fn half_sum(&mut self, x: V) -> Result<V, Why> { + 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")?; + if threads.iter().product::<u32>() % 64 != 0 { + return Err("a wave sum of 16-bit floats in a wave that is not full"); + } + if self.local { + return Err("a wave sum of 16-bit floats in a half-wave"); + } + // two host waves of 32 that exchange, or one host wave of 64 lanes + let halves = match (&self.exchange, self.s.wave_size) { + (Some((_, false, _)), _) => true, + (None, Some(64)) if self.x.p.wave64 => false, + _ => return Err("a wave sum of 16-bit floats on these waves"), + }; + 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)) + }; + if !every { + if halves { + need(self.cur_ir); + } + return Err(WHERE); + } + let c = self.cur; + let i32t = self.s.t.i32; + 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); + let partner = self.s.m.bin(c, Bin::Xor, lane, bit); + 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 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); + let mine = self.s.m.bin(c, Bin::Or, first, sum); + if !halves { + return Ok(mine); + } + let (lo, hi) = self.exchange_halves(c, mine); + let c = self.cur; + let total = self.add_halves(lo, hi); + let total = self.s.m.bin(c, Bin::And, total, low); + let first = self.s.m.bin(c, Bin::And, lo, high); + Ok(self.s.m.bin(c, Bin::Or, first, total)) + } + + fn run(mut self) -> Result<Lowered, Stop> { + let p = self.x.p; + let order = crate::ir::reverse_postorder(&p.blocks); + for (n, &b) in order.iter().enumerate() { + self.rpo[b] = n; + } + for (n, &b) in order.iter().enumerate() { + self.block[b] = Some(if n == 0 { + self.s.entry + } else { + self.s.m.new_block() + }); + } + // Loop headers count iterations (`LOOP_LIMIT`). + for &b in &order { + let header = p.blocks[b] + .preds + .iter() + .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]); + if header { + let blk = self.block[b].expect("reachable"); + let phi = self.s.m.phi(blk, self.s.t.i32); + 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; + let preds: Vec<usize> = p.blocks[b] + .preds + .iter() + .copied() + .filter(|&q| self.block[q].is_some()) + .collect(); + self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q)); + for (i, phi) in p.blocks[b].phis.iter().enumerate() { + let val = match phi.reg { + Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), + _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), + Reg::Scc => { + let v = self.s.m.phi(self.cur, self.s.t.i1); + self.data_phis.push((v, b, i)); + Val::Bit(v) + } + _ => { + let v = self.s.m.phi(self.cur, self.s.t.i32); + self.data_phis.push((v, b, i)); + Val::I32(v) + } + }; + self.vals.insert(phi.value, val); + } + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) { + self.lds_meeting(); + } + let mut i = 0; + while i < p.blocks[b].insts.len() { + self.inst(b, i)?; + if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) { + for j in i + 1..end { + self.section_inst(b, j, i); + } + i = end; + continue; + } + i += 1; + } + self.mask_ok = self.mask_data == MaskData::Console; + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) { + self.lds_meeting(); + } + self.tail[b] = Some(self.cur); + self.exit(b)?; + } + self.fill_phis()?; + let user_data = self.user_reads.values().copied().collect(); + 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.cmp_samplers; + let wave_size = self.s.wave_size; + Ok(Lowered { + wave_size, + cmp_samplers, + root_cbvs, + root_srvs, + root_uavs, + #[cfg(test)] + nonuniform_handles: self.s.nonuniform_handles, + #[cfg(test)] + wave_ops: self.s.flags & flags::WAVE_OPS != 0, + dxil: self.s.finish(), + user_data, + samplers: self.samplers, + }) + } + + fn exported_out(&self, b: usize) -> bool { + self.exported[b] || self.has_done_export(b) + } + + fn has_done_export(&self, b: usize) -> bool { + (0..self.x.p.blocks[b].insts.len()) + .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done)) + } + + /// Values of the program's input registers. + fn inputs(&mut self) -> Result<(), Stop> { + let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect(); + for &(reg, v) in &self.x.p.inputs { + let val = match reg { + Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use + // Most programs only interpolate with them: loaded on first + // use as a value (`get`). + Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => { + continue; + } + Reg::S(n) => match io_inputs.get(&v) { + Some(&input) => self.input(input), + // Above the SGPRs the hardware initializes, a register + // holds what the last wave left, so no program depends + // on it: a read the paths only seem to allow (a branch + // past the write, taken only with one past the read) + // reads zero, as VGPRs do. + None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { + Val::I32(self.s.m.i32(0)) + } + // A scalar parked in a VGPR lane (`ir::unspill`), read where the + // paths only seem to allow it before any save: the lane of a VGPR + // nobody wrote, and VGPRs nobody set read as zero. + None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)), + None => Val::Missing("a hardware SGPR input"), + }, + Reg::Scc => Val::Missing("SCC on entry"), + Reg::V(_) => match io_inputs.get(&v) { + Some(&input) => self.input(input), + // Registers no one set read as zero (the validator + // refuses reads of undef). + None => Val::I32(self.s.m.i32(0)), + }, + }; + self.vals.insert(v, val); + } + Ok(()) + } + + fn input(&mut self, input: Input) -> Val { + let (kind, col) = match input { + Input::VertexId => (1, 0), + Input::InstanceId => (2, 0), + Input::Position(c) => (3, c), + Input::Attribute { row, channel } => { + return match self.find_input(row, channel) { + Some((id, col)) => self.load_input(id, col), + None => Val::Missing("a vertex input the signature lacks"), + }; + } + Input::Barycentric { kind, index } => return self.barycentric(kind, index), + Input::PrimitiveId => return Val::Missing("the primitive id"), + // The console code tests it against 0 (`v_cmp_ne_u32`), as the + // host's value can be. + Input::FrontFace => (13, 0), + Input::ThreadIdInGroup(c) => return self.thread_id(c), + Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c), + Input::GroupInfo => return Val::Missing("the thread-group info SGPR"), + Input::MeshGroup => { + let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else { + unreachable!() + }; + let n = self.s.m.i32(self.x.mesh_stride); + return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n)); + } + Input::MergedWaveInfo => { + // shortcut: only the wave index (bits 24-27) is set; the + // console's other bits (lane counts) are read by no program. + let f = self.mesh_thread(); + let shift = self.s.m.i32(self.wave().trailing_zeros()); + let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift); + let k24 = self.s.m.i32(24); + return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24)); + } + _ => return Val::Missing("a pixel system input"), + }; + let free = self + .s + .inputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + let id = match self.s.inputs.iter().position(|e| e.kind == kind) { + Some(id) => { + if kind != 3 { + self.s.inputs[id].row.get_or_insert(free); + } + id + } + None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"), + None => { + // The console signature leaves out vertex and instance ids; PC + // gives them a row after the others. + let row = self + .s + .inputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + self.s.inputs.push(SigElement { + name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + }; + self.load_input(id, col) + } + + /// A component of a compute thread or group id, read in the entry block. + fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val { + let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c))); + Val::I32( + self.s + .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]), + ) + } + + fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> { + self.s.inputs.iter().enumerate().find_map(|(id, e)| { + let r = e.row?; + // `then`, not `then_some`: the channel is only past `col` when + // the condition holds. + (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols) + .then(|| (id, channel - e.col)) + }) + } + + fn load_input(&mut self, id: usize, col: u8) -> Val { + if self.s.inputs[id].half { + // shortcut: 16-bit vertex inputs (the fetch routine's) are not + // unpacked; pixel inputs are (`interp`). + return Val::Missing("a 16-bit input"); + } + self.load_any_input(id, col) + } + + /// An input element's channel as declared (16-bit ones as 32-bit floats). + fn load_any_input(&mut self, id: usize, col: u8) -> Val { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let (int, bit) = (e.comp != 9, e.comp == 1); + let ty = if bit { + self.s.t.i1 + } else if int { + self.s.t.i32 + } else { + self.s.t.f32 + }; + let suffix = if bit { + ".i1" + } else if int { + ".i32" + } else { + ".f32" + }; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.undef(self.s.t.i32), + ]; + let v = self.s.op( + entry, + &format!("loadInput{suffix}"), + Attr::ReadNone, + ty, + 4, + &args, + ); + if bit { + let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32); + Val::I32(z) + } else if int { + Val::I32(v) + } else { + Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32)) + } + } + + /// The DXIL form of an IR value. + fn get(&mut self, v: Value) -> Result<Val, Why> { + if self.phi_at.contains_key(&v) { + self.read_phis.insert(v); + } + let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v); + match self.vals.get(&v) { + Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => { + return self.mask_dword(v).map(Val::I32); + } + Some(&Val::Missing(w)) => return Err(w), + Some(&val) => return Ok(val), + None => {} + } + if let Some(&(param, dword)) = self.params.get(&v) { + let val = self.user(param, dword); + self.vals.insert(v, val); + return Ok(val); + } + if let Some(loaded) = self.lazy_barycentric(v) { + loaded?; + return Ok(self.vals[&v]); + } + Err("a value defined after its use") + } + + /// 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<Result<(), Why>> { + let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i { + Input::Barycentric { kind, index } if w == v => Some((kind, index)), + _ => None, + })?; + let val = self.barycentric(kind, index); + self.vals.insert(v, val); + Some(match val { + Val::Missing(w) => Err(w), + _ => Ok(()), + }) + } + + /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of + /// `SV_Barycentrics` declared with the same interpolation mode. + /// + /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are + /// the weights of vertices 1 and 2. The host's weights (x, y, z) are + /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex, + /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat + /// input): i is y and j is z. + /// shortcut: triangles only; on lines and points the console's i and j + /// are not checked against the host's weights. + fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val { + let Some(mode) = interp_mode(kind) else { + return Val::Missing("pull-model barycentrics"); + }; + if index > 1 { + return Val::Missing("pull-model barycentrics"); + } + // One element per interpolation mode (the console's own, if its + // signature declares one): DXIL allows two. + let bary = |e: &SigElement| e.kind == 28; + let id = match self + .s + .inputs + .iter() + .position(|e| bary(e) && (e.interp == mode || e.usage == 0)) + { + Some(id) => id, + None => { + let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32; + if index >= 2 { + return Val::Missing("barycentrics of a third interpolation mode"); + } + // A system value the validator wants unpacked (packing + // location -1), like other non-packed system values. + self.s.inputs.push(SigElement { + name: "SV_Barycentrics".into(), + index, + kind: 28, + comp: 9, + interp: mode, + row: None, + col: 0, + cols: 3, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + }; + let e = &mut self.s.inputs[id]; + if e.col != 0 || e.cols < 3 { + return Val::Missing("a console barycentrics element without i and j"); + } + e.row = None; + e.interp = mode; + self.s.flags |= flags::BARYCENTRICS; + self.load_any_input(id, index + 1) + } + + fn i32_of(&mut self, v: Value) -> Result<V, Why> { + match self.get(v)? { + Val::I32(x) => Ok(x), + Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)), + Val::Missing(w) => Err(w), + } + } + + /// A user-data dword: a root parameter's value. + fn user(&mut self, param: usize, dword: u32) -> Val { + let rp = self.x.native.layout[param]; + match rp.root { + RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)), + RootType::Constants | RootType::Table => {} + _ => return Val::Missing("a root descriptor"), + } + let index = u32::from(rp.user_data) + dword - self.user_first(); + self.user_reads.insert( + index, + UserData { + index, + slot: rp.slot, + root: rp.root, + dword, + }, + ); + Val::I32(self.user_at(index)) + } + + /// The user-data index that is dword 0 of the host's user data: 0, or + /// 16 for a program with a spilled user-data table, whose parameters + /// all sit at 16 and above. (The host's root signature has 64 dwords: + /// a builder stage with constants up to index 45, eight root views, + /// their biases and the memory directory would not fit with 16 dwords + /// nothing reads in front.) + fn user_first(&self) -> u32 { + if crate::spill::is_spilled(self.x.native) { + 16 + } else { + 0 + } + } + + /// A user-data dword no register of the console's holds: one the host + /// computes when it binds (`root` says what, an `Other` code of + /// `shader.rs`), placed after the layout's own dwords. + fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V { + let known = self + .user_reads + .values() + .find(|u| u.root == root && u.slot == slot && u.dword == dword) + .map(|u| u.index); + let index = match known { + Some(index) => index, + None => { + let first = self.user_first(); + let layout = &self.x.native.layout; + let mut index = layout + .iter() + .map(|e| u32::from(e.user_data) + e.sgprs) + .max() + .unwrap_or(0) + .saturating_sub(first); + while self.user_reads.contains_key(&index) { + index += 1; + } + self.user_reads.insert( + index, + UserData { + index, + slot, + root, + dword, + }, + ); + index + } + }; + self.user_at(index) + } + + /// User-data dword `index`, loaded in the entry block. + fn user_at(&mut self, index: u32) -> V { + self.s.user_data = self.s.user_data.max(index + 1); + let h = match self.user_data { + Some(h) => h, + None => { + let h = self.s.user_data_handle(); + self.user_data = Some(h); + h + } + }; + let entry = self.s.entry; + let row = self.s.m.i32(index / 4); + let r = self.s.op( + entry, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, row], + ); + self.s.m.extract(entry, r, index % 4) + } + + /// 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 + /// waterfall loop keeps a descriptor's dwords per lane, reads the first + /// lane's back and compares the lanes' with them. + fn computed_with(&self, v: Value, depth: u32) -> bool { + self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| { + if !i.reads.iter().any(|r| r.1 == v) { + return false; + } + let name = i.name(); + let moves = matches!( + name, + "s_mov_b32" + | "s_mov_b64" + | "v_mov_b32" + | "v_readfirstlane_b32" + | "v_readlane_b32" + | "v_writelane_b32" + | "v_cndmask_b32" + ); + match &i.fields { + Fields::Sop { .. } | Fields::Valu(_) if moves => { + depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1)) + } + Fields::Sop { .. } | Fields::Valu(_) => { + !(name.starts_with("v_cmp") || name.starts_with("s_cmp")) + } + _ => false, + } + }) + } + + /// The title address (low dword, bits from 32 up) of the buffer view + /// whose descriptor the scalar load at `site` reads from the start of + /// a table entry, as the host tells it when it binds (`shader.rs` + /// `USER_VIEW_ADDRESS`); none for anything else. (The console's + /// descriptor holds more in the second dword, the stride from bit 16 + /// up; code that takes the address masks those away.) + fn view_address(&mut self, site: Site) -> Option<(V, V)> { + use super::shader::USER_VIEW_ADDRESS; + let a = self.scalar.get(&site).copied()?; + let rp = *self.x.native.layout.get(a.param)?; + if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 { + return None; + } + let dword = a.offset / 4; + let used = self + .x + .native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords)?; + if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) { + return None; + } + let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword); + let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword); + Some((lo, hi)) + } + + /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry. + fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) { + if off == 0 { + return (lo, hi); + } + let c = self.cur; + let i32t = self.s.t.i32; + let k = self.s.m.i32(off as u32); + let sum = self.s.m.bin(c, Bin::Add, lo, k); + // Up: a carry when the sum wrapped below `lo`. Down: a borrow when + // it wrapped above. + let wrapped = self + .s + .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); + (sum, hi) + } + + /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs` + /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding + /// it and the byte in that view. A page without a copy reads zeros + /// (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, V) { + 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); + let (k16, k8) = (k(self, 16), k(self, 0xFF)); + let low = self.s.m.bin(c, Bin::LShr, lo, k16); + let high = self.s.m.bin(c, Bin::And, hi, k8); + let high = self.s.m.bin(c, Bin::Shl, high, k16); + let page = self.s.m.bin(c, Bin::Or, low, high); + // Inside the directory whatever the address (lanes that do not run + // compute one too); its last entry is never filled. + let last = k(self, MEMORY_PAGES - 1); + 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); + let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4)); + let entry = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[directory, at, iu, both, align], + ); + let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); + let (copy, start) = (self.as_int(copy), self.as_int(start)); + // A page without a copy: its number, at a place by the number, or + // at the sink for lanes that do not run and pages that have one. + let zero = k(self, 0); + let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero); + if let Some(g) = guard { + missing = self.s.m.bin(c, Bin::And, missing, g); + } + let places = k(self, MEMORY_FAULTS - 1); + let place = self.s.m.bin(c, Bin::URem, page, places); + let one = k(self, 1); + let place = self.s.m.bin(c, Bin::Add, place, one); + let k2 = k(self, 2); + let place = self.s.m.bin(c, Bin::Shl, place, k2); + let place = self.s.m.select(c, missing, place, zero); + let faults = self.s.root_uav_handle(SLOT_FAULTS); + let void = self.s.t.void; + let mask = self.s.m.i8(1); + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[faults, place, iu, page, iu, iu, iu, mask, align], + ); + let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); + let slot = self.s.m.bin(c, Bin::Add, base, copy); + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + let k64k = k(self, 0xFFFF); + let within = self.s.m.bin(c, Bin::And, lo, k64k); + let byte = self.s.m.bin(c, Bin::Add, start, within); + (h, byte) + } + + /// `global_load_*`, `global_store_*` and `global_atomic_*` on title + /// memory by address (`resource::MEMORY`): the address is the VGPR + /// pair, each lane its own. + fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { + dst, + addr, + data, + saddr, + offset, + lds, + cache, + } = &inst.fields + else { + unreachable!() + }; + if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) { + return Err("a global address with a scalar base"); + } + let Some(Operand::Vector { reg: areg, .. }) = *addr else { + return Err("a global address not in VGPRs"); + }; + let word = |l: &mut Self, k: u8| -> Result<V, Why> { + let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?; + l.i32_of(v) + }; + let (lo, hi) = (word(self, 0)?, word(self, 1)?); + let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); + let guard = self.guard(b, i)?; + let c = self.cur; + let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); + let iu = self.s.m.undef(i32t); + let align = self.s.m.i32(4); + let name = inst.name(); + let count = |rest: &str| match rest { + "dword" => Ok(1u8), + "dwordx2" => Ok(2), + "dwordx3" => Ok(3), + "dwordx4" => Ok(4), + _ => Err(name), + }; + if let Some(rest) = name.strip_prefix("global_load_") { + let n = count(rest)?; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let (h, byte) = self.memory(lo, hi, guard); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::V(reg + k), x, guard); + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("global_store_") { + let n = count(rest)?; + let d = data.as_ref().ok_or("global store data")?; + let vals = self.vgprs(inst, d, n)?; + let (h, byte) = self.memory(lo, hi, guard); + 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(align); + let at = self.begin_guarded(guard); + self.s + .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + self.end_guarded(at, &[]); + return Ok(()); + } + let Some(op) = name.strip_prefix("global_atomic_") else { + return Err(name); + }; + let d = data.as_ref().ok_or("global atomic data")?; + let v = self.vgprs(inst, d, 1)?[0]; + // With `glc` the value from before comes back, in the result + // register the instruction names. + let back = match (*dst, cache.glc) { + (Some(Operand::Vector { reg, .. }), true) => Some(reg), + _ => None, + }; + let old = match back.and_then(|reg| inst.read(Reg::V(reg))) { + Some(x) => self.i32_of(x)?, + None => self.s.m.i32(0), + }; + let (h, byte) = self.memory(lo, hi, guard); + // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed + // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. + let simple = match op { + "add" => Some((0, v)), + "sub" => { + let zero = self.s.m.i32(0); + Some((0, self.s.m.bin(c, Bin::Sub, zero, v))) + } + "and" => Some((1, v)), + "or" => Some((2, v)), + "xor" => Some((3, v)), + "smin" => Some((4, v)), + "smax" => Some((5, v)), + "umin" => Some((6, v)), + "umax" => Some((7, v)), + "swap" => Some((8, v)), + "fmin" | "fmax" => None, + _ => return Err(name), + }; + let at = self.begin_guarded(guard); + let was = match simple { + Some((code, x)) => { + let code = self.s.m.i32(code); + self.s.op( + self.cur, + "atomicBinOp.i32", + Attr::NoUnwind, + i32t, + 78, + &[h, code, byte, iu, iu, x], + ) + } + None => { + // A float minimum or maximum has no atomic operation on + // the host: the dword is exchanged for the smaller (larger) + // of itself and the value until no other thread got in + // between. Each failed pass means another one's succeeded; + // the limit only keeps a broken card from hanging. + let head = self.cur; + let mask = self.s.m.i8(1); + let first = self.s.op( + head, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + let first = self.s.m.extract(head, first, 0); + let first = self.as_int(first); + let (pass, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(head, Term::Br(pass)); + self.cur = pass; + let seen = self.s.m.phi(pass, i32t); + let n = self.s.m.phi(pass, i32t); + let (f32t, fv) = (self.s.t.f32, self.as_float(v)); + 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.as_int(wanted); + let found = self.s.op( + pass, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &[h, byte, iu, iu, seen, wanted], + ); + let one = self.s.m.i32(1); + let n1 = self.s.m.bin(pass, Bin::Add, n, one); + let lost = self.s.m.cmp(pass, pred::NE, found, seen); + let limit = self.s.m.i32(1 << 16); + let more = self.s.m.cmp(pass, pred::IULT, n1, limit); + let again = self.s.m.bin(pass, Bin::And, lost, more); + self.s.m.terminate(pass, Term::CondBr(again, pass, done)); + let zero = self.s.m.i32(0); + self.s.m.set_phi(seen, vec![(first, head), (found, pass)]); + self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]); + self.cur = done; + found + } + }; + let was = self.end_guarded(at, &[(was, old)])[0]; + if let Some(reg) = back { + self.write(inst, Reg::V(reg), was, None); + } + Ok(()) + } + + /// `s_load_dword*` from title memory by address (`resource::MEMORY`): + /// the SGPR pair plus the instruction's offsets. + fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + base: Operand::Scalar { code: base, .. }, + offset, + soffset, + .. + } = inst.fields + else { + return Err("a scalar load from memory"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u8, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory access by address"), + }; + let word = |l: &mut Self, k: u8| -> Result<V, Why> { + 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)?); + let c = self.cur; + let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + // An offset register counts up from the address. + let so = self.operand(inst, &soffset)?; + let sum = self.s.m.bin(c, Bin::Add, lo, so); + let carry = self.s.m.cmp(c, pred::IULT, sum, lo); + let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t); + hi = self.s.m.bin(c, Bin::Add, hi, carry); + lo = sum; + } + let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4)); + for first in (0..count).step_by(4) { + let n = (count - first).min(4); + let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); + let (h, byte) = self.memory(lo, hi, None); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::S(code + first + k), x, None); + } + } + Ok(()) + } + + /// A dword of a lane mask as a number: the ballot of the lanes' bits, + /// taken in the block that writes the mask (see [`MaskData`]). + fn mask_dword(&mut self, v: Value) -> Result<V, Why> { + let (lo, high) = match self.x.st.highs.get(&v) { + Some(&lo) => (lo, true), + None => (v, false), + }; + let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; + // A mask that holds lanes outside EXEC where it is written (the complement of one, + // 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)); + if !self.x.st.active.contains(&lo) && !whole { + if self.exchange.is_some() && !self.local { + need(made.unwrap_or(0)); + } + return Err(MASK_ELSEWHERE); + } + let (x, y) = match self.ballots.get(&lo) { + Some(&xy) => xy, + None => { + let at = match self.def_block.get(&lo) { + // Program inputs (EXEC on entry). + None => self.s.entry, + Some(&b) if b == self.cur_ir => self.cur, + Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?, + }; + if !self.balloting.insert(lo) { + return Err("a lane mask whose lanes depend on its own value"); + } + let bit = self.boolean(m, at); + self.balloting.remove(&lo); + let bit = bit?; + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let r = self + .s + .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); + self.s.flags |= flags::WAVE_OPS; + let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); + if self.exchange.is_some() { + // a host wave's ballot is its half's 32 bits: the halves exchange them + let b = self.def_block.get(&lo).copied(); + if self.local { + 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)) { + // (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"); + } + xy = self.exchange_halves(at, xy.0); + } + self.ballots.insert(lo, xy); + xy + } + }; + Ok(if high { y } else { x }) + } + + // ---- operands ---- + + fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> { + match *op { + Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)), + Operand::Scalar { code, .. } => { + let v = inst.read(Reg::S(code)).ok_or("an unread operand")?; + self.i32_of(v) + } + Operand::Vector { reg, .. } => { + let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?; + self.i32_of(v) + } + Operand::Const(c) => crate::resource::inline(c) + .map(|x| self.s.m.i32(x)) + .ok_or("a special operand (vccz, execz, scc, lds_direct)"), + Operand::Literal(x) => Ok(self.s.m.i32(x)), + Operand::Attr { .. } => Err("an attribute operand"), + } + } + + /// An operand read as f16 data: GFX10 puts an inline f16 constant in + /// the low half of the operand (upstream PR #637, checked there against + /// the instruction encodings; the half-and-half reading taken from PR + /// #458 gave the high half the constant too). + fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> { + match *op { + Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))), + _ => self.operand(inst, op), + } + } + + fn as_float(&mut self, x: V) -> V { + self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32) + } + + fn as_int(&mut self, f: V) -> V { + self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32) + } + + /// The SDWA operand selection of source `k`: a byte or word of the + /// dword, zero- or sign-extended (none: the whole dword). + fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + let s = v.sdwa?; + let sel = *s.src_sel.get(k)?; + let sext = s.sext >> k & 1 != 0; + (sel < 6).then_some((sel, sext)) + } + + /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended. + fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V { + let c = self.cur; + let (width, at) = if sel < 4 { + (8, 8 * sel) + } else { + (16, 16 * (sel - 4)) + }; + let left = self.s.m.i32(u32::from(32 - width - at)); + let t = self.s.m.bin(c, Bin::Shl, x, left); + let right = self.s.m.i32(32 - u32::from(width)); + let op = if sext { Bin::AShr } else { Bin::LShr }; + self.s.m.bin(c, op, t, right) + } + + /// A float source with its abs/neg modifiers. + fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let selected = Self::sdwa_src(inst, k); + let mut f = match op { + _ if selected.is_some() => { + let (sel, sext) = selected.expect("checked"); + let x = self.operand(inst, &op)?; + let x = self.select_bits(x, sel, sext); + self.as_float(x) + } + _ if k == 0 && self.src0.is_some() => { + let x = self.src0.expect("checked"); + self.as_float(x) + } + Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. } + if !matches!(op, Operand::Scalar { code: NULL, .. }) => + { + let r = if matches!(op, Operand::Vector { .. }) { + Reg::V(reg) + } else { + Reg::S(reg) + }; + let val = inst.read(r).ok_or("an unread operand")?; + 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)?; + self.as_float(x) + } + }; + 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(self.cur, Bin::Sub, z, f); + } + Ok(f) + } + + fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 { + return Err("integer operand modifiers"); + } + match self.src0 { + Some(x) if k == 0 => Ok(x), + _ => { + let x = self.operand(inst, &op)?; + Ok(match Self::sdwa_src(inst, k) { + Some((sel, sext)) => self.select_bits(x, sel, sext), + None => x, + }) + } + } + } + + fn unary(&mut self, op: u32, f: V) -> V { + self.s.op( + self.cur, + "unary.f32", + Attr::ReadNone, + self.s.t.f32, + op, + &[f], + ) + } + + fn binary(&mut self, op: u32, a: V, b: V) -> V { + self.s.op( + self.cur, + "binary.f32", + Attr::ReadNone, + self.s.t.f32, + op, + &[a, b], + ) + } + + /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's + /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where + /// the compare and select DXIL specifies gives either zero. + fn max_min(&mut self, max: bool, a: V, b: V) -> V { + let c = self.cur; + let r = self.binary(if max { 35 } else { 36 }, a, b); + let (ia, ib) = (self.as_int(a), self.as_int(b)); + let either = self.s.m.bin(c, Bin::Or, ia, ib); + let magnitude = self.s.m.i32(0x7FFF_FFFF); + let either = self.s.m.bin(c, Bin::And, either, magnitude); + let zero = self.s.m.i32(0); + let zeros = self.s.m.cmp(c, pred::EQ, either, zero); + // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min). + let op = if max { Bin::And } else { Bin::Or }; + let sign = self.s.m.bin(c, op, ia, ib); + let signed = self.as_float(sign); + self.s.m.select(c, zeros, signed, r) + } + + fn fmad(&mut self, a: V, b: V, c: V) -> V { + self.s.op( + self.cur, + "tertiary.f32", + Attr::ReadNone, + self.s.t.f32, + 46, + &[a, b, c], + ) + } + + /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even + /// conversion, one step back toward zero where it rounded away (which + /// also turns an overflow to infinity into the largest finite half). + fn f16_toward_zero(&mut self, f: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + let back = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]); + let (fa, ba) = (self.unary(6, f), self.unary(6, back)); + // Ordered: never for NaN. + let away = self.s.m.cmp(c, pred::OGT, ba, fa); + let one = self.s.m.i32(1); + let stepped = self.s.m.bin(c, Bin::Sub, h, one); + self.s.m.select(c, away, stepped, h) + } + + /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's + /// 16-bit float operations round, whatever the host's own conversion does: D3D lets + /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070: + /// `wave64_tests`). The conversion toward zero, or the next half away from zero where + /// that one is nearer, or as near and the first one odd. Past the largest half the next + /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity. + /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the + /// rounding of the exact result, 24 bits being more than twice 11 and two.) + fn f16_nearest(&mut self, f: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let lo = self.f16_toward_zero(f); + let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0)); + let hi = self.s.m.bin(c, Bin::Add, lo, one); + let size = |l: &mut Self, h: V| { + let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + l.unary(6, w) + }; + let (below, above) = (size(self, lo), size(self, hi)); + let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00)); + let m = self.s.m.bin(c, Bin::And, hi, magnitude); + let top = self.s.m.cmp(c, pred::EQ, m, infinity); + let bound = self.s.m.f32(65536.0f32.to_bits()); + let above = self.s.m.select(c, top, bound, above); + let fa = self.unary(6, f); + // (both differences are exact: the three values lie within one half's step) + let under = self.s.m.bin(c, Bin::Sub, fa, below); + let over = self.s.m.bin(c, Bin::Sub, above, fa); + // Ordered: never for NaN, which stays what the conversion made of it. + let nearer = self.s.m.cmp(c, pred::OLT, over, under); + let tie = self.s.m.cmp(c, pred::OEQ, over, under); + let odd = self.s.m.bin(c, Bin::And, lo, one); + let odd = self.s.m.cmp(c, pred::NE, odd, zero); + let tie = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, nearer, tie); + self.s.m.select(c, up, hi, lo) + } + + /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's + /// top bit when `signed`; widths from 32 on take every bit. A signed + /// field that runs past bit 31 extends from bit 31, as the hardware + /// does: the shift is arithmetic then. + fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V { + let c = self.cur; + let (k31, k32, zero, one, ones) = ( + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(0), + self.s.m.i32(1), + self.s.m.i32(u32::MAX), + ); + let off = self.s.m.bin(c, Bin::And, off, k31); + let shift = if signed { Bin::AShr } else { Bin::LShr }; + let shifted = self.s.m.bin(c, shift, a, off); + let full = self.s.m.cmp(c, pred::IUGE, width, k32); + let w = self.s.m.bin(c, Bin::And, width, k31); + let mask = self.s.m.bin(c, Bin::Shl, one, w); + let mask = self.s.m.bin(c, Bin::Sub, mask, one); + let mask = self.s.m.select(c, full, ones, mask); + let r = self.s.m.bin(c, Bin::And, shifted, mask); + if !signed { + return r; + } + // Sign-extend a field narrower than 32 bits (none for width 0). + let left = self.s.m.bin(c, Bin::Sub, k32, w); + let left = self.s.m.bin(c, Bin::And, left, k31); + let t = self.s.m.bin(c, Bin::Shl, r, left); + let t = self.s.m.bin(c, Bin::AShr, t, left); + let is0 = self.s.m.cmp(c, pred::EQ, w, zero); + let keep = self.s.m.bin(c, Bin::Or, full, is0); + self.s.m.select(c, keep, r, t) + } + + /// Whether an f32 value is NaN, tested in integer arithmetic so host + /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math. + fn is_nan_f32(&mut self, f: V) -> V { + let c = self.cur; + let bits = self.as_int(f); + let mask = self.s.m.i32(0x7FFF_FFFF); + let abs = self.s.m.bin(c, Bin::And, bits, mask); + let inf = self.s.m.i32(0x7F80_0000); + self.s.m.cmp(c, pred::IUGT, abs, inf) + } + + /// The median of three. With a NaN among them the hardware gives the + /// minimum of the three instead (the host's minimum skips NaNs, so that + /// is the smallest number among them). + fn med3(&mut self, a: V, b: V, third: V) -> V { + let c = self.cur; + let lo = self.binary(36, a, b); + let hi = self.binary(35, a, b); + let t = self.binary(36, hi, third); + let median = self.binary(35, lo, t); + let least = self.binary(36, lo, third); + let nan_a = self.is_nan_f32(a); + let nan_b = self.is_nan_f32(b); + let nan_3 = self.is_nan_f32(third); + let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b); + let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3); + self.s.m.select(c, nan, least, median) + } + + /// `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 + /// here (some give 1.0). Comparing against a `threshold` distinct from + /// `below_one` prevents drivers (observed on NVIDIA) from folding + /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN. + fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V { + let c = self.cur; + let r = self.unary(22, a); + let limit = self.s.m.f32(threshold.to_bits()); + let k = self.s.m.f32(below_one.to_bits()); + let over = self.s.m.cmp(c, pred::OGE, r, limit); + self.s.m.select(c, over, k, r) + } + + /// Sine, or cosine, of an angle in turns, as the hardware takes it. The + /// whole turns are taken off first (`x - round_even(x)`, exact, within + /// half a turn), so a large angle keeps its fraction; scaling to radians + /// first rounds it away. A zero passes unreduced (the sine of -0 is -0). + /// The sine of a half turn and the cosine of a quarter turn are exactly + /// +0 on the hardware, where the host's function of the rounded angle + /// gives about 1e-7. Infinities and NaN give NaN. + /// shortcut: below 2^-12 turns the hardware scales by a slightly + /// different constant than 2Ï€ (a last-place difference). + fn trig_turns(&mut self, x: V, cosine: bool) -> V { + let c = self.cur; + let zero = self.s.m.f32(0); + let whole = self.unary(26, x); + let part = self.s.m.bin(c, Bin::Sub, x, whole); + let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero); + let part = self.s.m.select(c, is_zero, x, part); + let k = self.s.m.f32(TWO_PI.to_bits()); + let angle = self.s.m.bin(c, Bin::Mul, part, k); + let r = self.unary(if cosine { 12 } else { 13 }, angle); + let at = if cosine { 0.25f32 } else { 0.5 }; + let at = self.s.m.f32(at.to_bits()); + let size = self.unary(6, part); + let exact = self.s.m.cmp(c, pred::OEQ, size, at); + self.s.m.select(c, exact, zero, r) + } + + /// The high dword of a 32 × 32-bit product. + fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V { + let c = self.cur; + let i64t = self.s.m.int(64); + let ext = if signed { Cast::SExt } else { Cast::ZExt }; + let a = self.s.m.cast(c, ext, a, i64t); + let b = self.s.m.cast(c, ext, b, i64t); + let m = self.s.m.bin(c, Bin::Mul, a, b); + let k32 = self.s.m.int_const(i64t, 32); + let hi = self.s.m.bin(c, Bin::LShr, m, k32); + self.s.flags |= flags::INT64; + self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32) + } + + /// `0 × anything = 0`, as in D3D9. + fn legacy_mul(&mut self, a: V, b: V) -> V { + let c = self.cur; + let m = self.s.m.bin(c, Bin::Mul, a, b); + let zero = self.s.m.f32(0); + let az = self.s.m.cmp(c, pred::OEQ, a, zero); + let bz = self.s.m.cmp(c, pred::OEQ, b, zero); + let z = self.s.m.bin(c, Bin::Or, az, bz); + self.s.m.select(c, z, zero, m) + } + + // ---- lane booleans ---- + + fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> { + if b == Bool::TRUE || b == Bool::FALSE { + return Ok(self.s.m.bool(b == Bool::TRUE)); + } + if let Some(&v) = self.bools.get(&(at, b)) { + return Ok(v); + } + 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; + let v = match (lo, hi) { + (Bool::FALSE, Bool::TRUE) => a, + (Bool::TRUE, Bool::FALSE) => { + let t = m.bool(true); + m.bin(at, Bin::Xor, a, t) + } + (Bool::FALSE, h) => { + let h = self.boolean(h, at)?; + self.s.m.bin(at, Bin::And, a, h) + } + (l, Bool::TRUE) => { + let l = self.boolean(l, at)?; + self.s.m.bin(at, Bin::Or, a, l) + } + (l, h) => { + let l = self.boolean(l, at)?; + let h = self.boolean(h, at)?; + 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<V, Why> { + match atom { + 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) => { + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, x, z)) + } + Val::Missing(w) => Err(w), + }, + Atom::Phi(id) => { + if let Some(&v) = self.mask_phis.get(&id) { + return Ok(v); + } + let &(b, i) = self + .phi_at + .get(&id) + .ok_or("a lane-mask join without a phi")?; + let blk = self.block[b].ok_or("an unreachable join")?; + let v = self.s.m.phi(blk, self.s.t.i1); + self.mask_phis.insert(id, v); + self.pending_masks.push((v, b, i)); + Ok(v) + } + // shortcut: "some lane of the quad is set" is taken as true: the + // lanes it adds only feed derivatives, and exports keep their own + // masks. Wrong if such a section had a side effect. + Atom::Quad(_) => Ok(self.s.m.bool(true)), + // With console lanes, a mask held as a number is the console's: + // the lane tests its own bit. + Atom::Opaque(v) if self.console_lanes => { + let hi = match self.pair_high(v) { + Some(h) => Some(self.get(h)?), + None => None, + }; + let lo = self.get(v)?; + let word = |w: Val| match w { + Val::I32(x) => Ok(x), + _ => Err("an opaque lane mask"), + }; + let lo = word(lo)?; + let hi = hi.map(word).transpose()?; + Ok(self.lane_bit(at, lo, hi)) + } + 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); + Ok(self.lane_bit(at, lo, Some(hi))) + } + Atom::Opaque(_) => Err("an opaque lane mask"), + Atom::Constant(_) => Err("a constant lane mask"), + } + } + + /// 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 + /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it + /// found. Branch-free, in the entry block, which every thread runs. + fn wave_base(&mut self) -> Option<V> { + let slot = self.halves?; + if let Some(v) = self.wave_base { + return Some(v); + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let lds = self.s.lds(); + let k = self.s.m.i32(slot); + let ptr = self.s.m.element(e, lds, k); + 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 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]); + self.s.flags |= flags::WAVE_OPS; + self.wave_base = Some(base); + Some(base) + } + + /// The console thread index of this thread in the group: `wave_base` plus the host lane + /// (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, &[]); + 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 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); + self.s.m.bin(e, Bin::Add, base, lane) + } + + /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host + /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane. + fn console_lane(&mut self) -> V { + if self.exchange.is_none() { + return self.lane_index(); + } + if let Some(v) = self.clane { + return v; + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let f = self.console_thread(); + let _ = i32t; + let k63 = self.s.m.i32(63); + let cl = self.s.m.bin(e, Bin::And, f, k63); + self.s.flags |= flags::WAVE_OPS; + self.clane = Some(cl); + cl + } + + /// A group barrier with an LDS fence in `block`. + 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]); + } + + /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get + /// (lower half's, upper half's). A group with no upper half gets 0 for it. + fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) { + let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else { + let z = self.s.m.i32(0); + return (mine, z); + }; + if small { + let z = self.s.m.i32(0); + return (mine, z); + } + if self.local { + // each host wave on its own: its half holds `mine`, the other nothing + let cl = self.console_lane(); + let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0)); + let upper = self.s.m.cmp(at, pred::IUGE, cl, k32); + let lo = self.s.m.select(at, upper, z, mine); + let hi = self.s.m.select(at, upper, mine, z); + return (lo, hi); + } + // the pair of dwords of this thread's console wave: its half's, then both + let pair = self.exchange_pair(slot); + let cl = self.console_lane(); + let five = self.s.m.i32(5); + let half = self.s.m.bin(at, Bin::LShr, cl, five); + let index = self.s.m.bin(at, Bin::Add, pair, half); + let lds = self.s.lds(); + let ptr = self.s.m.element(at, lds, index); + self.s.m.store(at, ptr, mine); + self.group_sync(at); + let one = self.s.m.i32(1); + let k1 = self.s.m.bin(at, Bin::Add, pair, one); + let p0 = self.s.m.element(at, lds, pair); + let p1 = self.s.m.element(at, lds, k1); + let lo = self.s.m.load(at, p0); + let hi = self.s.m.load(at, p1); + // the slots are written again only after every thread read them + self.group_sync(at); + (lo, hi) + } + + /// The first of the two exchange dwords of this thread's console wave (made in the entry + /// block): a group of several console waves has a pair for each. + fn exchange_pair(&mut self, slot: u32) -> V { + if let Some(v) = self.pair { + return v; + } + let e = self.s.entry; + let thread = self.console_thread(); + let six = self.s.m.i32(6); + let wave = self.s.m.bin(e, Bin::LShr, thread, six); + let one = self.s.m.i32(1); + let twice = self.s.m.bin(e, Bin::Shl, wave, one); + let base = self.s.m.i32(slot); + let v = self.s.m.bin(e, Bin::Add, base, twice); + self.pair = Some(v); + v + } + + /// The console's decision of the branch closing IR block `b`, which the wave takes + /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken + /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or + /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`]. + /// Each host wave asks its lanes and the halves exchange the answers, so both go the + /// same way and can meet again inside the branch. + /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the + /// console wave has its bit of the result, asked where the operation stands. The lanes + /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with + /// the console's waves the host wave's answer is the console's; two host waves of 32 + /// exchange theirs, which needs every lane there. + fn scc_some(&mut self, scc: Value) -> Result<V, Why> { + let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?; + // (not for a console wave cut into host waves that do not exchange) + if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() { + return Err(LANE_MASK); + } + let made = self.def_block.get(&scc).copied(); + let at = match made { + None => self.s.entry, + Some(b) if b == self.cur_ir => self.cur, + Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, + }; + 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]); + self.s.flags |= flags::WAVE_OPS; + if !self.exchange.as_ref().is_some_and(|e| !e.1) { + return Ok(some); + } + if !made.is_none_or(|b| self.all_lanes(b)) { + need(made.unwrap_or(0)); + return Err("a lane mask exchanged where not every lane runs"); + } + let some = self.s.m.cast(at, Cast::ZExt, some, i32t); + let (lo, hi) = self.exchange_halves(at, some); + let both = self.s.m.bin(at, Bin::Or, lo, hi); + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, both, z)) + } + + fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> { + 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 { + // 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. + let c = self.cur; + 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) }; + 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) { + return Err(WHY); + } + if !self.all_lanes(b) { + need(b); + return Err(WHY); + } + let c = self.cur; + let mine = self.boolean(when, c)?; + // what the halves exchange is "some lane speaks against" either way (for `any`: + // some lane's `when` holds; else: some lane's does not), so a half with no lane says + // nothing + let set = if any { + mine + } else { + let t = self.s.m.bool(true); + 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]); + 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)) + } + + /// 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)) + } + + /// This lane's bit of the mask `lo`, `hi` (wave64). + fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V { + self.s.flags |= flags::WAVE_OPS; + let lane = if self.exchange.is_some() { + self.console_lane() + } else { + self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) + }; + let (k31, k32, one, z) = ( + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(1), + self.s.m.i32(0), + ); + let word = match hi { + Some(hi) => { + let low = self.s.m.cmp(at, pred::IULT, lane, k32); + self.s.m.select(at, low, lo, hi) + } + None => lo, + }; + let sh = self.s.m.bin(at, Bin::And, lane, k31); + let t = self.s.m.bin(at, Bin::LShr, word, sh); + let t = self.s.m.bin(at, Bin::And, t, one); + self.s.m.cmp(at, pred::NE, t, z) + } + + /// The value of the high dword of the wave64 register pair whose low + /// dword holds `lo` (none in wave32). + fn pair_high(&self, lo: Value) -> Option<Value> { + if !self.x.native.wave64 { + return None; + } + let p = self.x.p; + let pick = |reg: Reg| match reg { + Reg::S(c) => Some(Reg::S(c + 1)), + _ => None, + }; + if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) { + let h = pick(reg)?; + return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1); + } + if let Some(&(b, i)) = self.phi_at.get(&lo) { + let h = pick(p.blocks[b].phis[i].reg)?; + return p.blocks[b] + .phis + .iter() + .find(|q| q.reg == h) + .map(|q| q.value); + } + let b = *self.def_block.get(&lo)?; + let inst = p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == lo))?; + let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?; + inst.write(pick(reg)?) + } + + fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> { + match self.x.st.guards[b][i] { + None => Ok(None), + Some(g) => Ok(Some(self.boolean(g, self.cur)?)), + } + } + + // ---- results ---- + + fn set(&mut self, v: Option<Value>, val: Val) { + if let Some(v) = v { + self.vals.insert(v, val); + } + } + + /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`. + fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) { + let x = match (Self::sdwa_dst(inst), reg) { + (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused), + _ => x, + }; + self.write_placed(inst, reg, x, guard); + } + + /// [`Self::write`] of a dword already placed (SDWA applied). + fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) { + let Some(new) = inst.write(reg) else { return }; + let x = match (guard, reg) { + (Some(g), Reg::V(_)) => { + 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, + }; + self.vals.insert(new, Val::I32(x)); + } + + /// The SDWA destination selection: a byte or word, and what the other + /// bits get (0 zeros, 1 the sign above the field, 2 the old bits). + fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + let s = v.sdwa?; + (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused)) + } + + /// The low byte or word of `x` placed at `sel` in VGPR `reg`. + fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V { + let c = self.cur; + let (width, at) = if sel < 4 { + (8u32, 8 * u32::from(sel)) + } else { + (16, 16 * u32::from(sel - 4)) + }; + let left = self.s.m.i32(32 - width); + let t = self.s.m.bin(c, Bin::Shl, x, left); + let right = self.s.m.i32(32 - width - at); + if unused == 1 { + // Bits below the field shift in as zeros. + return self.s.m.bin(c, Bin::AShr, t, right); + } + let field = self.s.m.bin(c, Bin::LShr, t, right); + if unused != 2 { + return field; + } + 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) + } + + fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let mut f = f; + match v.omod { + 0 => {} + k => { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)]; + let c = self.s.m.f32(factor.to_bits()); + f = self.s.m.bin(self.cur, Bin::Mul, f, c); + } + } + if v.clamp { + f = self.unary(7, f); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a float result outside a VGPR"); + }; + let x = self.as_int(f); + self.write(inst, Reg::V(reg), x, guard); + if guard.is_none() + && Self::sdwa_dst(inst).is_none() + && let Some(new) = inst.write(Reg::V(reg)) + { + self.floats.insert(new, f); + } + Ok(()) + } + + fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.clamp || v.omod != 0 { + return Err("integer output modifiers"); + } + match v.dst { + Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard), + Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None), + _ => return Err("a result without a register"), + } + Ok(()) + } + + /// Starts code only the lanes where `guard` holds run (a store under a + /// lane guard): returns where it started and the join block. + fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> { + let g = guard?; + let (then, join) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(self.cur, Term::CondBr(g, then, join)); + let head = self.cur; + self.cur = then; + Some((head, join)) + } + + /// Ends guarded code; each (value inside, value outside) becomes a phi. + fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> { + let Some((head, join)) = at else { + return values.iter().map(|v| v.0).collect(); + }; + let then = self.cur; + self.s.m.terminate(then, Term::Br(join)); + self.cur = join; + values + .iter() + .map(|&(inside, outside)| { + let ty = self.s.m.type_of(inside); + let phi = self.s.m.phi(join, ty); + self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]); + phi + }) + .collect() + } + + /// Code that depends on the lane layout: wave operations, and in compute + /// the console's wave size (lanes are thread ids in group order there). + /// Pixel lanes match only within a quad. + fn cross_lane(&mut self, quad: bool) -> Result<(), Why> { + if self.s.mesh.is_some() { + // 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. + return Err("a cross-lane operation in a mesh shader"); + } + if self.s.threads.is_none() && !(quad && self.s.pixel) { + return Err("a cross-lane operation outside compute"); + } + debug_assert!(self.s.threads.is_none() || self.console_lanes); + self.s.flags |= flags::WAVE_OPS; + Ok(()) + } + + /// Component `c` of the thread id in the group. With console lanes, the + /// thread is relabelled so that its host lane is its console lane: the + /// flat id is the wave's first lane's, rounded down to the wave size, + /// plus the lane index. (A bijection while each host wave holds a + /// wave-aligned run of flat ids, as the console's waves do.) + fn thread_id(&mut self, c: u8) -> Val { + if !self.console_lanes { + return self.compute_id("threadIdInGroup.i32", 95, c); + } + let [x, y, _] = self.s.threads.expect("compute"); + let e = self.s.entry; + let i32t = self.s.t.i32; + if self.halves.is_some() { + let f = self.console_thread(); + self.s.flags |= flags::WAVE_OPS; + let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); + return Val::I32(match c { + 0 => self.s.m.bin(e, Bin::URem, f, xk), + 1 => { + let t = self.s.m.bin(e, Bin::UDiv, f, xk); + self.s.m.bin(e, Bin::URem, t, yk) + } + _ => self.s.m.bin(e, Bin::UDiv, f, xy), + }); + } + 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.expect("set with console lanes"); + let mask = self.s.m.i32(!(wave - 1)); + let base = self.s.m.bin(e, Bin::And, first, mask); + let lane = self.lane_index(); + let f = self.s.m.bin(e, Bin::Add, base, lane); + self.s.flags |= flags::WAVE_OPS; + let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); + Val::I32(match c { + 0 => self.s.m.bin(e, Bin::URem, f, xk), + 1 => { + let t = self.s.m.bin(e, Bin::UDiv, f, xk); + self.s.m.bin(e, Bin::URem, t, yk) + } + _ => self.s.m.bin(e, Bin::UDiv, f, xy), + }) + } + + /// Mesh: the counts and the primitives no lane exports. The console's + /// counts come from one lane's allocation request, which DXIL cannot + /// express (one call, dominating every output write). + // shortcut: the counts are the declared maxima and each lane first culls + // its primitive (all indices 0, zero area), so primitives past the + // program's count are culled and vertices past it unused; this costs + // the host the unused vertex and primitive slots. Pass the program's own + // counts if that shows in frame time. + fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> { + let threads = self.s.threads.expect("mesh")[0]; + if mesh.topology != 2 { + return Err("a mesh shader not drawing triangles"); + } + if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { + return Err("a mesh shader beyond the host's limits"); + } + // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n + // writes only vertex n and primitive n, so maxima past the lanes are + // never reached: they come down to the lane count when the outputs + // do not fit. + use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes}; + let (outputs, prims) = (&self.s.outputs, &self.s.prims); + let fits = |m: super::shader::Mesh| { + mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT + }; + if !fits(mesh) { + mesh.max_vertices = mesh.max_vertices.min(threads); + mesh.max_primitives = mesh.max_primitives.min(threads); + // shortcut: outputs past the cap even at the lane count are + // still emitted with the lower maxima (drivers take them); + // refuse them here if one hangs. + // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused. + if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() { + return Err("a mesh shader whose outputs pass the host's 32 KiB"); + } + self.s.mesh = Some(mesh); + } + let e = self.s.entry; + let void = self.s.t.void; + let (v, p) = ( + self.s.m.i32(mesh.max_vertices), + self.s.m.i32(mesh.max_primitives), + ); + self.s + .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + let flat = self.mesh_thread(); + let z = self.s.m.i32(0); + // Every primitive of the declared count starts culled, also those + // past the lanes (a count of 256 with 128 lanes): lane n culls + // primitives n, n + lanes, ... The host draws all it was promised, + // and one never written has whatever indices its memory held: long + // triangles over the whole target, each pixel of them shaded. + let passes = mesh.max_primitives.div_ceil(threads.max(1)); + for pass in 0..passes { + let index = if pass == 0 { + flat + } else { + let past = self.s.m.i32(pass * threads); + self.s.m.bin(self.cur, Bin::Add, flat, past) + }; + let guard = ((pass + 1) * threads > mesh.max_primitives) + .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p)); + let at = self.begin_guarded(guard); + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[index, z, z, z], + ); + self.end_guarded(at, &[]); + } + Ok(()) + } + + /// Mesh: the thread's index in the group, which is its vertex and + /// primitive index. + fn mesh_thread(&mut self) -> V { + if let Some(f) = self.flat { + return f; + } + let e = self.s.entry; + let f = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + self.s.t.i32, + 96, + &[], + ); + self.flat = Some(f); + f + } + + /// The console wave size. + fn wave(&self) -> u32 { + if self.x.native.wave64 { 64 } else { 32 } + } + + fn lane_index(&mut self) -> V { + 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(); + let m = self.s.m.i32(self.wave() - 1); + return self.s.m.bin(self.s.entry, Bin::And, f, m); + } + self.s.op( + self.cur, + "waveGetLaneIndex", + Attr::ReadOnly, + self.s.t.i32, + 111, + &[], + ) + } + + /// `x` of lane `src` (in this lane's quad) through quad reads, whose + /// lane must be a constant. + fn quad_pick(&mut self, x: V, src: V) -> V { + self.s.flags |= flags::WAVE_OPS; + let c = self.cur; + let three = self.s.m.i32(3); + let q = self.s.m.bin(c, Bin::And, src, three); + let mut r = x; + for n in 0..4 { + let kn = self.s.m.i32(n); + let read = self.s.op( + c, + "quadReadLaneAt.i32", + Attr::NoUnwind, + self.s.t.i32, + 122, + &[x, kn], + ); + let is = self.s.m.cmp(c, pred::EQ, q, kn); + r = self.s.m.select(c, is, read, r); + } + r + } + + /// `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. + fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) { + 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 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 (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 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 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) + } + + fn read_lane(&mut self, x: V, lane: V) -> V { + self.s.op( + self.cur, + "waveReadLaneAt.i32", + Attr::NoUnwind, + self.s.t.i32, + 117, + &[x, lane], + ) + } + + /// The float value of a register value. + fn float_of(&mut self, v: Value) -> Result<V, Why> { + if let Some(&f) = self.floats.get(&v) { + return Ok(f); + } + let x = self.i32_of(v)?; + Ok(self.as_float(x)) + } + + /// The values of VGPRs `reg..reg + n` as `inst` reads them. + fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> { + let Operand::Vector { reg, .. } = *op else { + return Err("a vector operand"); + }; + (0..n) + .map(|k| { + let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?; + self.i32_of(v) + }) + .collect() + } + + /// LDS (thread-group shared memory) and `ds_swizzle`. + fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Ds { + dst, + addr, + data, + offset0, + offset1, + gds, + } = &inst.fields + else { + unreachable!() + }; + if *gds { + return Err("GDS"); + } + let name = inst.name(); + let guard = self.guard(b, i)?; + let c = self.cur; + let offset = u32::from(*offset0) | u32::from(*offset1) << 8; + let dst_reg = match dst { + Some(Operand::Vector { reg, .. }) => Some(*reg), + _ => None, + }; + if name == "ds_swizzle_b32" { + // Bit 15 set: each lane of a quad picks a lane of it; else lanes + // of each group of 32 combine their index with and/or/xor masks. + let quad = offset & 0x8000 != 0 + || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4; + // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the + // console's, so quad-local swizzles read through quad operations. + let mesh_quad = self.s.mesh.is_some() && quad; + if !mesh_quad { + self.cross_lane(quad)?; + } + // The source sits in the address field. + let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0]; + let lane = self.lane_index(); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let src = if offset & 0x8000 != 0 { + let (three, one) = (k(self, 3), k(self, 1)); + let sel = self.s.m.bin(c, Bin::And, lane, three); + let sh = self.s.m.bin(c, Bin::Shl, sel, one); + let pattern = k(self, offset & 0xFF); + let pick = self.s.m.bin(c, Bin::LShr, pattern, sh); + let pick = self.s.m.bin(c, Bin::And, pick, three); + let not3 = k(self, !3); + let base = self.s.m.bin(c, Bin::And, lane, not3); + self.s.m.bin(c, Bin::Or, base, pick) + } else { + let and = k(self, offset & 0x1F | !0x1F); + let or = k(self, offset >> 5 & 0x1F); + let xor = k(self, offset >> 10 & 0x1F); + let t = self.s.m.bin(c, Bin::And, lane, and); + let t = self.s.m.bin(c, Bin::Or, t, or); + self.s.m.bin(c, Bin::Xor, t, xor) + }; + let r = if mesh_quad { + self.quad_pick(x, src) + } else { + self.read_lane(x, src) + }; + let reg = dst_reg.ok_or("a swizzle result")?; + self.write(inst, Reg::V(reg), r, guard); + return Ok(()); + } + 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 + // 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 + // host (it left through a branch, not a guard) is read as the + // host gives it; the console reads 0. + self.cross_lane(false)?; + if self.exchange.as_ref().is_some_and(|e| !e.1) { + // a console wave of 64 run as two host waves: the lane named + // may be in the other one + return Err("a lane permute across two host waves"); + } + let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0]; + let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0]; + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, at, o); + let two = self.s.m.i32(2); + let src = self.s.m.bin(c, Bin::LShr, at, two); + let last = self.s.m.i32(self.wave() - 1); + let src = self.s.m.bin(c, Bin::And, src, last); + let x = match guard { + Some(g) => { + let z = self.s.m.i32(0); + self.s.m.select(c, g, x, z) + } + None => x, + }; + let r = self.read_lane(x, src); + let reg = dst_reg.ok_or("a permute result")?; + self.write(inst, Reg::V(reg), r, guard); + return Ok(()); + } + if self.s.lds_dwords == 0 { + return Err("LDS the program does not allocate"); + } + let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0]; + // shortcut: LDS addresses are taken as dword-aligned and in bounds + // (out-of-bounds console accesses read 0 and drop writes). + let dword = |l: &mut Self, bytes: u32| -> V { + let c = l.cur; + let o = l.s.m.i32(bytes); + let at = l.s.m.bin(c, Bin::Add, a, o); + let two = l.s.m.i32(2); + let index = l.s.m.bin(c, Bin::LShr, at, two); + let lds = l.s.lds(); + l.s.m.element(c, lds, index) + }; + let width = |n: &str| match n.rsplit('_').next() { + Some("b64") => 2, + Some("b96") => 3, + Some("b128") => 4, + _ => 1, + }; + // (byte offset, dwords) per element; read2/write2 scale their two + // offsets by the element size (×64 for st64). + let pair = |n: &str| -> Vec<(u32, u32)> { + let w = width(n); + let scale = 4 * w * if n.contains("st64") { 64 } else { 1 }; + vec![ + (u32::from(*offset0) * scale, w), + (u32::from(*offset1) * scale, w), + ] + }; + // Bytes and halves: the dword holding them, and their bit position + // in it (naturally aligned, so they never straddle dwords). + // `_d16` reads fill a register's low half (`_d16_hi` its high half) + // and keep the other; `_d16_hi` writes take the data's high half. + let base = name.trim_end_matches("_hi").trim_end_matches("_d16"); + let sub = match base { + "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32), + "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16), + _ => None, + }; + let sub = sub.filter(|_| { + base == name + || name.ends_with("_d16") && base.starts_with("ds_read") + || name.ends_with("_d16_hi") + }); + if let Some(bits) = sub { + let p = dword(self, offset); + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, a, o); + let three = self.s.m.i32(3); + let byte = self.s.m.bin(c, Bin::And, at, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + let mask = self.s.m.i32((1u32 << bits) - 1); + if name.starts_with("ds_read") { + let reg = dst_reg.ok_or("an LDS read result")?; + let w = self.s.m.load(c, p); + let x = self.s.m.bin(c, Bin::LShr, w, sh); + let x = if base.contains("_i") { + let k = self.s.m.i32(32 - bits); + let x = self.s.m.bin(c, Bin::Shl, x, k); + self.s.m.bin(c, Bin::AShr, x, k) + } else { + self.s.m.bin(c, Bin::And, x, mask) + }; + let x = if base == name { + x + } else { + let old = match inst.read(Reg::V(reg)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + let half = self.s.m.i32(0xFFFF); + let x = self.s.m.bin(c, Bin::And, x, half); + let (x, keep) = if name.ends_with("_hi") { + let k16 = self.s.m.i32(16); + (self.s.m.bin(c, Bin::Shl, x, k16), half) + } else { + (x, self.s.m.i32(0xFFFF_0000)) + }; + let old = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, old, x) + }; + self.write(inst, Reg::V(reg), x, guard); + } else { + // Clear, then set: two atomics, so lanes writing other + // bytes of the dword keep theirs. + let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0]; + if name != base { + // The data's high half. + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let x = self.s.m.bin(c, Bin::And, x, mask); + let x = self.s.m.bin(c, Bin::Shl, x, sh); + let m = self.s.m.bin(c, Bin::Shl, mask, sh); + let ones = self.s.m.i32(u32::MAX); + let keep = self.s.m.bin(c, Bin::Xor, m, ones); + use super::bitcode::Rmw; + let at = self.begin_guarded(guard); + self.s.m.atomic(self.cur, Rmw::And, p, keep); + self.s.m.atomic(self.cur, Rmw::Or, p, x); + self.end_guarded(at, &[]); + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("ds_read") { + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] + } else { + return Err("an LDS read of bytes or halves"); + }; + let reg = dst_reg.ok_or("an LDS read result")?; + let mut n = 0; + for (off, w) in elements { + for k in 0..w { + let p = dword(self, off + 4 * k); + let x = self.s.m.load(self.cur, p); + self.write(inst, Reg::V(reg + n), x, guard); + n += 1; + } + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("ds_write") { + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] + } else { + return Err("an LDS write of bytes or halves"); + }; + let mut stores = Vec::new(); + for (e, (off, w)) in elements.into_iter().enumerate() { + let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?; + for (k, x) in vals.into_iter().enumerate() { + stores.push((off + 4 * k as u32, x)); + } + } + let at = self.begin_guarded(guard); + for (off, x) in stores { + let p = dword(self, off); + self.s.m.store(self.cur, p, x); + } + self.end_guarded(at, &[]); + return Ok(()); + } + // Atomics: the old value returns with `_rtn`. + let op = name + .strip_prefix("ds_") + .map(|n| n.replace("_rtn", "")) + .ok_or("an LDS operation")?; + use super::bitcode::Rmw; + let rmw = match op.as_str() { + "add_u32" => Some(Rmw::Add), + "sub_u32" => Some(Rmw::Sub), + "and_b32" => Some(Rmw::And), + "or_b32" => Some(Rmw::Or), + "xor_b32" => Some(Rmw::Xor), + "min_i32" => Some(Rmw::Min), + "max_i32" => Some(Rmw::Max), + "min_u32" => Some(Rmw::UMin), + "max_u32" => Some(Rmw::UMax), + "wrxchg_b32" => Some(Rmw::Xchg), + "cmpst_b32" | "max_f32" | "min_f32" => None, + _ => return Err("an LDS operation"), + }; + let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0]; + let v1 = match data.get(1) { + Some(d) => Some(self.vgprs(inst, d, 1)?[0]), + None => None, + }; + 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() { + "max_f32" => Some(true), + "min_f32" => Some(false), + _ => None, + } { + let at = self.begin_guarded(guard); + let r = self.lds_float_min_max(p, v0, max); + let r = self.end_guarded(at, &[(r, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } + let at = self.begin_guarded(guard); + let r = match rmw { + Some(op) => self.s.m.atomic(self.cur, op, p, v0), + // Compare with data0, store data1. + None => self + .s + .m + .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?), + }; + let r = self.end_guarded(at, &[(r, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + Ok(()) + } + + /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with + /// the float bits `data`; the old bits return. + /// + /// DXIL has no float atomics on group-shared memory, so this is a + /// compare-exchange loop around [`Lower::lds_float_pick`], which gives + /// what RDNA2 writes (measured on gfx1036, reported on the pull + /// request): 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. + // shortcut: f32 denormals compare as kept; with the console's MODE + // flushing them they would order as ±0 first (MODE is not modelled). + fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V { + let pre = self.cur; + let init = self.s.m.load(pre, p); + let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(pre, Term::Br(lp)); + let i32t = self.s.t.i32; + let old = self.s.m.phi(lp, i32t); + self.cur = lp; + let new = self.lds_float_pick(old, data, max); + let prev = self.s.m.cmpxchg(lp, p, old, new); + let done = self.s.m.cmp(lp, pred::EQ, prev, old); + self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]); + self.s.m.terminate(lp, Term::CondBr(done, exit, lp)); + self.cur = exit; + old + } + + /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword + /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]). + fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (abs_mask, inf, quiet, zero) = ( + k(self, 0x7FFF_FFFF), + k(self, 0x7F80_0000), + k(self, 0x40_0000), + k(self, 0), + ); + let nan = |l: &mut Self, x: V| { + let m = l.s.m.bin(c, Bin::And, x, abs_mask); + l.s.m.cmp(c, pred::IUGT, m, inf) + }; + let snan = |l: &mut Self, x: V| { + let n = nan(l, x); + let q = l.s.m.bin(c, Bin::And, x, quiet); + let sig = l.s.m.cmp(c, pred::EQ, q, zero); + l.s.m.bin(c, Bin::And, n, sig) + }; + // A total order of the numbers as signed integers, -0 below +0: + // negative floats' magnitude bits reversed. + let key = |l: &mut Self, x: V| { + let k31 = l.s.m.i32(31); + let sign = l.s.m.bin(c, Bin::AShr, x, k31); + let flip = l.s.m.bin(c, Bin::And, sign, abs_mask); + l.s.m.bin(c, Bin::Xor, x, flip) + }; + let (dk, mk) = (key(self, data), key(self, mem)); + let take = self + .s + .m + .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk); + let r = self.s.m.select(c, take, data, mem); + let (dn, mn) = (nan(self, data), nan(self, mem)); + // One NaN: the number; two quiet NaNs: the data. + let r = self.s.m.select(c, mn, data, r); + let both = self.s.m.bin(c, Bin::And, dn, mn); + let only_data = { + let t = self.s.m.bool(true); + let not_both = self.s.m.bin(c, Bin::Xor, both, t); + self.s.m.bin(c, Bin::And, dn, not_both) + }; + let r = self.s.m.select(c, only_data, mem, r); + // Signalling NaNs win, quieted: the data's first. + let qm = self.s.m.bin(c, Bin::Or, mem, quiet); + let sm = snan(self, mem); + let r = self.s.m.select(c, sm, qm, r); + let qd = self.s.m.bin(c, Bin::Or, data, quiet); + let sd = snan(self, data); + self.s.m.select(c, sd, qd, r) + } + + // ---- instructions ---- + // ---- instructions ---- + + fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { + let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; + let offset = inst.machine.offset; + let name = inst.name(); + self.local_ok = name.starts_with("s_bcnt1_i32_") + || name.starts_with("s_ff1_i32_") + || name.starts_with("v_mbcnt_"); + self.mask_ok = match self.mask_data { + MaskData::Console => true, + MaskData::Host => { + name.starts_with("s_bcnt1_i32_") + || name.starts_with("s_ff1_i32_") + || name.starts_with("v_mbcnt_") + || matches!( + name, + "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64" + ) + } + // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which + // each host wave answers for itself. + MaskData::None => self.uniform_test(inst), + }; + let effect = matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || name == "s_barrier" + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + if self.split_lds + && matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_swizzle") || name.contains("permute")) + && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b]) + { + // the two host waves of a console wave meet before each LDS access: what the other + // 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]); + } + let r = match &inst.fields { + Fields::Sop { .. } => self.sop(inst), + Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), + Fields::Sopp { .. } if name == "s_barrier" => { + // Thread-group sync with a shared-memory fence, and a UAV + // fence when the program writes UAVs (the waits before an + // s_barrier make those writes visible on the console). + let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + // Without the wait for the group (bit 0) where not every + // lane arrives, or where the switch says so. + let waits = match super::group_sync() { + 0 => false, + 1 => !self.fence_only.contains(&b), + _ => true, + }; + if !waits { + mode &= !1; + } + let mode = self.s.m.i32(mode); + let void = self.s.t.void; + self.s + .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + Ok(()) + } + Fields::Sopp { .. } => Ok(()), + Fields::Smem { .. } => self.smem(inst, (b, i)), + Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)), + Fields::Valu(_) => self.valu(inst, b, i), + Fields::Vintrp { .. } => self.interp(inst, (b, i)), + // The ray and node test. A failure is a refusal at once: an + // instruction without a side effect otherwise only stops the + // 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)); + } + Fields::Image { .. } => self.image(inst, b, i), + Fields::Buffer { .. } => self.buffer(inst, b, i), + Fields::Exp { .. } => self.export(b, i), + Fields::Ds { .. } => self.ds(inst, b, i), + Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i), + Fields::Flat { .. } => Err("flat memory"), + }; + match r { + Ok(()) => Ok(()), + Err(why) if effect => Err(unsupported(offset, why)), + Err(why) => { + for &(_, v) in &inst.writes { + self.vals.insert(v, Val::Missing(why)); + } + Ok(()) + } + } + } + + /// The two host waves of a console wave meet (a group barrier with a shared-memory + /// fence): LDS writes before are seen by reads after. + 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]); + } + + /// Whether `v` is a register no program reads as a number: a descriptor dword without + /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot + /// gives the mask as data), or a join of only such values. Compiled code joins numbers + /// with numbers: where one of these meets numbers at a join, the register is dead on + /// that path (a variable set in one arm of a branch, its use behind a flag kept in a + /// VGPR). + fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool { + if self.stale.contains(&v) { + return true; + } + let st = self.x.st; + if self.mask_data != MaskData::Console + && (st.masks.contains_key(&v) || st.highs.contains_key(&v)) + { + return true; + } + let Some(&(b, i)) = self.phi_at.get(&v) else { + return false; + }; + if seen.contains(&v) { + return true; + } + seen.push(v); + self.x.p.blocks[b].phis[i] + .args + .iter() + .all(|&a| self.dead(a, seen)) + } + + /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value: + /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The + /// compiler tests a value for being the same in the whole wave this way, to take a + /// scalar path; both paths give each lane the same result, so the lanes of a host + /// wave may ask it of their own first lane, whatever the wave's size. + fn uniform_test(&self, inst: &Inst) -> bool { + let p = self.x.p; + let writer = |v: Value| -> Option<&'a Inst> { + let b = *self.def_block.get(&v)?; + p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == v)) + }; + let scalar = |i: &Inst, op: &Operand| match *op { + Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)), + _ => None, + }; + if !inst.name().starts_with("s_bcnt1_i32_") { + return false; + } + let Fields::Sop { src, .. } = &inst.fields else { + return false; + }; + let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else { + return false; + }; + let Fields::Sop { src, .. } = &xor.fields else { + return false; + }; + if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32") + || !src + .iter() + .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. })) + { + return false; + } + let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else { + return false; + }; + 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() { + return false; + } + let lanes = f.src.iter().find_map(|o| match *o { + Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)), + _ => None, + }); + let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer); + lanes.is_some() + && first.is_some_and(|fl| { + fl.name() == "v_readfirstlane_b32" + && matches!(&fl.fields, Fields::Valu(g) + if matches!(g.src.first(), Some(&Operand::Vector { reg, .. }) + if fl.read(Reg::V(reg)) == lanes)) + }) + } + + fn is_mask(&self, v: Option<Value>) -> bool { + v.is_some_and(|v| self.x.st.masks.contains_key(&v)) + } + + fn sop(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Sop { dst, src, imm } = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + let scc = inst.write(Reg::Scc); + let dst_code = match dst { + Some(Operand::Scalar { code, .. }) => Some(*code), + _ => None, + }; + let lo = dst_code.and_then(|c| inst.write(Reg::S(c))); + if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) { + return Err(LANE_MASK); + } + if matches!( + name, + "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version" + ) || name.starts_with("s_waitcnt") + { + // shortcut: the float MODE register is not modelled; s_swappc_b64 is the + // vertex fetch call, whose results arrive as inputs. + return Err("a register the emitter does not model"); + } + if name == "s_getpc_b64" { + // The address of the next instruction is no number the host has: tables in + // the code are read by their tracked address. As a number the counter is + // that instruction's offset in the code, so an address paths join before + // one load is the byte in the code, whichever table each path took + // (resource tracking gives such a join as the computed term, with no base). + let z = self.s.m.i32(0); + let at = self.s.m.i32(inst.machine.offset as u32 + 4); + let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); + self.set(lo, Val::I32(at)); + self.set(hi, Val::I32(z)); + return Ok(()); + } + let c = self.cur; + let src32 = |l: &mut Self, k: usize| -> Result<V, Why> { + // SOPK arithmetic reads its destination as the first source. + if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") { + let d = dst.as_ref().ok_or("a missing operand")?; + return l.operand(inst, d); + } + let op = src.get(k).ok_or("a missing operand")?; + l.operand(inst, op) + }; + let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32); + // Dword `h` of 64-bit source `k` (inline constants sign-extend). + let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> { + match src.get(k) { + Some(&Operand::Scalar { code, .. }) if code != NULL => { + let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?; + l.i32_of(v) + } + Some(op) if h == 0 => l.operand(inst, op), + Some(Operand::Const(k)) => { + let x = crate::resource::inline(*k).ok_or("a special operand")?; + Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) + } + _ => Ok(l.s.m.i32(0)), + } + }; + if let Some(op) = name.strip_prefix("s_bitcmp") { + // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form) + // of src0 is clear (bitcmp0) or set (bitcmp1). + let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31)); + let idx = self.s.m.bin(c, Bin::And, bit, k31); + let word = if op.ends_with("_b64") { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let k32 = self.s.m.i32(32); + let upper = self.s.m.bin(c, Bin::And, bit, k32); + let z = self.s.m.i32(0); + let upper = self.s.m.cmp(c, pred::NE, upper, z); + self.s.m.select(c, upper, b, a) + } else { + src32(self, 0)? + }; + let shifted = self.s.m.bin(c, Bin::LShr, word, idx); + let one = self.s.m.i32(1); + let tested = self.s.m.bin(c, Bin::And, shifted, one); + let want = self.s.m.i32(u32::from(op.starts_with('1'))); + let r = self.s.m.cmp(c, pred::EQ, tested, want); + self.set(scc, Val::Bit(r)); + return Ok(()); + } + if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) { + // eq and lg only: both dwords. + let mut r = None; + for h in 0..2 { + let (a, b) = (half(self, 0, h)?, half(self, 1, h)?); + let e = self.s.m.cmp(c, pred::EQ, a, b); + r = Some(match r { + Some(x) => self.s.m.bin(c, Bin::And, x, e), + None => e, + }); + } + let mut r = r.expect("two dwords"); + if op.starts_with("lg") { + let t = self.s.m.bool(true); + r = self.s.m.bin(c, Bin::Xor, r, t); + } + self.set(scc, Val::Bit(r)); + return Ok(()); + } + if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) { + let (a, b) = if name.starts_with("s_cmpk_") { + let b = if op.ends_with("_i32") { + sext16(self) + } else { + self.s.m.i32(u32::from(imm.unwrap_or(0))) + }; + (src32(self, 0)?, b) + } else { + if op.ends_with("64") { + return Err("a 64-bit scalar compare"); + } + (src32(self, 0)?, src32(self, 1)?) + }; + let signed = op.ends_with("_i32"); + let p = match &op[..2] { + "eq" => pred::EQ, + "lg" => pred::NE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + "lt" => pred::IULT, + "le" => pred::IULE, + _ => return Err("a scalar compare"), + }; + let r = self.s.m.cmp(c, p, a, b); + self.set(scc, Val::Bit(r)); + return Ok(()); + } + let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64"); + if wide { + let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); + let nonzero = |l: &mut Self, a: V, b: V| { + let o = l.s.m.bin(c, Bin::Or, a, b); + let z = l.s.m.i32(0); + l.s.m.cmp(c, pred::NE, o, z) + }; + return match name { + "s_bcnt1_i32_b64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let i32t = self.s.t.i32; + let na = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]); + let nb = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]); + let r = self.s.m.bin(c, Bin::Add, na, nb); + self.set(lo, Val::I32(r)); + let z = self.s.m.i32(0); + let s = self.s.m.cmp(c, pred::NE, r, z); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_ff1_i32_b64" => { + // The lowest set bit; -1 for none (as DXIL's first bit low). + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let i32t = self.s.t.i32; + let fa = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]); + let fb = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]); + let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); + let fb32 = self.s.m.bin(c, Bin::Add, fb, k32); + let none = self.s.m.cmp(c, pred::EQ, b, z); + let fb = self.s.m.select(c, none, fb, fb32); + let low = self.s.m.cmp(c, pred::NE, a, z); + let r = self.s.m.select(c, low, fa, fb); + self.set(lo, Val::I32(r)); + Ok(()) + } + "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64" + | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => { + let ones = self.s.m.i32(u32::MAX); + let mut r = Vec::new(); + for h in 0..2u8 { + let a = half(self, 0, h)?; + let x = if name == "s_not_b64" { + self.s.m.bin(c, Bin::Xor, a, ones) + } else { + let mut b = half(self, 1, h)?; + if name.contains("n2") { + b = self.s.m.bin(c, Bin::Xor, b, ones); + } + let op = match &name[2..5] { + "and" | "nan" => Bin::And, + "or_" | "orn" | "nor" => Bin::Or, + _ => Bin::Xor, + }; + let x = self.s.m.bin(c, op, a, b); + if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") { + self.s.m.bin(c, Bin::Xor, x, ones) + } else { + x + } + }; + r.push(x); + } + self.set(lo, Val::I32(r[0])); + self.set(hi, Val::I32(r[1])); + let s = nonzero(self, r[0], r[1]); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let n = src32(self, 1)?; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let a = self.s.m.cast(c, Cast::ZExt, a, i64t); + let b = self.s.m.cast(c, Cast::ZExt, b, i64t); + let k32 = self.s.m.int_const(i64t, 32); + let b = self.s.m.bin(c, Bin::Shl, b, k32); + let x = self.s.m.bin(c, Bin::Or, a, b); + let k63 = self.s.m.i32(63); + let n = self.s.m.bin(c, Bin::And, n, k63); + let n = self.s.m.cast(c, Cast::ZExt, n, i64t); + let op = match name { + "s_lshl_b64" => Bin::Shl, + "s_lshr_b64" => Bin::LShr, + _ => Bin::AShr, + }; + let r = self.s.m.bin(c, op, x, n); + let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32); + let rh = self.s.m.bin(c, Bin::LShr, r, k32); + let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32); + self.set(lo, Val::I32(rl)); + self.set(hi, Val::I32(rh)); + let s = nonzero(self, rl, rh); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_mov_b64" => { + // Each half by itself: two numbers that travel as a pair (two scalars + // parked in neighbouring VGPR lanes, say) need not both have a value. + for (h, v) in [(0, lo), (1, hi)] { + let val = match half(self, 0, h) { + Ok(a) => Val::I32(a), + Err(why) => Val::Missing(why), + }; + self.set(v, val); + } + Ok(()) + } + "s_cselect_b64" => { + let cond = self.scc_in(inst)?; + for (h, v) in [(0, lo), (1, hi)] { + let (a, b) = (half(self, 0, h)?, half(self, 1, h)?); + let r = self.s.m.select(c, cond, a, b); + self.set(v, Val::I32(r)); + } + Ok(()) + } + _ => Err(name), + }; + } + let m = &mut self.s.m; + let _ = m; + let (r, carry): (V, Option<V>) = match name { + "s_mov_b32" => (src32(self, 0)?, None), + "s_movk_i32" => (sext16(self), None), + "s_cselect_b32" => { + let cond = self.scc_in(inst)?; + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + (self.s.m.select(c, cond, a, b), None) + } + "s_brev_b32" => { + let a = src32(self, 0)?; + let r = self + .s + .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]); + (r, None) + } + "s_not_b32" => { + let a = src32(self, 0)?; + let ones = self.s.m.i32(u32::MAX); + (self.s.m.bin(c, Bin::Xor, a, ones), None) + } + "s_add_u32" | "s_add_i32" | "s_addk_i32" => { + let a = src32(self, 0)?; + let b = if name == "s_addk_i32" { + sext16(self) + } else { + src32(self, 1)? + }; + let r = self.s.m.bin(c, Bin::Add, a, b); + let carry = if name == "s_add_u32" { + Some(self.s.m.cmp(c, pred::IULT, r, a)) + } else { + None + }; + (r, carry) + } + "s_sub_u32" | "s_sub_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let r = self.s.m.bin(c, Bin::Sub, a, b); + let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b)); + (r, carry) + } + "s_addc_u32" | "s_subb_u32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let cin = self.scc_in(inst)?; + let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin)); + (r, Some(carry)) + } + "s_mul_i32" | "s_mulk_i32" => { + let a = src32(self, 0)?; + let b = if name == "s_mulk_i32" { + sext16(self) + } else { + src32(self, 1)? + }; + (self.s.m.bin(c, Bin::Mul, a, b), None) + } + "s_mul_hi_u32" | "s_mul_hi_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + (self.mul_hi(a, b, name.ends_with("i32")), None) + } + "s_flbit_i32_b32" | "s_flbit_i32" => { + // The first bit from the top (differing from the sign for + // the signed form), -1 for none: DXIL's first-bit-high. + let a = src32(self, 0)?; + let op = if name == "s_flbit_i32_b32" { 33 } else { 34 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + (r, None) + } + "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => { + // First set bit (-1 for zero, as DXIL's), or the bit count. + let a = src32(self, 0)?; + let op = if name == "s_ff1_i32_b32" { 32 } else { 31 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + (r, None) + } + "s_bfe_u32" | "s_bfe_i32" => { + // src1: offset in bits 0-4, width in bits 16-22. + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F)); + let w = self.s.m.bin(c, Bin::LShr, b, k16); + let w = self.s.m.bin(c, Bin::And, w, k127); + (self.bfe(a, b, w, name == "s_bfe_i32"), None) + } + "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32" + | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => { + let (a, mut b) = (src32(self, 0)?, src32(self, 1)?); + let ones = self.s.m.i32(u32::MAX); + if name.contains("n2") { + b = self.s.m.bin(c, Bin::Xor, b, ones); + } + let op = match &name[2..5] { + "and" | "nan" => Bin::And, + "or_" | "orn" | "nor" => Bin::Or, + _ => Bin::Xor, + }; + let mut r = self.s.m.bin(c, op, a, b); + if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") { + r = self.s.m.bin(c, Bin::Xor, r, ones); + } + (r, None) + } + "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k31 = self.s.m.i32(31); + let b = self.s.m.bin(c, Bin::And, b, k31); + let op = match name { + "s_lshl_b32" => Bin::Shl, + "s_lshr_b32" => Bin::LShr, + _ => Bin::AShr, + }; + (self.s.m.bin(c, op, a, b), None) + } + "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0')); + let t = self.s.m.bin(c, Bin::Shl, a, k); + (self.s.m.bin(c, Bin::Add, t, b), None) + } + "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let p = match name { + "s_min_u32" => pred::IULT, + "s_max_u32" => pred::IUGT, + "s_min_i32" => pred::SLT, + _ => pred::SGT, + }; + let t = self.s.m.cmp(c, p, a, b); + (self.s.m.select(c, t, a, b), None) + } + "s_abs_i32" => { + let a = src32(self, 0)?; + let z = self.s.m.i32(0); + let neg = self.s.m.cmp(c, pred::SLT, a, z); + let n = self.s.m.bin(c, Bin::Sub, z, a); + (self.s.m.select(c, neg, n, a), None) + } + "s_bitset0_b32" | "s_bitset1_b32" => { + // Sets (clears) bit src[4:0] of the destination it reads. + let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?; + let a = src32(self, 0)?; + let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1)); + let a = self.s.m.bin(c, Bin::And, a, k31); + let bit = self.s.m.bin(c, Bin::Shl, one, a); + if name == "s_bitset1_b32" { + (self.s.m.bin(c, Bin::Or, old, bit), None) + } else { + let ones = self.s.m.i32(u32::MAX); + let nb = self.s.m.bin(c, Bin::Xor, bit, ones); + (self.s.m.bin(c, Bin::And, old, nb), None) + } + } + "s_bfm_b32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k31 = self.s.m.i32(31); + let one = self.s.m.i32(1); + let a = self.s.m.bin(c, Bin::And, a, k31); + let b = self.s.m.bin(c, Bin::And, b, k31); + let m = self.s.m.bin(c, Bin::Shl, one, a); + let m = self.s.m.bin(c, Bin::Sub, m, one); + (self.s.m.bin(c, Bin::Shl, m, b), None) + } + _ => return Err(name), + }; + self.set(lo, Val::I32(r)); + if let Some(scc) = scc { + let val = match carry { + Some(k) => Val::Bit(k), + None if matches!( + name, + "s_mov_b32" + | "s_movk_i32" + | "s_cselect_b32" + | "s_brev_b32" + | "s_mul_i32" + | "s_mulk_i32" + ) => + { + 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)) + } + }; + self.vals.insert(scc, val); + } + Ok(()) + } + + /// `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, V) { + let op = if add { Bin::Add } else { Bin::Sub }; + let mut r = self.s.m.bin(c, op, a, b); + // Without a carry in: a + b wraps below a; a - b borrows when a < b. + let mut carry = if add { + self.s.m.cmp(c, pred::IULT, r, a) + } else { + self.s.m.cmp(c, pred::IULT, a, b) + }; + if let Some(cin) = cin { + let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32); + let t = r; + r = self.s.m.bin(c, op, t, one); + // The carry in carries on when the partial result is all ones + // (add) or zero (sub). + let edge = self.s.m.i32(if add { u32::MAX } else { 0 }); + let at_edge = self.s.m.cmp(c, pred::EQ, t, edge); + let more = self.s.m.bin(c, Bin::And, cin, at_edge); + carry = self.s.m.bin(c, Bin::Or, carry, more); + } + (r, carry) + } + + fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> { + let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; + match self.get(v)? { + Val::Bit(x) => Ok(x), + _ => Err("SCC without a value"), + } + } + + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + let Fields::Smem { + data, + offset, + soffset, + .. + } = &inst.fields + else { + unreachable!() + }; + let name = inst.name(); + if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { + return self.code_smem(inst, a); + } + 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 { + return self.descriptor_data(inst, site); + }; + let count = match rest { + "" => 1, + "x2" => 2, + "x4" => 4, + "x8" => 8, + "x16" => 16, + _ => return Err("a scalar buffer load"), + }; + let Some(Operand::Scalar { code, .. }) = *data else { + return Err("a scalar buffer load"); + }; + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked descriptor")?; + let kind = self.used_kind(src); + let c = self.cur; + let (base, extra) = self.built_offset(src)?; + let offset = &((*offset as u32).wrapping_add(base) as i32); + let mut addr = self.s.m.i32(*offset as u32); + if let Some(x) = extra { + addr = self.s.m.bin(c, Bin::Add, addr, x); + } + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(inst, soffset)?; + addr = self.s.m.bin(c, Bin::Add, addr, so); + } + if matches!(src, Source::Built { address, .. } if address.param == CODE) { + // A descriptor built around a table in the code. + for k in 0..count { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let x = self.code_dword(a)?; + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + // A buffer the program picks from the view heap by an index it + // computes (`ResourceHeap`) has no used-resource entry, and the + // 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, + // 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. + let picked = match kind { + None => self.slot_stride(src)?, + Some(_) => None, + }; + if let Some(stride) = picked { + let zero = self.s.m.i32(0); + let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero); + let at = self.begin_guarded(Some(is_buffer)); + let h = self.handle(site, src, false, (11, 0))?; + let mut raw = Vec::new(); + for k in 0..count { + let b = self.cur; + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(b, 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( + b, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + let x = self.s.m.extract(b, r, 0); + let x = self.as_int(x); + raw.push((x, zero)); + } + let raw = self.end_guarded(at, &raw); + let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero); + let at = self.begin_guarded(Some(other)); + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let mut both = Vec::new(); + for (k, &r) in raw.iter().enumerate() { + let b = self.cur; + let off = self.s.m.i32(4 * k as u32); + let a = self.s.m.bin(b, Bin::Add, addr, off); + let x = self.cbuffer_dword(h, a); + both.push((x, r)); + } + let both = self.end_guarded(at, &both); + for (k, x) in both.into_iter().enumerate() { + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { + let h = self.handle(site, src, false, (11, 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 h = self.handle(site, src, false, (13, 0x1_0000))?; + let constant = match addr { + V::Const(_) + if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() => + { + Some(*offset as u32) + } + _ => None, + }; + let mut rows: HashMap<u32, V> = HashMap::new(); + for k in 0..count { + let x = match constant { + Some(base) => { + let byte = base + 4 * k; + let row = match rows.get(&(byte >> 4)) { + Some(&r) => r, + None => { + let ri = self.s.m.i32(byte >> 4); + let r = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, ri], + ); + rows.insert(byte >> 4, r); + r + } + }; + self.s.m.extract(c, row, (byte >> 2) & 3) + } + None => { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + self.cbuffer_dword(h, a) + } + }; + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + + /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords + /// the code also reads as numbers: the console compiler computes sizes + /// from descriptor bits (an image's width, height, depth, levels; a + /// buffer's record count) instead of querying them. Those fields are + /// rebuilt from the host view's dimensions in the GFX10 layout (image + /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits + /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at + /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). + // 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. + 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 { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar memory read as data"); + }; + 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 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. + let x = self.x; + let uses = |of: Site| { + x.res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource) + .filter_map(move |d| { + d.source.leaves().into_iter().find_map(|l| match *l { + Source::Loaded { load, first } if load == of => Some((d.site, first)), + _ => None, + }) + }) + }; + 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 + // its base level, one for each read of the image). Another load of as many dwords + // from the same address reads the same descriptor, so what uses that one tells + // this one's kind. The handle is still made from this load's own operands, which + // hold here. + let address = self.scalar.get(&site).copied(); + let twin = || { + let a = address?; + let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); + x.res + .scalar + .iter() + .filter(|(s, b)| *s != site && *b == a && same(*s)) + .find_map(|(s, _)| use_of(*s)) + }; + let use_at = use_of(site).or_else(twin); + let Some((at, first)) = use_at else { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only + // copies its dwords and compares them, lane against first lane, and every load + // that reaches those lanes reads one address. Each dword stands in as its place + // in the table, so the lanes compare equal as they do on the console. + if self.x.res.lane_copied.contains(&site) + && let Some(a) = self.scalar.get(&site).copied() + { + for k in 0..count { + let x = self.s.m.i32(a.offset / 4 + k); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + // A sampler's descriptor: no program reads its dwords as numbers, so where one + // meets numbers at a join the register is dead on that path (`dead`), as 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), + ) + }); + if sampler { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk + // the memory behind it (a ray-tracing structure): the address + // from the host, the other dwords have no value. + if count <= 4 + && let Some((lo, hi)) = self.view_address(site) + { + for k in 0..count { + let reg = Reg::S(code + k as u8); + match k { + 0 => self.write(inst, reg, lo, None), + 1 => self.write(inst, reg, hi, None), + _ => { + if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + return Ok(()); + } + // No image instruction names this load. A material shader still + // reads the descriptor's size fields and then samples, so the + // fields are rebuilt as a 2D texture's (width, height, levels). + // A dword with no host value stays missing, as before. + let src = Source::Loaded { load: site, first: 0 }; + let h = self.handle(site, &src, false, (2, 0x409))?; + let c = self.cur; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let mip = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let one = self.s.m.i32(1); + let dim = |l: &mut Self, k: u32| { + let x = l.s.m.extract(c, d, k); + l.s.m.bin(c, Bin::Sub, x, one) + }; + let w = dim(self, 0); + let height = dim(self, 1); + let levels = dim(self, 3); + let k30 = self.s.m.i32(30); + let k2 = self.s.m.i32(2); + let k14 = self.s.m.i32(14); + let k16 = self.s.m.i32(16); + let mask = self.s.m.i32(0x3FFF); + let ty = self.s.m.i32(0xFAC | 9 << 28); + let d1 = self.s.m.bin(c, Bin::Shl, w, k30); + let hi = self.s.m.bin(c, Bin::LShr, w, k2); + let hi = self.s.m.bin(c, Bin::And, hi, mask); + let ht = self.s.m.bin(c, Bin::Shl, height, k14); + let d2 = self.s.m.bin(c, Bin::Or, hi, ht); + let last = self.s.m.bin(c, Bin::Shl, levels, k16); + let d3 = self.s.m.bin(c, Bin::Or, ty, last); + let words = [(1u32, d1), (2, d2), (3, d3)]; + for k in 0..count { + match words.iter().find(|w| w.0 == k) { + 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)) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + return Ok(()); + }; + let src = Source::Loaded { load: site, first }; + let used = self.used_kind(&src); + let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; + let un = ui.name(); + let uav = un.contains("store") + || un.contains("atomic") + || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let (props, image) = match &ui.fields { + // A ray-tracing structure in a buffer of the host: read raw. + Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), + Fields::Image { dim, .. } => { + let kind = match dim { + 0 => 1, + 1 => 2, + 2 => 4, + 4 => 6, + 5 => 7, + _ => return Err("an image dimension (cube or MSAA)"), + }; + ((kind | u, 0x409), Some(kind)) + } + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let props = if un.starts_with("buffer_load_format") + || un.starts_with("buffer_store_format") + { + (10 | u, 0x409) + } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { + (12 | u, stride) + } else { + (11 | u, 0) + }; + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + (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 { .. } => { + 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"), + }; + let h = self.handle(site, &src, false, props)?; + let c = self.cur; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let mip = if image.is_some() && !uav { + self.s.m.i32(0) + } else { + self.s.m.undef(i32t) + }; + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k); + let words: Vec<(u32, V)> = match image { + Some(kind) => { + let one = self.s.m.i32(1); + let w = field(self, 0); + let (height, depth) = match kind { + 1 => (one, one), + 2 => (field(self, 1), one), + 6 => (one, field(self, 1)), + _ => (field(self, 1), field(self, 2)), + }; + let levels = if uav { one } else { field(self, 3) }; + let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); + let (w, height, depth, levels) = ( + less(self, w), + less(self, height), + less(self, depth), + less(self, levels), + ); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k30, k2, k14, k16, mask) = ( + k(self, 30), + k(self, 2), + k(self, 14), + k(self, 16), + k(self, 0x3FFF), + ); + let d1 = self.s.m.bin(c, Bin::Shl, w, k30); + let hi = self.s.m.bin(c, Bin::LShr, w, k2); + let hi = self.s.m.bin(c, Bin::And, hi, mask); + let ht = self.s.m.bin(c, Bin::Shl, height, k14); + let d2 = self.s.m.bin(c, Bin::Or, hi, ht); + let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize]; + let base = k(self, 0xFAC | ty << 28); + let last = self.s.m.bin(c, Bin::Shl, levels, k16); + let d3 = self.s.m.bin(c, Bin::Or, base, last); + vec![(1, d1), (2, d2), (3, d3), (4, depth)] + } + None => { + // A raw view counts bytes; the descriptor's record count is in elements. + let n = field(self, 0); + let stride = used.map_or(0, |u| u.stride); + let n = if props.0 & 0xFF == 11 && stride > 1 { + let k = self.s.m.i32(stride); + self.s.m.bin(c, Bin::UDiv, n, k) + } else { + n + }; + let mut words = vec![(2, n)]; + // Its address too, where the code computes with it and the + // host can tell it. + let computed = (0..2u8).any(|k| { + inst.write(Reg::S(code + first + k)) + .is_some_and(|v| self.computed_with(v, 6)) + }); + if first == 0 + && computed + && let Some((lo, hi)) = self.view_address(site) + { + words.extend([(0, lo), (1, hi)]); + } + words + } + }; + for k in 0..count { + let rel = k.wrapping_sub(u32::from(first)); + 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)) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + 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(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(_))); + 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]); + } + addr = self.s.m.bin(c, Bin::Add, addr, d); + } + for k in 0..count { + let off = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, addr, off); + let x = self.code_dword(at)?; + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + + /// The dword at a computed byte address of a constant buffer. + fn cbuffer_dword(&mut self, h: V, a: V) -> V { + let c = self.cur; + let four = self.s.m.i32(4); + let ri = self.s.m.bin(c, Bin::LShr, a, four); + let r = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, ri], + ); + let two = self.s.m.i32(2); + let three = self.s.m.i32(3); + let comp = self.s.m.bin(c, Bin::LShr, a, two); + let comp = self.s.m.bin(c, Bin::And, comp, three); + let mut x = self.s.m.extract(c, r, 0); + for j in 1..4 { + let e = self.s.m.extract(c, r, j); + let jc = self.s.m.i32(j); + let is = self.s.m.cmp(c, pred::EQ, comp, jc); + x = self.s.m.select(c, is, e, x); + } + x + } + + /// `channels` channels of the element at byte `off` of raw buffer `h`, + /// converted from the GFX10 buffer format `format` as the hardware's + /// typed loads do (channels past the format's read 0, 0, 0, 1). + // shortcut: the descriptor's channel swizzle is taken as the identity + // (it is for raw views and the descriptors code builds), elements of 4 + // bytes or more as dword-aligned. Norm formats divide, which the AMD + // driver does 1 ULP off the hardware's correctly rounded conversion for + // some values; correct it with an integer check if a title compares + // converted values exactly. + fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> { + let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; + let c = self.cur; + let total: u32 = bits.iter().sum(); + let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let load = |l: &mut Self, at: V, n: u32| -> Vec<V> { + let mask = l.s.m.i8((1u8 << n) - 1); + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, at, u, mask, align], + ); + (0..n) + .map(|k| { + let x = l.s.m.extract(c, r, k); + l.as_int(x) + }) + .collect() + }; + let words = if total < 32 { + // A byte or half inside the dword that holds it. + let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3)); + let at = self.s.m.bin(c, Bin::And, off, not3); + let w = load(self, at, 1)[0]; + let byte = self.s.m.bin(c, Bin::And, off, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + vec![self.s.m.bin(c, Bin::LShr, w, sh)] + } else { + load(self, off, total / 32) + }; + let float = |l: &mut Self, f: V| l.as_int(f); + let mut out = Vec::new(); + let mut at = 0; + for &w in bits { + let word = words[(at / 32) as usize]; + let field = if w == 32 { + word + } else { + let sh = self.s.m.i32(at % 32); + let t = self.s.m.bin(c, Bin::LShr, word, sh); + let m = self.s.m.i32((1 << w) - 1); + self.s.m.bin(c, Bin::And, t, m) + }; + at += w; + // Sign-extended from the field's top bit. + let signed = |l: &mut Self| { + if w == 32 { + return field; + } + let k = l.s.m.i32(32 - w); + let t = l.s.m.bin(c, Bin::Shl, field, k); + l.s.m.bin(c, Bin::AShr, t, k) + }; + let f32t = self.s.t.f32; + let x = match numeric { + 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 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); + float(self, f) + } + Numeric::Sscaled => { + let s = signed(self); + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + float(self, f) + } + Numeric::Uint => field, + Numeric::Sint => signed(self), + Numeric::Float if w == 32 => field, + Numeric::Float => { + let h = match half_shift(w) { + 0 => field, + k => { + let sh = self.s.m.i32(k); + self.s.m.bin(c, Bin::Shl, field, sh) + } + }; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + float(self, f) + } + }; + out.push(x); + } + let one = match numeric { + Numeric::Uint | Numeric::Sint => 1, + _ => 1.0f32.to_bits(), + }; + for k in out.len() as u32..channels { + out.push(self.s.m.i32(if k == 3 { one } else { 0 })); + } + out.truncate(channels as usize); + Ok(out) + } + + /// The byte offset a buffer descriptor built around a root descriptor adds + /// (constant and computed parts); none for other descriptors. + fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> { + match src { + Source::Built { address, .. } => { + let mut x = match address.dynamic { + Some(v) => Some(self.i32_of(v)?), + None => None, + }; + if let Some(bias) = self.root_bias(address.param) { + x = Some(match x { + Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias), + None => bias, + }); + } + Ok((address.offset, x)) + } + _ => Ok((0, None)), + } + } + + /// 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 + /// with a spilled user-data table (the others keep the views they + /// have). + fn root_bias(&mut self, param: usize) -> Option<V> { + use super::shader::USER_VIEW_BIAS; + let rp = *self.x.native.layout.get(param)?; + if rp.root != RootType::Descriptor { + return None; + } + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + let biased = match kind { + Some(ResourceType::Uav) => true, + Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native), + _ => false, + }; + biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) + } + + /// The used-resource entry a descriptor loaded from a table falls in. + fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { + if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } = + src + { + return self.used_kind(args.first()?); + } + if let Source::LanePhi { args, .. } = src { + return args.iter().flatten().find_map(|a| self.used_kind(a)); + } + if let Source::Built { address, .. } = src { + let rp = self.x.native.layout.get(address.param)?; + return self + .x + .native + .used + .iter() + .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data); + } + let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else { + return None; + }; + let a = self.scalar.get(load)?; + let rp = self.x.native.layout.get(a.param)?; + if rp.root != RootType::Table { + return None; + } + let dword = (a.offset / 4) + u32::from(*first); + self.x + .native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords) + } + + /// A handle for the descriptor `src` read at `site`. + fn handle( + &mut self, + site: Site, + src: &Source, + sampler: bool, + props: (u32, u32), + ) -> Result<V, Why> { + match src { + Source::Loaded { load, first } => { + let key = (self.cur, *load, *first, sampler, props); + if let Some(&h) = self.handles.get(&key) { + return Ok(h); + } + 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); + let h = self + .s + .heap_handle(self.cur, index, sampler, per_lane, props); + self.handles.insert(key, h); + Ok(h) + } + Source::Constant(words) if sampler => { + let words: [u32; 4] = words + .get(..4) + .and_then(|w| w.try_into().ok()) + .ok_or("a sampler constant")?; + let n = match self.samplers.iter().position(|w| *w == words) { + Some(n) => n, + None => { + self.samplers.push(words); + self.samplers.len() - 1 + } + }; + 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, .. } => { + let rp = *self + .x + .native + .layout + .get(address.param) + .ok_or("a descriptor built around a table in the code")?; + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + match (rp.root, kind, props.0) { + (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => { + Ok(self.s.root_cbv_handle(rp.slot)) + } + (RootType::Descriptor, Some(ResourceType::Srv), 11) => { + Ok(self.s.root_srv_handle(rp.slot)) + } + // A root UAV: a raw buffer whether the access reads + // (11) or writes (11 with the UAV bit). Indexed + // accesses reach here as raw ones at index times the + // entry's stride (`buffer`). + (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => { + Ok(self.s.root_uav_handle(rp.slot)) + } + (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => { + Err("a write through a root SRV") + } + _ => Err("a typed root view"), + } + } + Source::Phi { block, args } => { + let _ = site; + let phi = self.descriptor_phi(*block, args, sampler, 8)?; + Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) + } + Source::Select { scc, args } => { + // The heap index of each choice, picked by SCC (uniform). + let [ + Source::Loaded { load: a, first: fa }, + Source::Loaded { load: b, first: fb }, + ] = args[..] + else { + return Err("a descriptor chosen by a condition"); + }; + let cond = match self.get(*scc)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + }; + let set = self.heap_index(a, fa, sampler)?; + let clear = self.heap_index(b, fb, sampler)?; + let index = self.s.m.select(self.cur, cond, set, clear); + Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + } + Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { + // A descriptor each lane has its own of (a waterfall loop + // reads it from the first active lane): each lane's heap + // index, non-uniform. + let index = self.lane_heap_index(src, sampler)?; + Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) + } + } + } + + /// 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 + /// phi of an earlier join, which dominates it) gives that join's phi, + /// at most `depth` joins deep. + fn descriptor_phi( + &mut self, + block: usize, + args: &[Source], + sampler: bool, + depth: u32, + ) -> Result<V, Why> { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + let mut incoming = Vec::new(); + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or(WHY)?; + let at = self.edges.get(&(q, block)).copied().unwrap_or(tail); + let index = match arg { + Source::Loaded { load, first } => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.heap_index(*load, *first, sampler); + self.cur = here; + index? + } + 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)); + } + let join = self.block[block].ok_or(WHY)?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + + /// The bytes per element of the buffer view `src` names, if the program + /// picks it from the view heap at an index it computes (root type + /// `ResourceHeap`): read from the host's table by heap slot in the + /// current block. + fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> { + let Source::Loaded { load, first } = src else { + return Ok(None); + }; + let heap = self + .scalar + .get(load) + .and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap); + if !heap { + return Ok(None); + } + let key = (self.cur, *load, *first); + if let Some(&v) = self.strides.get(&key) { + return Ok(Some(v)); + } + let c = self.cur; + let slot = self.heap_index(*load, *first, false)?; + // Inside the table whatever the index (lanes that do not run + // 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]); + 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); + let iu = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ); + let f = self.s.m.extract(c, r, 0); + let v = self.as_int(f); + self.strides.insert(key, v); + Ok(Some(v)) + } + + /// The heap index of a descriptor that may differ between lanes, + /// computed in the current block (or, chosen by control flow, at the + /// join). + fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> { + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler), + Source::Lanes { mask, args } | Source::Select { scc: mask, args } => { + let [a, b] = &args[..] else { + return Err("a descriptor chosen per lane"); + }; + let cond = if matches!(src, Source::Lanes { .. }) { + let &m = self + .x + .st + .masks + .get(mask) + .ok_or("a descriptor chosen per lane by an untracked mask")?; + self.boolean(m, self.cur)? + } else { + match self.get(*mask)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + } + }; + let set = self.lane_heap_index(a, sampler)?; + let clear = self.lane_heap_index(b, sampler)?; + Ok(self.s.m.select(self.cur, cond, set, clear)) + } + Source::LanePhi { block, args } => { + // Each predecessor computes its heap index at its end (what + // it reads is there: the dwords are, on that edge); the join + // picks the one of the edge the lane came by. An edge no + // lane reading it takes gives index 0. + let join = + self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?; + 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 per-lane descriptor joined from a later block")?; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let index = match arg { + Some(arg) => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.lane_heap_index(arg, sampler); + self.cur = here; + index? + } + None => self.s.m.i32(0), + }; + incoming.push((index, at)); + } + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"), + } + } + + /// The heap index of the descriptor at dword `first` of what the global + /// load at `load` reads, in each lane: its address (base plus offsets) + /// over the descriptor size. + fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> { + const WHY: Why = "a per-lane descriptor load"; + let a = *self + .scalar + .get(&load) + .ok_or("an untracked descriptor load")?; + match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + _ => return Err("a descriptor outside the heaps"), + } + let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; + let Fields::Flat { + addr: Some(Operand::Vector { reg, .. }), + saddr, + offset, + .. + } = li.fields + else { + return Err(WHY); + }; + let c = self.cur; + // The low dword of the address: SGPR base plus VGPR offset, or the + // VGPR pair's low half (heap addresses fit in 32 bits). + let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?; + if let Some(Operand::Scalar { code, .. }) = saddr + && code != NULL + { + let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?; + at = self.s.m.bin(c, Bin::Add, base, at); + } + let k = self + .s + .m + .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first))); + at = self.s.m.bin(c, Bin::Add, at, k); + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + Ok(self.s.m.bin(c, Bin::LShr, at, shift)) + } + + /// The heap index of the descriptor at dword `first` of what the scalar + /// load at `load` reads, computed in the current block. + fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> { + let a = *self + .scalar + .get(&load) + .ok_or("an untracked descriptor load")?; + match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + _ => return Err("a descriptor outside the heaps"), + } + let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; + let Fields::Smem { + base, + offset, + soffset, + .. + } = &li.fields + else { + return Err("a descriptor load"); + }; + let Operand::Scalar { code, .. } = *base else { + return Err("a descriptor load"); + }; + let c = self.cur; + let base = li.read(Reg::S(code)).ok_or("a descriptor load")?; + let mut addr = self.i32_of(base)?; + let k = self + .s + .m + .i32((*offset as u32).wrapping_add(4 * u32::from(first))); + addr = self.s.m.bin(c, Bin::Add, addr, k); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(li, soffset)?; + addr = self.s.m.bin(c, Bin::Add, addr, so); + } + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + Ok(self.s.m.bin(c, Bin::LShr, addr, shift)) + } + + fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + if self.x.res.waterfall.compares.contains(&(b, i)) { + // The first lane's dwords of a waterfall loop are each lane's + // own (see `resource::Waterfall`). + self.lane(inst, Some(true)); + return Ok(()); + } + if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) { + let r = if v.dpp.is_some() { + Err("a compare with DPP") + } else { + self.compare(inst, rest) + }; + if let Err(why) = r { + for &(_, w) in &inst.writes { + self.lane_fail.insert(w, why); + } + } + return r; + } + let mut guard = self.guard(b, i)?; + if let Some(d) = v.dpp { + let (x, enable) = self.dpp(inst, d)?; + guard = match (guard, enable) { + (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)), + (g, e) => g.or(e), + }; + self.src0 = Some(x); + } + let r = self.valu_op(inst, guard); + self.src0 = None; + r + } + + /// DPP: src0 as read from another lane, and which lanes write their + /// result (none: all). + fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let Some(&Operand::Vector { reg, .. }) = v.src.first() else { + return Err("a DPP operand"); + }; + let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?; + // Quad permutations and DPP8 stay in groups the pixel layout shares. + let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. }); + let mesh_quad = self.s.mesh.is_some() && quad; + if !mesh_quad { + self.cross_lane(quad)?; + } + let c = self.cur; + let lane = self.lane_index(); + let k = |l: &mut Self, n: u32| l.s.m.i32(n); + let (sixteen_mask, low) = (k(self, !15), k(self, 15)); + let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask); + let pos = self.s.m.bin(c, Bin::And, lane, low); + // Source lane, and whether it lies in the row. + let (src, inside, masks, zero) = match dpp { + Dpp::Lanes { sel, .. } => { + let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3)); + let p = self.s.m.bin(c, Bin::And, lane, seven); + let sh = self.s.m.bin(c, Bin::Mul, p, three); + let sel = k(self, sel); + let pick = self.s.m.bin(c, Bin::LShr, sel, sh); + let pick = self.s.m.bin(c, Bin::And, pick, seven); + let base = self.s.m.bin(c, Bin::And, lane, not7); + (self.s.m.bin(c, Bin::Or, base, pick), None, None, false) + } + Dpp::Row { + ctrl, + row_mask, + bank_mask, + bound_ctrl, + .. + } => { + let n = u32::from(ctrl & 15); + let (src, inside) = match ctrl { + 0..=0xFF => { + let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3)); + let p = self.s.m.bin(c, Bin::And, lane, three); + let sh = self.s.m.bin(c, Bin::Shl, p, one); + let perm = k(self, u32::from(ctrl)); + let pick = self.s.m.bin(c, Bin::LShr, perm, sh); + let pick = self.s.m.bin(c, Bin::And, pick, three); + let base = self.s.m.bin(c, Bin::And, lane, not3); + (self.s.m.bin(c, Bin::Or, base, pick), None) + } + 0x101..=0x10F | 0x111..=0x11F => { + let nn = k(self, n); + let left = ctrl < 0x110; + let (op, p) = if left { + (Bin::Add, pred::IULT) + } else { + (Bin::Sub, pred::IUGE) + }; + let s = self.s.m.bin(c, op, lane, nn); + // Left: pos + n < 16; right: pos >= n. + let bound = if left { k(self, 16 - n) } else { nn }; + (s, Some(self.s.m.cmp(c, p, pos, bound))) + } + 0x121..=0x12F => { + let nn = k(self, n); + let t = self.s.m.bin(c, Bin::Sub, pos, nn); + let t = self.s.m.bin(c, Bin::And, t, low); + (self.s.m.bin(c, Bin::Or, row, t), None) + } + 0x140 | 0x141 => { + let m = k(self, if ctrl == 0x140 { 15 } else { 7 }); + let t = self.s.m.bin(c, Bin::Xor, lane, m); + (t, None) + } + 0x150..=0x15F => { + let nn = k(self, n); + (self.s.m.bin(c, Bin::Or, row, nn), None) + } + 0x160..=0x16F => { + let nn = k(self, n); + (self.s.m.bin(c, Bin::Xor, lane, nn), None) + } + _ => return Err("a DPP lane pattern"), + }; + let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask)); + (src, inside, masks, bound_ctrl) + } + }; + let mut r = if mesh_quad { + self.quad_pick(x, src) + } else { + self.read_lane(x, src) + }; + let mut enable = None; + if let Some(inside) = inside { + if zero { + let z = k(self, 0); + r = self.s.m.select(c, inside, r, z); + } else { + enable = Some(inside); + } + } + if let Some((rows, banks)) = masks { + // Row (16 lanes) and bank (4 lanes of a row) write masks. + let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3)); + let ri = self.s.m.bin(c, Bin::LShr, lane, four); + let ri = self.s.m.bin(c, Bin::And, ri, three); + let bi = self.s.m.bin(c, Bin::LShr, lane, two); + let bi = self.s.m.bin(c, Bin::And, bi, three); + let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks))); + let rb = self.s.m.bin(c, Bin::LShr, rm, ri); + let bb = self.s.m.bin(c, Bin::LShr, bm, bi); + let both = self.s.m.bin(c, Bin::And, rb, bb); + let (one, z) = (k(self, 1), k(self, 0)); + let both = self.s.m.bin(c, Bin::And, both, one); + let on = self.s.m.cmp(c, pred::NE, both, z); + enable = Some(match enable { + Some(e) => self.s.m.bin(c, Bin::And, e, on), + None => on, + }); + } + Ok((r, enable)) + } + + fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + let c = self.cur; + let f = |l: &mut Self, k| l.fsrc(inst, k); + let s = |l: &mut Self, k| l.src(inst, k); + let float = |l: &mut Self, r: V| l.write_f(inst, r, guard); + let int = |l: &mut Self, r: V| l.write_i(inst, r, guard); + if let Some(r) = self.valu16(inst, name, guard) { + return r; + } + if let Some(op) = name.strip_prefix("v_pk_") { + return self.packed16(inst, op, guard); + } + match name { + "v_mad_u64_u32" => { + // a * b + c, c and the result 64 bits wide; the carry out + // of the sum is this lane's bit of the mask it names. + let (a, b) = (s(self, 0)?, s(self, 1)?); + let x = self.src64(inst, 2)?; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let a = self.s.m.cast(c, Cast::ZExt, a, i64t); + let b = self.s.m.cast(c, Cast::ZExt, b, i64t); + let product = self.s.m.bin(c, Bin::Mul, a, b); + let r = self.s.m.bin(c, Bin::Add, product, x); + let carry = self.s.m.cmp(c, pred::IULT, r, x); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => { + let n = s(self, 0)?; + let x = self.src64(inst, 1)?; + let i64t = self.s.m.int(64); + let k63 = self.s.m.i32(63); + let n = self.s.m.bin(c, Bin::And, n, k63); + let n = self.s.m.cast(c, Cast::ZExt, n, i64t); + let op = match name { + "v_lshlrev_b64" => Bin::Shl, + "v_lshrrev_b64" => Bin::LShr, + _ => Bin::AShr, + }; + let r = self.s.m.bin(c, op, x, n); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + Ok(()) + } + "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => { + // Cube-map face coordinates (AMD's ISA): the major axis is z + // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|, + // else x. + let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z)); + let zx = self.s.m.cmp(c, pred::OGE, az, ax); + let zy = self.s.m.cmp(c, pred::OGE, az, ay); + let zmaj = self.s.m.bin(c, Bin::And, zx, zy); + let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax); + let zero = self.s.m.f32(0); + let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero); + let minus = |l: &mut Self, v: V| { + let z = l.s.m.f32(0x8000_0000); + l.s.m.bin(c, Bin::Sub, z, v) + }; + let pick = |l: &mut Self, zv: V, yv: V, xv: V| { + let t = l.s.m.select(c, ymaj, yv, xv); + l.s.m.select(c, zmaj, zv, t) + }; + let r = match name { + "v_cubeid_f32" => { + let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); + let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x)); + let (f5, f4, f3, f2, f1, f0) = ( + k(self, 5.0), + k(self, 4.0), + k(self, 3.0), + k(self, 2.0), + k(self, 1.0), + k(self, 0.0), + ); + let zf = self.s.m.select(c, nz, f5, f4); + let yf = self.s.m.select(c, ny, f3, f2); + let xf = self.s.m.select(c, nx, f1, f0); + pick(self, zf, yf, xf) + } + "v_cubesc_f32" => { + let (nz, nx) = (neg(self, z), neg(self, x)); + let (mx, mz) = (minus(self, x), minus(self, z)); + let zf = self.s.m.select(c, nz, mx, x); + let xf = self.s.m.select(c, nx, z, mz); + pick(self, zf, x, xf) + } + "v_cubetc_f32" => { + let ny = neg(self, y); + let (my, mz) = (minus(self, y), minus(self, z)); + let yf = self.s.m.select(c, ny, mz, z); + pick(self, my, yf, my) + } + _ => { + let t = pick(self, z, y, x); + let two = self.s.m.f32(2.0f32.to_bits()); + self.s.m.bin(c, Bin::Mul, t, two) + } + }; + float(self, r) + } + "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => { + // M0 indexes the source (movrels), the destination (movreld) + // or both, from the encoded register up to the program's + // VGPR count (the registers the instruction reads or writes). + let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?; + let ( + Some(&Operand::Vector { reg: sreg, .. }), + Some(Operand::Vector { reg: dreg, .. }), + ) = (v.src.first(), v.dst) + else { + return Err("an M0-relative move"); + }; + let indexed_src = name != "v_movreld_b32"; + let value = if indexed_src { + let mut r = self.s.m.i32(0); + for k in 0..=255u8.saturating_sub(sreg) { + let Some(x) = inst.read(Reg::V(sreg + k)) else { + break; + }; + let x = self.i32_of(x)?; + let kk = self.s.m.i32(u32::from(k)); + let is = self.s.m.cmp(c, pred::EQ, m0, kk); + r = self.s.m.select(c, is, x, r); + } + r + } else { + s(self, 0)? + }; + if name == "v_movrels_b32" { + return int(self, value); + } + for k in 0..=255u8.saturating_sub(dreg) { + let Some(_) = inst.write(Reg::V(dreg + k)) else { + break; + }; + let old = match inst.read(Reg::V(dreg + k)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + let kk = self.s.m.i32(u32::from(k)); + let is = self.s.m.cmp(c, pred::EQ, m0, kk); + let x = self.s.m.select(c, is, value, old); + self.write_placed(inst, Reg::V(dreg + k), x, guard); + } + Ok(()) + } + "v_swap_b32" => { + let ( + Some(&Operand::Vector { reg: sreg, .. }), + Some(Operand::Vector { reg: dreg, .. }), + ) = (v.src.first(), v.dst) + else { + return Err("v_swap_b32"); + }; + let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?; + let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?; + self.write_placed(inst, Reg::V(dreg), b, guard); + if dreg != sreg { + self.write_placed(inst, Reg::V(sreg), a, guard); + } + Ok(()) + } + "v_ffbh_u32" | "v_ffbh_i32" => { + // Counted from the top bit, -1 when none (DXIL's too). + let a = s(self, 0)?; + let op = if name == "v_ffbh_u32" { 33 } else { 34 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + int(self, r) + } + "v_mov_b32" => { + if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 { + let a = f(self, 0)?; + return float(self, a); + } + let a = s(self, 0)?; + int(self, a) + } + "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32" + | "v_max_f32" | "v_min_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let r = match name { + "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb), + "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb), + "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a), + "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb), + "v_mul_legacy_f32" => self.legacy_mul(a, bb), + "v_max_f32" => self.max_min(true, a, bb), + _ => self.max_min(false, a, bb), + }; + float(self, r) + } + "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => { + // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse. + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let r = self.fmad(a, bb, cc); + float(self, r) + } + "v_div_scale_f32" => { + // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator. + let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den)); + let (k23, k255, kabs) = ( + self.s.m.i32(23), + self.s.m.i32(0xFF), + self.s.m.i32(0x7FFF_FFFF), + ); + let (zero, k23_exp, k232_exp, k96) = ( + self.s.m.i32(0), + self.s.m.i32(23), + self.s.m.i32(232), + self.s.m.i32(96), + ); + let exp_of = |l: &mut Self, x: V| { + let s = l.s.m.bin(c, Bin::LShr, x, k23); + l.s.m.bin(c, Bin::And, s, k255) + }; + let (e1, e2) = (exp_of(self, ni), exp_of(self, di)); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let any_zero = self.s.m.bin(c, Bin::Or, z1, z2); + let special = { + let s1 = self.s.m.cmp(c, pred::EQ, e1, k255); + let s2 = self.s.m.cmp(c, pred::EQ, e2, k255); + let a12 = self.s.m.bin(c, Bin::Or, s1, s2); + self.s.m.bin(c, Bin::Or, a12, any_zero) + }; + let is_den = self.s.m.cmp(c, pred::EQ, ai, di); + let diff = self.s.m.bin(c, Bin::Sub, e2, e1); + let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp); + let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp); + let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp); + let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp); + let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96); + let not_den_huge = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, den_huge, t) + }; + let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge); + let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap); + let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny); + let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge); + let not_special = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, special, t) + }; + let up = self.s.m.bin(c, Bin::And, up_raw, not_special); + let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special); + let uncancelled = { + let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny); + let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge); + self.s.m.bin(c, Bin::Or, x_tiny, x_huge) + }; + let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw); + let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special); + let k_up = self.s.m.f32(0x5F80_0000); + let k_dn = self.s.m.f32(0x1F80_0000); + let a_up = self.s.m.bin(c, Bin::Mul, a, k_up); + let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn); + let r = self.s.m.select(c, dn, a_dn, a); + let r = self.s.m.select(c, up, a_up, r); + let qnan = self.s.m.f32(0x7FC0_0000); + let r = self.s.m.select(c, any_zero, qnan, r); + float(self, r)?; + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, flag); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_div_fmas_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let m = inst + .read(Reg::S(crate::ir::VCC)) + .and_then(|v| self.x.st.masks.get(&v).copied()) + .ok_or("v_div_fmas_f32 without VCC")?; + let vcc = self.boolean(m, c)?; + let tmp = self.fmad(a, bb, cc); + let ci = self.as_int(cc); + let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128)); + let sh = self.s.m.bin(c, Bin::LShr, ci, k23); + let exp = self.s.m.bin(c, Bin::And, sh, k255); + let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128); + let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000)); + let scale = self.s.m.select(c, exp_ge, k_up, k_dn); + let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale); + let r = self.s.m.select(c, vcc, scaled, tmp); + float(self, r) + } + "v_div_fixup_f32" => { + let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num)); + let (ksign, kabs, kinf) = ( + self.s.m.i32(0x8000_0000), + self.s.m.i32(0x7FFF_FFFF), + self.s.m.i32(0x7F80_0000), + ); + let (kqnan_bit, kneg_qnan, zero) = ( + self.s.m.i32(0x0040_0000), + self.s.m.i32(0xFFC0_0000), + self.s.m.i32(0), + ); + let sign = { + let x = self.s.m.bin(c, Bin::Xor, ni, di); + self.s.m.bin(c, Bin::And, x, ksign) + }; + let q_abs = self.s.m.bin(c, Bin::And, qi, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf); + let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf); + let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf); + let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf); + let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf); + let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf); + let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero); + let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero); + let make_inf = { + let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero); + self.s.m.bin(c, Bin::Or, t, q_nan) + }; + let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero); + let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs); + let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf); + let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit); + let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit); + 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); + 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) + } + "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("an accumulator"); + }; + let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?; + 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" => { + let m = self.s.m.bin(c, Bin::Mul, a, bb); + self.s.m.bin(c, Bin::Add, m, acc) + } + _ => { + let m = self.legacy_mul(a, bb); + self.s.m.bin(c, Bin::Add, m, acc) + } + }; + float(self, r) + } + "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let m = if name == "v_mad_legacy_f32" { + self.legacy_mul(a, bb) + } else { + self.s.m.bin(c, Bin::Mul, a, bb) + }; + let r = self.s.m.bin(c, Bin::Add, m, cc); + float(self, r) + } + "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let r = match name { + "v_max3_f32" => { + let t = self.max_min(true, a, bb); + self.max_min(true, t, cc) + } + "v_min3_f32" => { + let t = self.max_min(false, a, bb); + self.max_min(false, t, cc) + } + _ => self.med3(a, bb, cc), + }; + float(self, r) + } + "v_rcp_f32" | "v_rcp_iflag_f32" => { + // shortcut: the hardware reciprocal is approximate (1 ULP); this divides. + let a = f(self, 0)?; + let one = self.s.m.f32(1.0f32.to_bits()); + let r = self.s.m.bin(c, Bin::SDiv, one, a); + float(self, r) + } + "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32" + | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32" + | "v_cos_f32" => { + let a = f(self, 0)?; + let op = match name { + "v_rsq_f32" => 25, + "v_sqrt_f32" => 24, + "v_log_f32" => 23, + "v_exp_f32" => 21, + "v_fract_f32" => 22, + "v_trunc_f32" => 29, + "v_floor_f32" => 27, + "v_ceil_f32" => 28, + "v_rndne_f32" => 26, + "v_sin_f32" => 13, + _ => 12, + }; + let r = match op { + 12 | 13 => self.trig_turns(a, op == 12), + 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)), + _ => self.unary(op, a), + }; + float(self, r) + } + "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" { + let h = self.s.m.f32(0.5f32.to_bits()); + a = self.s.m.bin(c, Bin::Add, a, h); + } + if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" { + a = self.unary(27, a); + } + // D3D's conversions saturate and give 0 for NaN, as the + // hardware does (checked on the RX 6700 XT and WARP). + let op = if name == "v_cvt_u32_f32" { + Cast::FpToUi + } else { + Cast::FpToSi + }; + let r = self.s.m.cast(c, op, a, self.s.t.i32); + int(self, r) + } + "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" + | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { + let mut a = s(self, 0)?; + if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") { + let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0')); + let ff = self.s.m.i32(0xff); + a = self.s.m.bin(c, Bin::LShr, a, sh); + a = self.s.m.bin(c, Bin::And, a, ff); + } + let op = if name == "v_cvt_f32_i32" { + Cast::SiToFp + } else { + Cast::UiToFp + }; + let r = self.s.m.cast(c, op, a, self.s.t.f32); + float(self, r) + } + "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { + // Each source is f32, or with op_sel_hi the low (op_sel: high) + // f16 half; neg_hi is the absolute value here. + let mut xs = Vec::new(); + for i in 0..3 { + let op = v.src.get(i).ok_or("a missing operand")?; + let mut x = if v.opsel_hi >> i & 1 != 0 { + let x = self.f16_operand(inst, op)?; + let h = if v.opsel >> i & 1 != 0 { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + self.s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]) + } else { + let x = self.operand(inst, op)?; + self.as_float(x) + }; + if v.neg_hi >> i & 1 != 0 { + x = self.unary(6, x); + } + if v.neg >> i & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + x = self.s.m.bin(c, Bin::Sub, z, x); + } + xs.push(x); + } + let mut r = self.fmad(xs[0], xs[1], xs[2]); + if name == "v_fma_mix_f32" { + return float(self, r); + } + if v.clamp { + r = self.unary(7, r); + } + // The f16 result goes to one half; the other half stays. + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a mixed-precision result"); + }; + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]); + let (keep, h) = if name == "v_fma_mixhi_f16" { + let k16 = self.s.m.i32(16); + (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16)) + } else { + (0xFFFF_0000, h) + }; + let keep = self.s.m.i32(keep); + let old = self.s.m.bin(c, Bin::And, old, keep); + let x = self.s.m.bin(c, Bin::Or, old, h); + self.write(inst, Reg::V(reg), x, guard); + Ok(()) + } + "v_cvt_pkrtz_f16_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let lo = self.f16_toward_zero(a); + let hi = self.f16_toward_zero(bb); + let sh = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, sh); + let r = self.s.m.bin(c, Bin::Or, lo, hi); + int(self, r) + } + "v_cvt_f16_f32" if v.opsel == 0 => { + // Rounded to nearest even (the MODE default) into the low half. + let a = f(self, 0)?; + let r = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 16-bit result outside a VGPR"); + }; + let r = self.low_half(inst, reg, r); + int(self, r) + } + "v_pack_b32_f16" => { + // Two f16 sources (op_sel: their high halves; abs and neg on + // the sign bit) into the low and high half. + let mut halves = Vec::new(); + for k in 0..2 { + let op = v.src.get(k).ok_or("a missing operand")?; + let mut x = self.f16_operand(inst, op)?; + if v.opsel >> k & 1 != 0 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF }; + let mask = self.s.m.i32(mask); + x = self.s.m.bin(c, Bin::And, x, mask); + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000); + x = self.s.m.bin(c, Bin::Xor, x, sign); + } + halves.push(x); + } + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); + let r = self.s.m.bin(c, Bin::Or, halves[0], hi); + int(self, r) + } + "v_cvt_f32_f64" => { + let bits = self.src64(inst, 0)?; + let (lo, hi) = self.split64(bits); + let r = self.f64_to_f32(lo, hi); + float(self, r) + } + "v_cvt_f32_f16" if v.opsel == 0 => { + let a = s(self, 0)?; + let r = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]); + float(self, r) + } + "v_cndmask_b32" => { + 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); + return float(self, r); + } + let (a, bb) = (s(self, 0)?, s(self, 1)?); + let r = self.s.m.select(c, cond, bb, a); + int(self, r) + } + "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32" + | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => { + // The carry (borrow) out is a lane mask: this lane's bit. + let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?); + if name.contains("subrev") { + std::mem::swap(&mut a, &mut bb); + } + let cin = if name.ends_with("_ci_u32") { + 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 + }; + let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin); + int(self, r)?; + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_readlane_b32" => { + let (a, lane) = (s(self, 0)?, s(self, 1)?); + // A computed lane in a pixel or vertex program is a host lane + // (from a mask or `v_mbcnt`); a constant one is the console's. + if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) { + self.s.flags |= flags::WAVE_OPS; + } else { + self.cross_lane(false)?; + } + if let Some(slot) = self.exchange.as_ref().map(|e| e.0) { + if self.local && self.local_any { + // this host wave's lane of that number (lanes 32..63 are 0..31 here) + let k31 = self.s.m.i32(31); + let here = self.s.m.bin(self.cur, Bin::And, lane, k31); + let r = self.read_lane(a, here); + return int(self, r); + } + if self.local { + return Err("a lane read in a half-wave"); + } + if self.exchange.as_ref().is_some_and(|e| e.1) { + // a group of 32 or fewer: the lane is in this host wave + let r = self.read_lane(a, lane); + return int(self, r); + } + // the lane that holds it may be in the other host wave: it gives it through LDS + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a lane read where not every lane runs"); + } + let cl = self.console_lane(); + let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane); + let k = self.exchange_pair(slot); + let at = self.begin_guarded(Some(is)); + let lds = self.s.lds(); + let ptr = self.s.m.element(self.cur, lds, k); + self.s.m.store(self.cur, ptr, a); + self.end_guarded(at, &[]); + let c2 = self.cur; + self.group_sync(c2); + let ptr = self.s.m.element(c2, lds, k); + let r = self.s.m.load(c2, ptr); + self.group_sync(c2); + return int(self, r); + } + let r = self.read_lane(a, lane); + int(self, r) + } + "v_writelane_b32" => { + // The lane given takes the scalar; the others keep their value. + let (a, lane) = (s(self, 0)?, s(self, 1)?); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a lane write"); + }; + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + self.cross_lane(false)?; + if self.local && !self.local_any { + return Err("a lane write in a half-wave"); + } + let me = self.console_lane(); + let is = self.s.m.cmp(c, pred::EQ, me, lane); + let r = self.s.m.select(c, is, a, old); + int(self, r) + } + "v_readfirstlane_b32" + if inst + .writes + .first() + .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) => + { + // A waterfall loop's read of a descriptor dword: the lane's own. + let a = s(self, 0)?; + int(self, a) + } + "v_readfirstlane_b32" + if matches!(v.src.first(), Some(&Operand::Vector { reg, .. }) + if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) => + { + // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of + // the host wave holds the same, so the first lane's is the lane's own. + let a = s(self, 0)?; + int(self, a) + } + "v_readfirstlane_b32" => { + let a = s(self, 0)?; + let (mine, any) = self.first_lane(a, guard); + // 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)) + } + _ => 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) { + need(self.cur_ir); + return Err("a first-lane read where not every lane runs"); + } + let c = self.cur; + 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) + } + _ => { + let r = self.integer(inst, name)?; + int(self, r) + } + } + } + + /// `v_cvt_f32_f64`: round an IEEE binary64 bit pattern to binary32. + /// Subnormals flush to zero. Round to nearest, ties to even. + fn f64_to_f32(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let sign_shift = self.s.m.i32(31); + let exp_shift = self.s.m.i32(20); + let exp_mask = self.s.m.i32(0x7ff); + let man_mask = self.s.m.i32(0x000f_ffff); + let sign = self.s.m.bin(c, Bin::LShr, hi, sign_shift); + let exp = self.s.m.bin(c, Bin::LShr, hi, exp_shift); + let exp = self.s.m.bin(c, Bin::And, exp, exp_mask); + let man_hi = self.s.m.bin(c, Bin::And, hi, man_mask); + let three = self.s.m.i32(3); + let top = self.s.m.bin(c, Bin::Shl, man_hi, three); + let twenty_nine = self.s.m.i32(29); + let low3 = self.s.m.bin(c, Bin::LShr, lo, twenty_nine); + let mut mant = self.s.m.bin(c, Bin::Or, top, low3); + let twenty_eight = self.s.m.i32(28); + let round_shift = self.s.m.bin(c, Bin::LShr, lo, twenty_eight); + let one = self.s.m.i32(1); + let zero = self.s.m.i32(0); + let round = self.s.m.bin(c, Bin::And, round_shift, one); + let sticky_mask = self.s.m.i32(0x0fff_ffff); + let sticky = self.s.m.bin(c, Bin::And, lo, sticky_mask); + let mant_odd = self.s.m.bin(c, Bin::And, mant, one); + let tie = self.s.m.bin(c, Bin::Or, sticky, mant_odd); + let tie = self.s.m.cmp(c, pred::NE, tie, zero); + let do_round = self.s.m.cmp(c, pred::NE, round, zero); + let do_round = self.s.m.bin(c, Bin::And, do_round, tie); + let bumped = self.s.m.bin(c, Bin::Add, mant, one); + mant = self.s.m.select(c, do_round, bumped, mant); + let mant_lim = self.s.m.i32(1 << 23); + let carry = self.s.m.cmp(c, pred::IUGE, mant, mant_lim); + mant = self.s.m.select(c, carry, zero, mant); + let exp_bump = self.s.m.select(c, carry, one, zero); + let bias64 = self.s.m.i32(1023); + let bias32 = self.s.m.i32(127); + let unbiased = self.s.m.bin(c, Bin::Sub, exp, bias64); + let mut fexp = self.s.m.bin(c, Bin::Add, unbiased, bias32); + fexp = self.s.m.bin(c, Bin::Add, fexp, exp_bump); + let inf_exp = self.s.m.i32(0xff); + let exp_nan = self.s.m.i32(0x7ff); + let naninf = self.s.m.cmp(c, pred::EQ, exp, exp_nan); + let zero_exp = self.s.m.cmp(c, pred::EQ, exp, zero); + let overflow = self.s.m.cmp(c, pred::IUGE, fexp, inf_exp); + let underflow = self.s.m.cmp(c, pred::SLE, fexp, zero); + let man_or = self.s.m.bin(c, Bin::Or, man_hi, lo); + let is_nan = self.s.m.cmp(c, pred::NE, man_or, zero); + let nan_bit = self.s.m.select(c, is_nan, one, zero); + let to_inf = self.s.m.bin(c, Bin::Or, naninf, overflow); + let special_exp = self.s.m.select(c, to_inf, inf_exp, zero); + let special_man = self.s.m.select(c, naninf, nan_bit, zero); + let mut use_special = self.s.m.bin(c, Bin::Or, naninf, zero_exp); + use_special = self.s.m.bin(c, Bin::Or, use_special, overflow); + use_special = self.s.m.bin(c, Bin::Or, use_special, underflow); + fexp = self.s.m.select(c, use_special, special_exp, fexp); + let finite_man = self.s.m.select(c, overflow, zero, mant); + mant = self.s.m.select(c, use_special, special_man, finite_man); + let sign_bit = self.s.m.bin(c, Bin::Shl, sign, sign_shift); + let exp_shift32 = self.s.m.i32(23); + let exp_bit = self.s.m.bin(c, Bin::Shl, fexp, exp_shift32); + let bits = self.s.m.bin(c, Bin::Or, sign_bit, exp_bit); + let bits = self.s.m.bin(c, Bin::Or, bits, mant); + self.s.m.cast(c, Cast::Bitcast, bits, self.s.t.f32) + } + + /// A 64-bit source (a register pair; inline constants sign-extend). + fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let c = self.cur; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok(l.join64(lo, hi)) + }; + match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)), + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1)) + } + Operand::Const(k @ 128..=208) => { + let x = crate::resource::inline(k).ok_or("a special operand")?; + Ok(self.s.m.int_const(i64t, i64::from(x as i32))) + } + _ => { + // Literals and the null register: zero-extended. + let x = self.operand(inst, &op)?; + Ok(self.s.m.cast(c, Cast::ZExt, x, i64t)) + } + } + } + + 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 low and high dwords of an i64. + fn split64(&mut self, x: V) -> (V, V) { + let c = self.cur; + let i64t = self.s.m.int(64); + let k32 = self.s.m.int_const(i64t, 32); + let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32); + let hi = self.s.m.bin(c, Bin::LShr, x, k32); + let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32); + (lo, hi) + } + + /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0): + /// 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<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + 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 => {} + 5 => high = true, + 6 => {} + _ => return Err("a byte select on a 16-bit operation"), + } + } + let x = match self.src0 { + Some(x) if k == 0 => x, + _ => self.f16_operand(inst, &op)?, + }; + let c = self.cur; + let x = if high { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + Ok(self.s.m.bin(c, Bin::And, x, m)) + } + + /// An f16 source as an f32 (exact), with its abs/neg modifiers. + fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let h = self.half_src(inst, k)?; + let f32t = self.s.t.f32; + let mut f = self + .s + .op(self.cur, "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(self.cur, Bin::Sub, z, f); + } + Ok(f) + } + + /// Writes a 16-bit result (low bits of `x`) into the destination's low + /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select); + /// the other half is kept (GFX10). + fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 16-bit result outside a VGPR"); + }; + let mut high = v.opsel >> 3 & 1 != 0; + // SDWA: the word written, the other one kept (preserve) or zero + // (pad; a sign extension above the high word adds nothing). + let mut keep = true; + if let Some(sd) = v.sdwa { + match (sd.dst_sel, sd.dst_unused) { + (4, 2) => {} + (5, 2) => high = true, + (4 | 6, _) => keep = false, + (5, _) => (high, keep) = (true, false), + _ => return Err("an SDWA destination of a 16-bit operation"), + } + } + let c = self.cur; + 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); + let r = if high { + let o = self.s.m.bin(c, Bin::And, old, low); + let x = self.s.m.bin(c, Bin::Shl, x, k16); + self.s.m.bin(c, Bin::Or, o, x) + } else { + let keep = self.s.m.i32(0xFFFF_0000); + let o = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, o, x) + }; + self.write_placed(inst, Reg::V(reg), r, guard); + Ok(()) + } + + /// 16-bit operations, computed in f32 or i32: f16 sums, differences and + /// products are exact there and round once to f16 (f32 has the 2 x 11 + + /// 2 bits that make double rounding harmless); `None` if `name` is none. + fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> { + const FLOAT2: &[&str] = &[ + "v_add_f16", + "v_sub_f16", + "v_subrev_f16", + "v_mul_f16", + "v_max_f16", + "v_min_f16", + ]; + const FLOAT3: &[&str] = &[ + "v_fma_f16", + "v_mad_f16", + "v_fmac_f16", + "v_mac_f16", + "v_max3_f16", + "v_min3_f16", + "v_med3_f16", + ]; + const FLOAT1: &[&str] = &[ + "v_rcp_f16", + "v_sqrt_f16", + "v_rsq_f16", + "v_log_f16", + "v_exp_f16", + "v_fract_f16", + "v_trunc_f16", + "v_floor_f16", + "v_ceil_f16", + "v_rndne_f16", + "v_sin_f16", + "v_cos_f16", + "v_cvt_f16_u16", + "v_cvt_f16_i16", + ]; + const INT: &[&str] = &[ + "v_add_nc_u16", + "v_sub_nc_u16", + "v_subrev_nc_u16", + "v_mul_lo_u16", + "v_lshlrev_b16", + "v_lshrrev_b16", + "v_ashrrev_i16", + "v_max_u16", + "v_max_i16", + "v_min_u16", + "v_min_i16", + "v_cvt_u16_f16", + "v_cvt_i16_f16", + "v_cvt_norm_i16_f16", + "v_cvt_norm_u16_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") + { + return None; + } + Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3)) + } + + #[allow(clippy::too_many_arguments)] + fn valu16_op( + &mut self, + inst: &Inst, + name: &str, + guard: Option<V>, + float1: &[&str], + float2: &[&str], + float3: &[&str], + ) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let c = self.cur; + let i32t = self.s.t.i32; + let f32t = self.s.t.f32; + if name == "v_cvt_f32_f16" { + let f = self.half_fsrc(inst, 0)?; + return self.write_f(inst, f, guard); + } + let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> { + match v.omod { + 0 => {} + k => { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)]; + let k = l.s.m.f32(factor.to_bits()); + f = l.s.m.bin(l.cur, Bin::Mul, f, k); + } + } + if v.clamp { + f = l.unary(7, f); + } + // The console rounds to nearest; the host's conversion may round toward zero + // (NVIDIA's does), one step of the last place lower where the two differ. + // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1` + // ([`f16_nearest_on`]), which costs a dozen instructions per result. + let h = if f16_nearest_on() { + l.f16_nearest(f) + } else { + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; + l.write_half(inst, h, guard) + }; + if name == "v_cvt_f16_f32" { + let f = self.fsrc(inst, 0)?; + return float_result(self, f); + } + if float2.contains(&name) { + let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); + let r = match name { + "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b), + "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b), + "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a), + "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b), + "v_max_f16" => self.max_min(true, a, b), + _ => self.max_min(false, a, b), + }; + return float_result(self, r); + } + if float3.contains(&name) { + let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); + let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") { + // The accumulator is the destination's half that is written. + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("an accumulator"); + }; + let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?; + let x = if v.opsel >> 3 & 1 != 0 { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + let x = self.s.m.bin(c, Bin::And, x, m); + self.s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]) + } else { + self.half_fsrc(inst, 2)? + }; + let r = match name { + // shortcut: fused f16 multiply-adds as FMad in f32 (the + // product is exact; the sum rounds twice). + "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc), + "v_max3_f16" => { + let t = self.max_min(true, a, b); + self.max_min(true, t, acc) + } + "v_min3_f16" => { + let t = self.max_min(false, a, b); + self.max_min(false, t, acc) + } + _ => self.med3(a, b, acc), + }; + return float_result(self, r); + } + if float1.contains(&name) { + let r = match name { + "v_cvt_f16_u16" | "v_cvt_f16_i16" => { + let mut x = self.half_src(inst, 0)?; + let op = if name == "v_cvt_f16_i16" { + let k16 = self.s.m.i32(16); + let t = self.s.m.bin(c, Bin::Shl, x, k16); + x = self.s.m.bin(c, Bin::AShr, t, k16); + Cast::SiToFp + } else { + Cast::UiToFp + }; + self.s.m.cast(c, op, x, f32t) + } + "v_rcp_f16" => { + let a = self.half_fsrc(inst, 0)?; + let one = self.s.m.f32(1.0f32.to_bits()); + self.s.m.bin(c, Bin::SDiv, one, a) + } + _ => { + let a = self.half_fsrc(inst, 0)?; + let op = match name { + "v_sqrt_f16" => 24, + "v_rsq_f16" => 25, + "v_log_f16" => 23, + "v_exp_f16" => 21, + "v_fract_f16" => 22, + "v_trunc_f16" => 29, + "v_floor_f16" => 27, + "v_ceil_f16" => 28, + "v_rndne_f16" => 26, + "v_sin_f16" => 13, + _ => 12, + }; + match op { + 12 | 13 => self.trig_turns(a, op == 12), + // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11). + 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0), + _ => self.unary(op, a), + } + } + }; + return float_result(self, r); + } + if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + // Toward zero, saturating at the 16-bit range (infinities + // included); NaN gives 0. Clamped in f32 first, where every + // f16 is exact, so the conversion never leaves i32's range + // (upstream PR #384's arithmetic; the source's abs and neg + // modifiers are applied by `half_fsrc`, as before). + let a = self.half_fsrc(inst, 0)?; + let (lo, hi) = if name == "v_cvt_u16_f16" { + (0.0f32, 65535.0f32) + } else { + (-32768.0, 32767.0) + }; + let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); + let t = self.binary(35, a, lo); + let t = self.binary(36, t, hi); + let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); + let nan = self.s.m.cmp(c, pred::UNO, a, a); + let z = self.s.m.i32(0); + let r = self.s.m.select(c, nan, z, r); + return self.write_half(inst, r, guard); + } + if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; + return self.write_half(inst, r, guard); + } + // 16-bit integers: computed on the low halves, the low 16 bits kept. + if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = { + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if name.ends_with("_i16") { + a = sext(self, a); + b = sext(self, b); + } + let k15 = self.s.m.i32(15); + 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_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); + let x = if name == "v_ashrrev_i16" { + sext(self, b) + } else { + b + }; + let op = match name { + "v_lshlrev_b16" => Bin::Shl, + "v_lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, x, sh) + } + _ => { + let p = match name { + "v_max_u16" => pred::IUGT, + "v_min_u16" => pred::IULT, + "v_max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) + } + } + }; + self.write_half(inst, r, guard) + } + + /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its + /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535, + /// rounded to nearest even once from the exact product; NaN gives 0. + /// Worked on the f16's bits in integers, because in f32 the product + /// (up to 26 significant bits) would round before the rounding to an + /// integer. + fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let mut h = self.half_src(inst, 0)?; + if v.abs & 1 != 0 { + let m = k(self, 0x7FFF); + h = self.s.m.bin(c, Bin::And, h, m); + } + if v.neg & 1 != 0 { + let m = k(self, 0x8000); + h = self.s.m.bin(c, Bin::Xor, h, m); + } + let scale = if signed { 0x7FFF } else { 0xFFFF }; + let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10)); + let mag_mask = k(self, 0x7FFF); + let mag = self.s.m.bin(c, Bin::And, h, mag_mask); + let k15 = k(self, 15); + let neg = self.s.m.bin(c, Bin::LShr, h, k15); + let neg = self.s.m.cmp(c, pred::NE, neg, k0); + // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24. + let exp = self.s.m.bin(c, Bin::LShr, mag, k10); + let man_mask = k(self, 0x3FF); + let man = self.s.m.bin(c, Bin::And, mag, man_mask); + let implicit = k(self, 0x400); + let normal = self.s.m.bin(c, Bin::Or, man, implicit); + let sub = self.s.m.cmp(c, pred::EQ, exp, k0); + let m = self.s.m.select(c, sub, man, normal); + let k25 = k(self, 25); + let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp); + let k24 = k(self, 24); + let sh = self.s.m.select(c, sub, k24, s_norm); + let ks = k(self, scale); + let p = self.s.m.bin(c, Bin::Mul, m, ks); + let q = self.s.m.bin(c, Bin::LShr, p, sh); + let one_s = self.s.m.bin(c, Bin::Shl, k1, sh); + let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1); + let rem = self.s.m.bin(c, Bin::And, p, low_mask); + let half = self.s.m.bin(c, Bin::LShr, one_s, k1); + let above = self.s.m.cmp(c, pred::IUGT, rem, half); + let tie = self.s.m.cmp(c, pred::EQ, rem, half); + let odd = self.s.m.bin(c, Bin::And, q, k1); + let odd = self.s.m.cmp(c, pred::NE, odd, k0); + let tie_up = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, above, tie_up); + let r = self.s.m.select(c, up, k1, k0); + let r = self.s.m.bin(c, Bin::Add, q, r); + // |x| >= 1 (and infinity) saturates; NaN gives 0. + let one_h = k(self, 0x3C00); + let big = self.s.m.cmp(c, pred::IUGE, mag, one_h); + let r = self.s.m.select(c, big, ks, r); + let inf = k(self, 0x7C00); + let nan = self.s.m.cmp(c, pred::IUGT, mag, inf); + let r = self.s.m.select(c, nan, k0, r); + let r = if signed { + let n = self.s.m.bin(c, Bin::Sub, k0, r); + self.s.m.select(c, neg, n, r) + } else { + self.s.m.select(c, neg, k0, r) + }; + let m16 = k(self, 0xFFFF); + Ok(self.s.m.bin(c, Bin::And, r, m16)) + } + + /// Half `high` of source `k` of a packed (VOP3P) operation, in the low + /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the + /// half the high result reads. Packed integer instructions see the f32 + /// bits of an inline float constant. + fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0; + let x = if float { + self.f16_operand(inst, &op)? + } else { + self.operand(inst, &op)? + }; + let c = self.cur; + let x = if sel { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + Ok(self.s.m.bin(c, Bin::And, x, m)) + } + + /// 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<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let float = op.ends_with("_f16"); + let n = match op { + "fma_f16" | "mad_u16" | "mad_i16" => 3, + "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16" + | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" + | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2, + _ => return Err("a packed 16-bit operation"), + }; + 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; + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let mut halves = Vec::new(); + for high in [false, true] { + let mut xs = Vec::new(); + for k in 0..n { + let h = self.packed_src(inst, k, high, float)?; + if float { + let mut f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + let neg = if high { v.neg_hi } else { v.neg }; + if neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(c, Bin::Sub, z, f); + } + xs.push(f); + } else { + xs.push(h); + } + } + let r = if float { + let mut f = match op { + "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), + "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), + "min_f16" => self.max_min(false, xs[0], xs[1]), + "max_f16" => self.max_min(true, xs[0], xs[1]), + // shortcut: FMad in f32, as v_fma_f16. + _ => self.fmad(xs[0], xs[1], xs[2]), + }; + if v.clamp { + f = self.unary(7, f); + } + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + } else { + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if op.ends_with("_i16") { + for x in &mut xs { + *x = sext(self, *x); + } + } + let k15 = self.s.m.i32(15); + 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]), + "mad_u16" | "mad_i16" => { + let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]); + self.s.m.bin(c, Bin::Add, m, xs[2]) + } + "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => { + let sh = self.s.m.bin(c, Bin::And, xs[0], k15); + let o = match op { + "lshlrev_b16" => Bin::Shl, + "lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + let x = if op == "ashrrev_i16" { + sext(self, xs[1]) + } else { + xs[1] + }; + self.s.m.bin(c, o, x, sh) + } + _ => { + let p = match op { + "max_u16" => pred::IUGT, + "min_u16" => pred::IULT, + "max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, xs[0], xs[1]); + self.s.m.select(c, t, xs[0], xs[1]) + } + } + }; + let m = self.s.m.i32(0xFFFF); + halves.push(self.s.m.bin(c, Bin::And, r, m)); + } + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); + let r = self.s.m.bin(c, Bin::Or, halves[0], hi); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a packed result outside a VGPR"); + }; + self.write(inst, Reg::V(reg), r, guard); + Ok(()) + } + + fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> { + let c = self.cur; + let s = |l: &mut Self, k| l.src(inst, k); + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let m31 = |l: &mut Self, x: V| { + let k31 = l.s.m.i32(31); + l.s.m.bin(c, Bin::And, x, k31) + }; + Ok(match name { + "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32" + | "v_subrev_nc_u32" | "v_mul_lo_u32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let (op, a, b) = match name { + "v_and_b32" => (Bin::And, a, b), + "v_or_b32" => (Bin::Or, a, b), + "v_xor_b32" => (Bin::Xor, a, b), + "v_add_nc_u32" => (Bin::Add, a, b), + "v_sub_nc_u32" => (Bin::Sub, a, b), + "v_subrev_nc_u32" => (Bin::Sub, b, a), + _ => (Bin::Mul, a, b), + }; + self.s.m.bin(c, op, a, b) + } + "v_xnor_b32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let x = self.s.m.bin(c, Bin::Xor, a, b); + let ones = k(self, u32::MAX); + self.s.m.bin(c, Bin::Xor, x, ones) + } + "v_not_b32" => { + let a = s(self, 0)?; + let ones = k(self, u32::MAX); + self.s.m.bin(c, Bin::Xor, a, ones) + } + "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => { + let (sh, a) = (s(self, 0)?, s(self, 1)?); + let sh = m31(self, sh); + let op = match name { + "v_lshlrev_b32" => Bin::Shl, + "v_lshrrev_b32" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, a, sh) + } + "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32" + | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + match name { + "v_lshl_add_u32" | "v_lshl_or_b32" => { + let b = m31(self, b); + let t = self.s.m.bin(c, Bin::Shl, a, b); + let op = if name == "v_lshl_add_u32" { + Bin::Add + } else { + Bin::Or + }; + self.s.m.bin(c, op, t, d) + } + "v_add_lshl_u32" => { + let t = self.s.m.bin(c, Bin::Add, a, b); + let d = m31(self, d); + self.s.m.bin(c, Bin::Shl, t, d) + } + _ => { + let (o1, o2) = match name { + "v_and_or_b32" => (Bin::And, Bin::Or), + "v_or3_b32" => (Bin::Or, Bin::Or), + "v_xad_u32" => (Bin::Xor, Bin::Add), + "v_add3_u32" => (Bin::Add, Bin::Add), + _ => (Bin::Xor, Bin::Xor), + }; + let t = self.s.m.bin(c, o1, a, b); + self.s.m.bin(c, o2, t, d) + } + } + } + "v_mul_u32_u24" | "v_mul_i32_i24" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let (sh, op) = ( + k(self, 8), + if name == "v_mul_i32_i24" { + Bin::AShr + } else { + Bin::LShr + }, + ); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + self.s.m.bin(c, Bin::Mul, a, b) + } + "v_bfe_u32" | "v_bfe_i32" => { + let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let w = m31(self, w); + self.bfe(a, off, w, name == "v_bfe_i32") + } + "v_bfi_b32" => { + let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let ones = k(self, u32::MAX); + let nm = self.s.m.bin(c, Bin::Xor, m, ones); + let x = self.s.m.bin(c, Bin::And, m, a); + let y = self.s.m.bin(c, Bin::And, nm, b); + self.s.m.bin(c, Bin::Or, x, y) + } + "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let p = match name { + "v_max_i32" => pred::SGT, + "v_min_i32" => pred::SLT, + "v_max_u32" => pred::IUGT, + _ => pred::IULT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) + } + "v_mul_hi_u32" | "v_mul_hi_i32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + self.mul_hi(a, b, name == "v_mul_hi_i32") + } + "v_alignbit_b32" | "v_alignbyte_b32" => { + // The low dword of {a, b} >> shift. + let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let sh = if name == "v_alignbyte_b32" { + let three = k(self, 3); + let t = self.s.m.bin(c, Bin::And, sh, three); + let k3 = k(self, 3); + self.s.m.bin(c, Bin::Shl, t, k3) + } else { + m31(self, sh) + }; + let k32 = k(self, 32); + let lo = self.s.m.bin(c, Bin::LShr, b, sh); + let left = self.s.m.bin(c, Bin::Sub, k32, sh); + let left = m31(self, left); + let hi = self.s.m.bin(c, Bin::Shl, a, left); + let zero = k(self, 0); + let none = self.s.m.cmp(c, pred::EQ, sh, zero); + let hi = self.s.m.select(c, none, zero, hi); + self.s.m.bin(c, Bin::Or, lo, hi) + } + "v_bfrev_b32" => { + let a = s(self, 0)?; + self.s + .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]) + } + "v_bcnt_u32_b32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let n = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]); + self.s.m.bin(c, Bin::Add, n, b) + } + "v_mad_u32_u24" | "v_mad_i32_i24" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let (sh, op) = ( + k(self, 8), + if name == "v_mad_i32_i24" { + Bin::AShr + } else { + Bin::LShr + }, + ); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + let m = self.s.m.bin(c, Bin::Mul, a, b); + self.s.m.bin(c, Bin::Add, m, d) + } + "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32" + | "v_med3_u32" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let signed = name.ends_with("i32"); + let (lt, gt) = if signed { + (pred::SLT, pred::SGT) + } else { + (pred::IULT, pred::IUGT) + }; + let pick = |l: &mut Self, p, x, y| { + let t = l.s.m.cmp(c, p, x, y); + l.s.m.select(c, t, x, y) + }; + match &name[2..6] { + "min3" => { + let t = pick(self, lt, a, b); + pick(self, lt, t, d) + } + "max3" => { + let t = pick(self, gt, a, b); + pick(self, gt, t, d) + } + _ => { + let lo = pick(self, lt, a, b); + let hi = pick(self, gt, a, b); + let t = pick(self, lt, hi, d); + pick(self, gt, lo, t) + } + } + } + "v_perm_b32" => { + // Byte i of the result is byte S of {src0, src1} (src1 the + // low dword) for selector byte S below 8; 8-11 repeat the + // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00, + // higher 0xFF. + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let sel = match v.src.get(2) { + Some(&Operand::Literal(x)) => x, + Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?, + _ => { + // A computed selector: each byte picked at run time. + let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let mut r = k(self, 0); + for i in 0..4u32 { + let (sh, ff) = (k(self, 8 * i), k(self, 0xFF)); + let sel = self.s.m.bin(c, Bin::LShr, sv, sh); + let sel = self.s.m.bin(c, Bin::And, sel, ff); + // Select a dword and a byte within it. + // Later selects handle codes 8 and above. + let four = k(self, 4); + let zero = k(self, 0); + let high = self.s.m.bin(c, Bin::And, sel, four); + let high = self.s.m.cmp(c, pred::NE, high, zero); + let word = self.s.m.select(c, high, a, b); + let three = k(self, 3); + let index = self.s.m.bin(c, Bin::And, sel, three); + let bits = self.s.m.bin(c, Bin::Shl, index, three); + let x = self.s.m.bin(c, Bin::LShr, word, bits); + let mut byte = self.s.m.bin(c, Bin::And, x, ff); + // 8-11: the sign of bytes 1, 3 of src1, then of src0. + for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)] + { + let left = k(self, 31 - bit); + let t = self.s.m.bin(c, Bin::Shl, src, left); + let k31 = k(self, 31); + let t = self.s.m.bin(c, Bin::AShr, t, k31); + let t = self.s.m.bin(c, Bin::And, t, ff); + let kn = k(self, n); + let is = self.s.m.cmp(c, pred::EQ, sel, kn); + byte = self.s.m.select(c, is, t, byte); + } + let (k12, z) = (k(self, 12), k(self, 0)); + let is12 = self.s.m.cmp(c, pred::EQ, sel, k12); + byte = self.s.m.select(c, is12, z, byte); + let above = self.s.m.cmp(c, pred::IUGT, sel, k12); + byte = self.s.m.select(c, above, ff, byte); + let at = k(self, 8 * i); + let byte = self.s.m.bin(c, Bin::Shl, byte, at); + r = self.s.m.bin(c, Bin::Or, r, byte); + } + return Ok(r); + } + }; + let (a, b) = (s(self, 0)?, s(self, 1)?); + let mut r = k(self, 0); + for i in 0..4 { + let pick = sel >> (8 * i) & 0xFF; + let byte = match pick { + 0..=7 => { + let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) }; + let sh = k(self, 8 * n); + let t = self.s.m.bin(c, Bin::LShr, src, sh); + let ff = k(self, 0xFF); + self.s.m.bin(c, Bin::And, t, ff) + } + 8..=11 => { + let src = if pick < 10 { b } else { a }; + let bit = if pick % 2 == 0 { 15 } else { 31 }; + let left = k(self, 31 - bit); + let t = self.s.m.bin(c, Bin::Shl, src, left); + let k31 = k(self, 31); + let t = self.s.m.bin(c, Bin::AShr, t, k31); + let ff = k(self, 0xFF); + self.s.m.bin(c, Bin::And, t, ff) + } + 12 => continue, + _ => k(self, 0xFF), + }; + let at = k(self, 8 * i); + let byte = self.s.m.bin(c, Bin::Shl, byte, at); + r = self.s.m.bin(c, Bin::Or, r, byte); + } + r + } + "v_bfm_b32" => { + // ((1 << src0[4:0]) - 1) << src1[4:0] + let (a, b) = (s(self, 0)?, s(self, 1)?); + let one = k(self, 1); + let (a, b) = (m31(self, a), m31(self, b)); + let m = self.s.m.bin(c, Bin::Shl, one, a); + let m = self.s.m.bin(c, Bin::Sub, m, one); + self.s.m.bin(c, Bin::Shl, m, b) + } + "v_cvt_pk_u8_f32" => { + // src0 rounded to nearest even and saturated to a byte, into + // byte src1[1:0] of src2. + let f = self.fsrc(inst, 0)?; + let (b, d) = (s(self, 1)?, s(self, 2)?); + let f = self.unary(26, f); + let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits())); + let f = self.binary(35, f, zero); + let f = self.binary(36, f, max); + let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32); + let (three, k3) = (k(self, 3), k(self, 3)); + let sh = self.s.m.bin(c, Bin::And, b, three); + let sh = self.s.m.bin(c, Bin::Shl, sh, k3); + let x = self.s.m.bin(c, Bin::Shl, x, sh); + let ff = k(self, 0xFF); + let hole = self.s.m.bin(c, Bin::Shl, ff, sh); + let ones = k(self, u32::MAX); + let hole = self.s.m.bin(c, Bin::Xor, hole, ones); + let d = self.s.m.bin(c, Bin::And, d, hole); + self.s.m.bin(c, Bin::Or, d, x) + } + "v_ffbl_b32" => { + // -1 for zero, as DXIL's first-bit-low. + let a = s(self, 0)?; + self.s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a]) + } + "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => { + // Bits of the mask's low (high) half below this lane, plus src1: + // with an all-ones mask, the lane index. + let (a, b) = (s(self, 0)?, s(self, 1)?); + // Mesh lanes are the console's by construction; pixel and + // vertex lanes are the host's, as their masks are. + if self.mask_data == MaskData::Host { + // Host lanes: the mask must be one (a ballot) or all lanes. + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let host = match v.src.first() { + Some(&Operand::Const(193)) => true, + Some(&Operand::Scalar { code, .. }) => { + inst.read(Reg::S(code)).is_some_and(|m| { + self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m) + }) + } + _ => false, + }; + if !host { + return Err("v_mbcnt of a mask that is no ballot (console lane layout)"); + } + self.s.flags |= flags::WAVE_OPS; + } else if self.s.mesh.is_none() { + self.cross_lane(false)?; + } + let lane = self.console_lane(); + let below = if name == "v_mbcnt_lo_u32_b32" { + lane + } else { + let (k32, z) = (k(self, 32), k(self, 0)); + let t = self.s.m.bin(c, Bin::Sub, lane, k32); + let low = self.s.m.cmp(c, pred::IULT, lane, k32); + self.s.m.select(c, low, z, t) + }; + // (1 << below) - 1, all ones from 32 on. + let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX)); + let sh = m31(self, below); + let m = self.s.m.bin(c, Bin::Shl, one, sh); + let m = self.s.m.bin(c, Bin::Sub, m, one); + let full = self.s.m.cmp(c, pred::IUGE, below, k32); + let m = self.s.m.select(c, full, ones, m); + let x = self.s.m.bin(c, Bin::And, a, m); + let n = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]); + self.s.m.bin(c, Bin::Add, n, b) + } + _ => return Err(name), + }) + } + + fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> { + let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?; + let c = self.cur; + let r = match ty { + "f32" | "f16" if op == "class" => { + // Bit k of src1 tests class k: signalling NaN, quiet NaN, + // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf. + let f16 = ty == "f16"; + let x = if f16 { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let mut h = self.half_src(inst, 0)?; + if v.abs & 1 != 0 { + let m = self.s.m.i32(0x7FFF); + h = self.s.m.bin(c, Bin::And, h, m); + } + if v.neg & 1 != 0 { + let s = self.s.m.i32(0x8000); + h = self.s.m.bin(c, Bin::Xor, h, s); + } + h + } else { + let x = self.fsrc(inst, 0)?; + self.as_int(x) + }; + let mask = self.src(inst, 1)?; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 { + (10, 15, 0x1F, 0x03FF, 0x0200) + } else { + (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000) + }; + let (k_exp, k_sign, k_emax, mant, quiet) = ( + k(self, exp_sh), + k(self, sign_sh), + k(self, exp_mask), + k(self, mant_mask), + k(self, quiet_bit), + ); + let e = self.s.m.bin(c, Bin::LShr, x, k_exp); + let e = self.s.m.bin(c, Bin::And, e, k_emax); + let m = self.s.m.bin(c, Bin::And, x, mant); + let neg = self.s.m.bin(c, Bin::LShr, x, k_sign); + let zero = k(self, 0); + let (e0, emax) = ( + self.s.m.cmp(c, pred::EQ, e, zero), + self.s.m.cmp(c, pred::EQ, e, k_emax), + ); + let m0 = self.s.m.cmp(c, pred::EQ, m, zero); + let q = self.s.m.bin(c, Bin::And, x, quiet); + let q = self.s.m.cmp(c, pred::NE, q, zero); + // Positive classes 6-9; negative ones are 11 minus those. + let (normal, inf, zero_c, denorm) = + (k(self, 8), k(self, 9), k(self, 6), k(self, 7)); + let t = self.s.m.select(c, m0, zero_c, denorm); + let t = self.s.m.select(c, e0, t, normal); + let t = self.s.m.select(c, emax, inf, t); + let eleven = k(self, 11); + let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t); + let is_neg = self.s.m.cmp(c, pred::NE, neg, zero); + let t = self.s.m.select(c, is_neg, mirrored, t); + let (one, snan) = (k(self, 1), k(self, 0)); + let nan_class = self.s.m.select(c, q, one, snan); + let yes = self.s.m.bool(true); + let nan = self.s.m.bin(c, Bin::Xor, m0, yes); + let nan = self.s.m.bin(c, Bin::And, nan, emax); + let t = self.s.m.select(c, nan, nan_class, t); + let bit = self.s.m.bin(c, Bin::LShr, mask, t); + let bit = self.s.m.bin(c, Bin::And, bit, one); + self.s.m.cmp(c, pred::NE, bit, zero) + } + "f32" | "f16" => { + let (a, b) = if ty == "f16" { + (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?) + } else { + (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) + }; + if op == "lg" { + // Ordered and not equal, false for a NaN, as `olt | ogt`. + // `fcmp one` means the same, but the AMD D3D12 driver + // runs it as unordered (true for a NaN) where NVIDIA + // and WARP do not; olt and ogt agree on all three. + let lt = self.s.m.cmp(c, pred::OLT, a, b); + let gt = self.s.m.cmp(c, pred::OGT, a, b); + self.s.m.bin(c, Bin::Or, lt, gt) + } else { + let p = match op { + "f" => pred::FALSE, + "lt" => pred::OLT, + "eq" => pred::OEQ, + "le" => pred::OLE, + "gt" => pred::OGT, + "ge" => pred::OGE, + "o" => pred::ORD, + "u" => pred::UNO, + "nge" => pred::ULT, + "nlg" => pred::UEQ, + "ngt" => pred::ULE, + "nle" => pred::UGT, + "neq" => pred::UNE, + "nlt" => pred::UGE, + "tru" => pred::TRUE, + _ => return Err(inst.name()), + }; + self.s.m.cmp(c, p, a, b) + } + } + "u64" | "i64" => { + let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); + let signed = ty == "i64"; + let p = match op { + "eq" => pred::EQ, + "ne" | "lg" => pred::NE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" => pred::IULT, + "le" => pred::IULE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + _ => return Err("a 64-bit compare"), + }; + self.s.m.cmp(c, p, a, b) + } + "u32" | "i32" | "u16" | "i16" => { + let (a, b) = if ty.ends_with("16") { + 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] { + let t = self.s.m.bin(c, Bin::Shl, *x, k16); + *x = self.s.m.bin(c, Bin::AShr, t, k16); + } + } + (a, b) + } else { + (self.src(inst, 0)?, self.src(inst, 1)?) + }; + let signed = ty == "i32" || ty == "i16"; + let p = match op { + "eq" => pred::EQ, + "ne" | "lg" => pred::NE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" => pred::IULT, + "le" => pred::IULE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + "f" | "t" => { + self.lane(inst, Some(op == "t")); + return Ok(()); + } + _ => return Err("an integer compare"), + }; + self.s.m.cmp(c, p, a, b) + } + _ => return Err(inst.name()), + }; + self.lane_bits_for(inst, r); + Ok(()) + } + + fn lane(&mut self, inst: &Inst, value: Option<bool>) { + let b = self.s.m.bool(value == Some(true)); + self.lane_bits_for(inst, b); + } + + fn lane_bits_for(&mut self, inst: &Inst, r: V) { + let Fields::Valu(v) = &inst.fields else { + return; + }; + let code = if inst.name().starts_with("v_cmpx") { + Some(EXEC) + } else { + match v.dst { + Some(Operand::Scalar { code, .. }) => Some(code), + _ => None, + } + }; + if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) { + self.lane_bits.insert(lo, r); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + } + + fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + let Some(&interp) = self.interps.get(&site) else { + return Err("the first half of an interpolation"); + }; + let name = inst.name(); + let (dst, src) = match &inst.fields { + Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)), + Fields::Valu(v) => { + if v.abs != 0 || v.neg != 0 { + return Err("interpolation operand modifiers"); + } + (v.dst.ok_or("an interpolation")?, v.src.get(1).copied()) + } + _ => unreachable!(), + }; + let Operand::Vector { reg, .. } = dst else { + return Err("an interpolation"); + }; + // A float operand of the instruction. + let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> { + let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?; + Ok(l.as_float(x)) + }; + // What the result adds to the evaluated channel (a second half's + // first half, when the halves evaluate on their own). + let mut add = None; + let (attribute, eval) = match *interp { + Interp::Interpolated { + attribute, + barycentric, + .. + } => { + let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?; + let eval = if self.per_vertex(attribute.row) { + // The element is read per vertex elsewhere, so it is + // constant: weigh its vertices with SV_Barycentrics. + let mut ij = [None; 2]; + for (index, w) in ij.iter_mut().enumerate() { + let x = match self.barycentric(barycentric, index as u8) { + Val::I32(x) => x, + Val::Missing(w) => return Err(w), + Val::Bit(_) => unreachable!(), + }; + *w = Some(self.as_float(x)); + } + Eval::Weights { + p0: true, + i: ij[0], + j: ij[1], + } + } else { + Eval::Mode(mode) + }; + (attribute, eval) + } + // P0, the provoking vertex: a flat (nointerpolation) input. + Interp::Vertex { + attribute, + vertex: 2, + } => (attribute, Eval::Mode(1)), + // P10 and P20: what the first and second halves weigh, P1 - P0 + // and P2 - P0, which is what the hardware holds for an + // attribute the program also interpolates. + Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => { + let one = Some(self.s.m.f32(1f32.to_bits())); + let (i, j) = if vertex == 0 { + (one, None) + } else { + (None, one) + }; + (attribute, Eval::Weights { p0: false, i, j }) + } + Interp::Vertex { .. } => return Err("a non-provoking vertex value"), + // A half of an interpolation with computed i or j: P0 + i P10, + // or the old dst (f16: the third operand) + j P20. + Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => { + let i = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: true, + i, + j: None, + }, + ) + } + Interp::Weighted { attribute } => { + let old = match &inst.fields { + Fields::Valu(v) => v.src.get(2).copied(), + _ => Some(dst), + }; + add = Some(float(self, old)?); + let j = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: false, + i: None, + j, + }, + ) + } + }; + let packing = match &self.x.native.io { + StageIo::Ps { inputs, .. } => inputs + .iter() + .find(|i| i.row == attribute.row && i.fp16) + .map(|i| { + let packs = if i.pack2 { + input_packs(&self.x.native.io, &self.s.inputs) + } else { + Vec::new() + }; + (i.pack2, packs) + }), + _ => None, + }; + let f16 = name.ends_with("_f16"); + // The evaluated channel plus `add`, as a float. + let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> { + let x = l.eval_channel(row, ch, eval)?; + let x = l.as_float(x); + Ok(match add { + Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x), + None => x, + }) + }; + let x = match packing { + None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"), + None => { + let x = total(self, attribute.row, attribute.channel)?; + self.as_int(x) + } + Some((pack2, packs)) => { + // 16-bit values: one in the low half of each dword, or two + // per dword (`packed_half`); the host's are 32-bit floats. + let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> { + let src = if pack2 { + packed_half(&l.s.inputs, &packs, attribute.row, h) + } else { + h.is_multiple_of(2).then_some((attribute.row, h / 2)) + }; + match src { + Some((row, ch)) => total(l, row, ch).map(Some), + None => Ok(None), + } + }; + let to_f16 = |l: &mut Self, f: V| { + let i32t = l.s.t.i32; + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; + let h = 2 * attribute.channel + u8::from(attribute.high); + let c = self.cur; + if name == "v_interp_p1ll_f16" { + // An f32 result from 16-bit vertex values. + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + self.as_int(f) + } else if f16 { + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + let lo = to_f16(self, f); + self.low_half(inst, reg, lo) + } else if matches!(eval, Eval::Mode(1)) { + // The whole dword of a flat input: both halves. + let h = 2 * attribute.channel; + let z = self.s.m.i32(0); + let lo = match half(self, h)? { + Some(f) => to_f16(self, f), + None => z, + }; + let hi = match half(self, h + 1)? { + Some(f) => to_f16(self, f), + None => z, + }; + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } else { + return Err("32-bit interpolation of a 16-bit input"); + } + } + }; + // A pixel interpolates in every lane; guards only hide inactive ones. + self.write(inst, Reg::V(reg), x, None); + Ok(()) + } + + /// Whether the program reads attribute row `row` per vertex (an + /// interpolation with computed barycentrics, or P10 or P20): then its + /// element is declared constant and read with `attributeAtVertex`. + fn per_vertex(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Weighted { attribute } => attribute.row == row, + Interp::Vertex { attribute, vertex } => { + attribute.row == row && vertex != 2 && self.interpolated(row) + } + Interp::Interpolated { .. } => false, + }) + } + + /// Whether the program interpolates attribute row `row` (so the + /// hardware holds P1 - P0 and P2 - P0 for it). + fn interpolated(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => { + attribute.row == row + } + Interp::Vertex { .. } => false, + }) + } + + /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits. + fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> { + let (id, col) = self + .find_input(row, ch) + .ok_or("an input the signature lacks")?; + let mode = match eval { + Eval::Mode(mode) => mode, + Eval::Weights { .. } => 1, + }; + let e = &mut self.s.inputs[id]; + if e.interp != mode && e.usage != 0 { + return Err("one input interpolated two ways"); + } + e.interp = mode; + let Eval::Weights { p0, i, j } = eval else { + return match self.load_any_input(id, col) { + Val::I32(x) => Ok(x), + _ => Err("an input"), + }; + }; + let v0 = self.vertex_input(id, col, 0); + let c = self.cur; + let mut acc = p0.then_some(v0); + for (k, w) in [(1, i), (2, j)] { + let Some(w) = w else { continue }; + let vk = self.vertex_input(id, col, k); + let d = self.s.m.bin(c, Bin::Sub, vk, v0); + acc = Some(match acc { + Some(a) => self.fmad(w, d, a), + None => self.s.m.bin(c, Bin::Mul, w, d), + }); + } + let acc = acc.ok_or("an interpolation")?; + Ok(self.as_int(acc)) + } + + /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them) + /// of a constant input element's channel, as a float. + fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let int = e.comp != 9; + let (ty, suffix) = if int { + (self.s.t.i32, ".i32") + } else { + (self.s.t.f32, ".f32") + }; + self.s.flags |= flags::BARYCENTRICS; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.i8(k), + ]; + let v = self.s.op( + entry, + &format!("attributeAtVertex{suffix}"), + Attr::ReadNone, + ty, + 137, + &args, + ); + if int { + self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32) + } else { + v + } + } + + /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit + /// 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 = 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); + self.s.m.bin(c, Bin::Or, old, x) + } + + fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Image { + data, + addr, + dmask, + dim, + unorm, + a16, + d16, + tfe, + lwe, + .. + } = &inst.fields + else { + unreachable!() + }; + if *tfe || *lwe { + return Err("an image access with tfe or lwe"); + } + let name = inst.name(); + // A load or sample with no channel enabled returns the first. + let dmask = if *dmask == 0 { &1 } else { dmask }; + let site = (b, i); + let guard = self.guard(b, i)?; + let c = self.cur; + let (kind, coords) = match dim { + 0 => (1, 1), + 1 => (2, 2), + 2 => (4, 3), + // Sampled (face coordinates and face, see `cube_direction`) or + // sized only. + 3 if name.starts_with("image_sample") + || name.starts_with("image_gather") + || name == "image_get_resinfo" => + { + (5, 3) + } + 4 => (6, 2), + 5 => (7, 3), + _ => return Err("an image dimension (cube loads or MSAA)"), + }; + // Address VGPRs in order. + let mut regs = Vec::new(); + for a in addr { + if let Operand::Vector { reg, dwords } = *a { + regs.extend((0..dwords).map(|k| reg + k)); + } + } + // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare). + let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> { + let r = *regs.get(reg_idx).ok_or("an image address")?; + let v = inst.read(Reg::V(r)).ok_or("an image address")?; + l.i32_of(v) + }; + // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first. + let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> { + let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?; + if !*a16 { + return Ok(x); + } + let c = l.cur; + let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF)); + let x = l.s.m.bin(c, Bin::LShr, x, sh); + Ok(l.s.m.bin(c, Bin::And, x, mask)) + }; + let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) }; + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked image")?; + let store = name.starts_with("image_store"); + let uav = store + || self + .used_kind(src) + .is_some_and(|u| u.kind == ResourceType::Uav); + let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); + if let Some(op) = name.strip_prefix("image_atomic_") { + // GLC returns the old value. DXIL implements subtraction by adding + // the two's complement of the operand at the same width. + let code = match op { + "add" | "sub" => 0, + "and" => 1, + "or" => 2, + "xor" => 3, + "smin" => 4, + "smax" => 5, + "umin" => 6, + "umax" => 7, + "swap" => 8, + "cmpswap" => u32::MAX, + _ => return Err(name), + }; + let Fields::Image { cache, .. } = &inst.fields else { + unreachable!() + }; + if *d16 || *a16 { + return Err("a 16-bit image atomic"); + } + // Compare-exchange consumes a replacement followed by a comparand. + let compare = code == u32::MAX; + let wide = match (compare, *dmask) { + (false, 1) | (true, 3) => false, + (false, 3) | (true, 15) => true, + _ => return Err("an image atomic data mask"), + }; + let iu = self.s.m.undef(self.s.t.i32); + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let Operand::Vector { reg, .. } = *data else { + return Err("image atomic data"); + }; + let width = if wide { 2 } else { 1 }; + let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?; + let (ty, component) = if wide { + 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) + }; + let original = if wide { + self.join64(vals[0], vals[1]) + } else { + vals[0] + }; + let value = if op == "sub" { + let zero = self.s.m.int_const(ty, 0); + self.s.m.bin(c, Bin::Sub, zero, original) + } else { + original + }; + let h = self.handle(site, src, false, (kind | 0x1000, component))?; + let mut args = vec![h]; + let (intrinsic, opcode) = if compare { + let comparand = if wide { + self.join64(vals[2], vals[3]) + } else { + vals[1] + }; + args.extend(cs); + args.extend([comparand, value]); + let intrinsic = if wide { + "atomicCompareExchange.i64" + } else { + "atomicCompareExchange.i32" + }; + (intrinsic, 79) + } else { + args.push(self.s.m.i32(code)); + args.extend(cs); + args.push(value); + ( + if wide { + "atomicBinOp.i64" + } else { + "atomicBinOp.i32" + }, + 78, + ) + }; + let at = self.begin_guarded(guard); + let r = self + .s + .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args); + if cache.glc { + let old = self.end_guarded(at, &[(r, original)])[0]; + if wide { + let (lo, hi) = self.split64(old); + self.write(inst, Reg::V(reg), lo, None); + self.write(inst, Reg::V(reg + 1), hi, None); + } else { + self.write(inst, Reg::V(reg), old, None); + } + } else { + self.end_guarded(at, &[]); + } + return Ok(()); + } + if store { + if name != "image_store" { + return Err("an image store to a mip level"); + } + // shortcut: stores are taken to write all four channels of a + // float format (the console converts by the view's format). + if *dmask != 0xF { + return Err("an image store of some channels"); + } + let iu = self.s.m.undef(self.s.t.i32); + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let Operand::Vector { reg, .. } = *data else { + return Err("image store data"); + }; + let mut vals = Vec::new(); + for k in 0..4u8 { + // d16: two f16 channels per VGPR, low half first. + let r = if *d16 { k / 2 } else { k }; + let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?; + vals.push(if *d16 { + let mut x = self.i32_of(v)?; + if k % 2 == 1 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(self.cur, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + self.s + .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]) + } else { + self.float_of(v)? + }); + } + let h = self.handle(site, src, false, props)?; + let at = self.begin_guarded(guard); + let mut args = vec![h]; + args.extend(cs); + args.extend(vals); + args.push(self.s.m.i8(0xF)); + let void = self.s.t.void; + self.s.op( + self.cur, + "textureStore.f32", + Attr::NoUnwind, + void, + 67, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } + let has_cl = name.ends_with("_cl"); + let (op, sample) = match name { + "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true), + "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_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_load" | "image_load_mip" => (66, false), + "image_get_resinfo" => (72, false), + _ => return Err(name), + }; + if op == 72 { + // Width, height, depth or layers, levels (per dmask) of the level + // in the first address: DXIL's dimensions; a channel DXIL leaves + // out reads 1 (UAVs: one level). + let h = self.handle(site, src, false, props)?; + let mip = if uav { + self.s.m.undef(self.s.t.i32) + } else { + addr_val(self, 0)? + }; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let one = self.s.m.i32(1); + let present = match kind { + 1 => [true, false, false, true], + 2 | 5 | 6 => [true, true, false, true], + _ => [true, true, true, true], + }; + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { + let x = if ch == 3 && uav || !present[ch as usize] { + one + } else { + self.s.m.extract(c, d, ch) + }; + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + if uav && op != 66 { + return Err("sampling a UAV"); + } + let h = self.handle(site, src, false, props)?; + let fu = self.s.m.undef(self.s.t.f32); + let iu = self.s.m.undef(self.s.t.i32); + // A gather at a named level, done as four texel reads (below). + let mut gathered: Option<[V; 4]> = None; + let r = if sample { + let ss = self + .descriptors + .get(&(site, true)) + .copied() + .ok_or("an untracked sampler")?; + // Comparison: the reference value is the first address after + // the bias, and the sampler is a comparison sampler. + let cmp = matches!(op, 64 | 65); + if cmp && (*a16 || dmask.count_ones() != 1) { + 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: 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. + 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 + } + } else { + 0 + }; + let coord_base = first + 2 * deriv_regs; + let mut cs = vec![fu; 4]; + // With a16, sampling coordinates, gradients, LOD and clamp are f16. + let to_float = |l: &mut Self, x: V| { + if *a16 { + let f = l.s.t.f32; + l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x]) + } else { + l.as_float(x) + } + }; + if kind == 5 && (*unorm || op == 81) { + return Err("a cube sample with texel coordinates or a level query"); + } + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + let x = addr_packed(self, coord_base, k)?; + *slot = to_float(self, x); + } + if kind == 5 { + let dir = self.cube_direction(cs[0], cs[1], cs[2]); + cs[..3].copy_from_slice(&dir); + } + if *unorm { + // Texel coordinates: divided by the size of level 0. + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + for (k, slot) in cs.iter_mut().enumerate().take(spatial) { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32); + *slot = self.s.m.bin(c, Bin::SDiv, *slot, n); + } + } + if op == 81 { + // The clamped then the unclamped level of detail. + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + let f32t = self.s.t.f32; + for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { + let clamped = self.s.m.bool(ch == 0); + let lod = self.s.op( + c, + "calculateLOD.f32", + Attr::ReadOnly, + f32t, + 81, + &[h, sh, cs[0], cs[1], cs[2], clamped], + ); + let x = self.as_int(lod); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let offsets = if kind == 5 { + 0 + } else { + (coords - usize::from(kind == 6 || kind == 7)).min(3) + }; + let zero = self.s.m.i32(0); + let mut os = vec![iu; 3]; + for o in os.iter_mut().take(offsets) { + *o = zero; + } + if offset_word && offsets > 0 { + let w = addr_val(self, 0)?; + for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) { + // 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); + } + } + let mut args = vec![h, sh]; + args.extend(&cs); + let clamp = if has_cl { + let x = addr_packed(self, coord_base, coords)?; + to_float(self, x) + } else { + fu + }; + match op { + // Outside a pixel shader there are no screen derivatives: + // the validator refuses `sample` there ("features + // incompatible with the shader stage": 730 compute programs, + // among them the G-buffer resolves and the sky), and what a + // driver does with it is its own affair. + // shortcut: such a sample reads level 0 (a bias: that + // level). The console takes derivatives from neighbouring + // lanes there; compute them from the lanes if a resolve + // shows the wrong mip. + 60 if !self.s.pixel => { + args.extend(&os); + args.push(self.s.m.f32(0)); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + 60 => { + if offset_word { + // DXIL wants immediate offsets in -8..=7 here; the + // console's are 6-bit and may be computed. A + // constant word in range becomes immediates + // (upstream PR #634); anything else keeps the + // offsets computed above (upstream refuses those). + let w = addr_val(self, 0)?; + if let Some(w) = self.s.m.int_value(w) { + let w = w as u32; + let field = |k: usize| { + let x = (w >> (8 * k) & 0x3F) as i32; + if x >= 32 { x - 64 } else { x } + }; + let n = offsets.min(2); + if (0..n).all(|k| (-8..=7).contains(&field(k))) { + for (k, o) in os.iter_mut().enumerate().take(n) { + *o = self.s.m.i32(field(k) as u32); + } + } + } + } + args.extend(&os); + args.push(clamp); + self.s + .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) + } + 61 => { + // With a16 the bias is an f16 in the low half of its + // word (the word is whole, the value is not). + let bias = addr_u32(self, usize::from(offset_word))?; + let bias = if *a16 { + let low = self.s.m.i32(0xFFFF); + let bias = self.s.m.bin(c, Bin::And, bias, low); + to_float(self, bias) + } else { + self.as_float(bias) + }; + args.extend(&os); + if self.s.pixel { + args.extend([bias, clamp]); + self.s.op( + c, + "sampleBias.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 61, + &args, + ) + } else { + // As above: the bias is the level. + args.push(bias); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + } + 63 if kind == 5 => { + // A cube with explicit gradients: the host wants them + // as changes of the direction, the console gives the + // changes of the face coordinates (the face is one + // unit wide). The level they select is taken from the + // longer of the two, in texels, and sampled directly. + // shortcut: no anisotropic filtering for these samples + // (the longer axis alone decides the level). + let mut len = [fu; 2]; + for (axis, slot) in len.iter_mut().enumerate() { + let mut sum = self.s.m.f32(0); + for k in 0..2 { + let x = addr_packed(self, first + axis * deriv_regs, k)?; + let x = to_float(self, x); + let sq = self.s.m.bin(c, Bin::Mul, x, x); + sum = self.s.m.bin(c, Bin::Add, sum, sq); + } + *slot = self.unary(24, sum); // square root + } + let longer = self.binary(35, len[0], len[1]); // maximum + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + let width = self.s.m.extract(c, d, 0); + let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32); + let texels = self.s.m.bin(c, Bin::Mul, longer, width); + // log2 = natural logarithm / ln 2; a length of 0 gives + // minus infinity, which the sampler clamps to level 0. + let ln = self.unary(23, texels); + let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits()); + let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2); + args.extend(&os); + args.push(lod); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + 63 => { + let mut g = vec![fu; 6]; + for k in 0..spatial { + let x = addr_packed(self, first, k)?; + g[k] = to_float(self, x); + let y = addr_packed(self, first + deriv_regs, k)?; + g[3 + k] = to_float(self, y); + } + args.extend(&os); + args.extend(g); + args.push(clamp); + self.s.op( + c, + "sampleGrad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 63, + &args, + ) + } + 64 | 65 => { + let reference = addr_u32(self, first - 1)?; + let reference = self.as_float(reference); + args.extend(&os); + args.push(reference); + let name = if op == 64 { + args.push(clamp); + "sampleCmp.f32" + } else { + "sampleCmpLevelZero.f32" + }; + self.s + .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args) + } + 62 => { + let lod = if name == "image_sample_l" { + let x = addr_packed(self, coord_base, coords)?; + to_float(self, x) + } else { + self.s.m.f32(0) + }; + args.extend(&os); + args.push(lod); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + _ => { + if name == "image_gather4" { + return Err("a gather with implicit level"); + } + if dmask.count_ones() != 1 { + return Err("a gather of several channels"); + } + if matches!(name, "image_gather4_l" | "image_gather4_l_o") + && coords == 2 + && spatial == 2 + { + // The host's gather has no level: it read level 0 + // where the title names one (the depth pyramid its + // occlusion tests read: most of the world was + // culled against the wrong depths). The four texels + // 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 + // 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 + // meshlet three or four texels wide was tested + // against a quarter of what it covers. + // shortcut: the level is rounded to a whole one and + // coordinates past the edge are clamped, whatever + // the sampler says. + let lod = addr_packed(self, coord_base, coords)?; + let lod = to_float(self, lod); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let zero = self.s.m.f32(0); + let lod = self.binary(35, lod, zero); // maximum + let lod = self.unary(26, lod); // round to nearest + let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t); + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let half = self.s.m.f32(0.5f32.to_bits()); + let one = self.s.m.f32(1.0f32.to_bits()); + let (mut lo, mut hi) = ([iu; 2], [iu; 2]); + for k in 0..2 { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, f32t); + let last = self.s.m.bin(c, Bin::Sub, n, one); + let t = self.s.m.bin(c, Bin::Mul, cs[k], n); + let t = self.s.m.bin(c, Bin::Sub, t, half); + let first = self.unary(27, t); // round down + // The offset word's field (0 without one). + let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t); + let first = self.s.m.bin(c, Bin::Add, first, by); + let next = self.s.m.bin(c, Bin::Add, first, one); + for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] { + let x = self.binary(35, x, zero); // maximum + let x = self.binary(36, x, last); // minimum + *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t); + } + } + 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])]; + for (slot, (x, y)) in g.iter_mut().zip(texels) { + let r = self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &[h, mip, x, y, iu, iu, iu, iu], + ); + *slot = self.s.m.extract(c, r, ch); + read = Some(r); + } + gathered = Some(g); + read.expect("four reads") + } else { + args.extend(&os[..2]); + args.push(self.s.m.i32(dmask.trailing_zeros())); + self.s.op( + c, + "textureGather.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 73, + &args, + ) + } + } + } + } else { + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let mip = if name == "image_load_mip" { + addr_val(self, coords)? + } else if uav { + // Our declarations have four channels. + self.s.flags |= flags::TYPED_UAV_LOADS; + iu + } else { + self.s.m.i32(0) + }; + let mut args = vec![h, mip]; + args.extend(&cs); + args.extend([iu, iu, iu]); + self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &args, + ) + }; + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + let channels: Vec<u32> = if op == 73 { + vec![0, 1, 2, 3] + } else { + (0..4).filter(|ch| dmask >> ch & 1 != 0).collect() + }; + let mut xs = Vec::new(); + for ch in channels { + let x = match gathered { + Some(g) => g[ch as usize], + None => self.s.m.extract(c, r, ch), + }; + xs.push(if *d16 { + // shortcut: d16 results are taken as floats (rounded to + // nearest even); integer formats would keep 16 bits. + let i32t = self.s.t.i32; + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]) + } else { + self.as_int(x) + }); + } + if *d16 { + // Two channels per VGPR, low half first (an odd last high half 0). + let k16 = self.s.m.i32(16); + xs = xs + .chunks(2) + .map(|p| match *p { + [lo, hi] => { + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } + _ => p[0], + }) + .collect(); + } + for (k, x) in xs.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + /// The direction a cube sample's face coordinates stand for: the + /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over + /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the + /// host's cube sampling turns back into the same texel. + // shortcut: the view is taken as a cube, not a cube array (whose face + // operand adds 8 × the slice). + fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] { + let c = self.cur; + let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); + let (two, three) = (k(self, 2.0), k(self, 3.0)); + let u = self.s.m.bin(c, Bin::Mul, s, two); + let u = self.s.m.bin(c, Bin::Sub, u, three); + let v = self.s.m.bin(c, Bin::Mul, t, two); + let v = self.s.m.bin(c, Bin::Sub, v, three); + let z = self.s.m.f32(0x8000_0000); + let (nu, nv) = ( + self.s.m.bin(c, Bin::Sub, z, u), + self.s.m.bin(c, Bin::Sub, z, v), + ); + let (one, mone) = (k(self, 1.0), k(self, -1.0)); + let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32); + // Per face +x, -x, +y, -y, +z, -z. + let table = [ + [one, mone, u, u, u, nu], + [nv, nv, one, mone, nv, nv], + [nu, u, v, nv, one, mone], + ]; + table.map(|row| { + let mut r = row[0]; + for (n, &x) in row.iter().enumerate().skip(1) { + let kn = self.s.m.i32(n as u32); + let is = self.s.m.cmp(c, pred::EQ, f, kn); + r = self.s.m.select(c, is, x, r); + } + r + }) + } + + fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Buffer { + data, + addr, + soffset, + offset, + offen, + idxen, + format, + lds, + tfe, + .. + } = &inst.fields + else { + unreachable!() + }; + let name = inst.name(); + if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" { + // The host has no console buffer cache to invalidate. + return Ok(()); + } + if *lds || *tfe { + return Err("a buffer access to LDS or with tfe"); + } + if format.is_some() && !name.starts_with("tbuffer_load_format_") { + return Err(name); + } + let site = (b, i); + let guard = self.guard(b, i)?; + let c = self.cur; + let store = name.starts_with("buffer_store_"); + // DXIL atomic operations: add, and, or, xor, signed and unsigned + // min and max, exchange; compare-exchange apart. + let atomic = match name.strip_prefix("buffer_atomic_") { + None => None, + Some("add") => Some(0), + Some("and") => Some(1), + Some("or") => Some(2), + Some("xor") => Some(3), + Some("smin") => Some(4), + Some("smax") => Some(5), + Some("umin") => Some(6), + Some("umax") => Some(7), + Some("swap") => Some(8), + Some("cmpswap") => Some(u32::MAX), + Some(_) => return Err(name), + }; + // Byte and 16-bit accesses: bits, and whether a load sign-extends. + let narrow = match name { + "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)), + "buffer_load_sbyte" => Some((8, true)), + "buffer_load_ushort" | "buffer_store_short" => Some((16, false)), + "buffer_load_sshort" => Some((16, true)), + _ => None, + }; + // d16: two 16-bit channels per VGPR, low half first. + let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); + let plain = name.replace("_format_d16_", "_format_"); + let (typed, count) = match plain + .strip_prefix("buffer_load_") + .or(plain.strip_prefix("buffer_store_")) + .or(plain.strip_prefix("tbuffer_load_")) + { + _ if atomic.is_some() || narrow.is_some() => (false, 1), + Some("dword") => (false, 1), + Some("dwordx2") => (false, 2), + Some("dwordx3") => (false, 3), + Some("dwordx4") => (false, 4), + Some("format_x") => (true, 1), + Some("format_xy") => (true, 2), + Some("format_xyz") => (true, 3), + Some("format_xyzw") => (true, 4), + _ => return Err(name), + }; + let Operand::Vector { reg: areg, .. } = *addr else { + return Err("a buffer address"); + }; + let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> { + let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?; + l.i32_of(v) + }; + let index = if *idxen { Some(vaddr(self, 0)?) } else { None }; + let mut off = self.s.m.i32(u32::from(*offset)); + if *offen { + let o = vaddr(self, u8::from(*idxen))?; + off = self.s.m.bin(c, Bin::Add, off, o); + } + if !matches!( + soffset, + Operand::Scalar { code: NULL, .. } | Operand::Const(128) + ) { + let so = self.operand(inst, soffset)?; + off = self.s.m.bin(c, Bin::Add, off, so); + } + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked buffer")?; + let used = self.used_kind(src); + let (base, extra) = self.built_offset(src)?; + if base != 0 { + let b = self.s.m.i32(base); + off = self.s.m.bin(c, Bin::Add, off, b); + } + if let Some(x) = extra { + off = self.s.m.bin(c, Bin::Add, off, x); + } + // A buffer the program picks from the view heap by an index it + // computes: no used-resource entry gives its stride, the host's + // table by heap slot does; the access becomes a raw one at the + // element's byte. (Also tells the host this shader reads such + // buffers.) + let mut index = index; + if let Some(stride) = self.slot_stride(src)? + && let Some(element) = index + && !typed + && used.is_none() + { + let at = self.s.m.bin(c, Bin::Mul, element, stride); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } + // A structured buffer by its used-resource entry's stride: raw + // bytes too. The host makes its buffer views raw (a raw read + // through a structured view gives zeros on NVIDIA), and one kind + // of view can then serve every shader that reads the buffer. + if let (Some(element), Some(u)) = (index, used) + && !typed + && u.kind != ResourceType::Cbv + && u.stride >= 4 + && u.stride.is_multiple_of(4) + { + let k = self.s.m.i32(u.stride); + let at = self.s.m.bin(c, Bin::Mul, element, k); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } + if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed { + // A constant buffer read per lane (a dynamically indexed array). + // shortcut: the console's CBV descriptor is taken to have a 16-byte + // stride, as the vector loads of whole rows suggest. + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let byte = match index { + Some(i) => { + let sixteen = self.s.m.i32(16); + let rows = self.s.m.bin(c, Bin::Mul, i, sixteen); + self.s.m.bin(c, Bin::Add, rows, off) + } + None => off, + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + for k in 0..count { + let four = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, byte, four); + let x = self.cbuffer_dword(h, a); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let iu = self.s.m.undef(self.s.t.i32); + if let Some((bits, signed)) = narrow { + // Below a dword: raw buffers are read and written in dwords on + // 4 bytes, so the dword that holds the value is read and + // shifted, or changed with two atomic operations that touch + // only the value's own bits (other lanes may write the rest of + // the dword at the same time). A 16-bit value at a dword's + // last byte continues in the next dword. + let byte = match index { + None => off, + Some(index) if used.is_some_and(|u| u.stride == 1) => { + self.s.m.bin(c, Bin::Add, index, off) + } + Some(_) => return Err("a byte or 16-bit buffer access by index"), + }; + let h = self.handle(site, src, false, (11 | u, 0))?; + let k3 = self.s.m.i32(3); + let within = self.s.m.bin(c, Bin::And, byte, k3); + let aligned = self.s.m.bin(c, Bin::Sub, byte, within); + let shift = self.s.m.bin(c, Bin::Shl, within, k3); + let four = self.s.m.i32(4); + let next = self.s.m.bin(c, Bin::Add, aligned, four); + let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff }); + let zero = self.s.m.i32(0); + let k8 = self.s.m.i32(8); + let straddles = self.s.m.cmp(c, pred::EQ, within, k3); + if !store { + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let dword = |l: &mut Self, at: V| { + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, at, iu, mask, align], + ); + let f = l.s.m.extract(c, r, 0); + l.as_int(f) + }; + let low = dword(self, aligned); + let mut x = self.s.m.bin(c, Bin::LShr, low, shift); + if bits == 16 { + let high = dword(self, next); + let high = self.s.m.bin(c, Bin::Shl, high, k8); + let high = self.s.m.select(c, straddles, high, zero); + x = self.s.m.bin(c, Bin::Or, x, high); + } + x = self.s.m.bin(c, Bin::And, x, ones); + if signed { + let up = self.s.m.i32(32 - bits); + x = self.s.m.bin(c, Bin::Shl, x, up); + x = self.s.m.bin(c, Bin::AShr, x, up); + } + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + self.write(inst, Reg::V(reg), x, guard); + return Ok(()); + } + let d = data.as_ref().ok_or("buffer store data")?; + let v = self.vgprs(inst, d, 1)?[0]; + let v = self.s.m.bin(c, Bin::And, v, ones); + let all = self.s.m.i32(u32::MAX); + let clear = self.s.m.bin(c, Bin::Shl, ones, shift); + let keep = self.s.m.bin(c, Bin::Xor, clear, all); + let set = self.s.m.bin(c, Bin::Shl, v, shift); + let keep_next = self.s.m.i32(0xffff_ff00); + let set_next = self.s.m.bin(c, Bin::LShr, v, k8); + let (and, or) = (self.s.m.i32(1), self.s.m.i32(2)); + let i32t = self.s.t.i32; + let at = self.begin_guarded(guard); + for (op, x) in [(and, keep), (or, set)] { + let args = [h, op, aligned, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + if bits == 16 { + let second = self.begin_guarded(Some(straddles)); + for (op, x) in [(and, keep_next), (or, set_next)] { + let args = [h, op, next, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + self.end_guarded(second, &[]); + } + self.end_guarded(at, &[]); + return Ok(()); + } + if let Some(op) = atomic { + let d = data.as_ref().ok_or("buffer atomic data")?; + let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; + let (h, coords) = match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu]) + } + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let h = self.handle(site, src, false, (12 | u, stride))?; + (h, [index, off, iu]) + } + None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]), + }; + let Operand::Vector { reg, .. } = *d else { + return Err("buffer atomic data"); + }; + let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc); + let old = match inst.read(Reg::V(reg)) { + Some(v) if returns => self.i32_of(v)?, + _ => self.s.m.i32(0), + }; + let at = self.begin_guarded(guard); + let i32t = self.s.t.i32; + let r = if op == u32::MAX { + // cmpswap: data is (new, compare). + let mut args = vec![h]; + args.extend(coords); + args.extend([vals[1], vals[0]]); + self.s.op( + self.cur, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ) + } else { + let mut args = vec![h, self.s.m.i32(op)]; + args.extend(coords); + args.push(vals[0]); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + }; + let r = self.end_guarded(at, &[(r, old)])[0]; + if returns { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } + if store { + let regs = if d16 { count.div_ceil(2) } else { count }; + let mut vals = + self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; + if d16 { + // shortcut: d16 data is taken as f16 (integer formats would + // keep 16 bits), widened for the 32-bit float store. + let mut wide = Vec::new(); + for k in 0..count { + let mut x = vals[(k / 2) as usize]; + if k % 2 == 1 { + 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]); + wide.push(self.as_int(f)); + } + vals = wide; + } + let mut args = Vec::new(); + let (op, name) = if typed { + // shortcut: typed stores are taken to write all four channels + // of a float format. + if count != 4 || *offen || *offset != 0 { + return Err("a typed buffer store of some channels or at an offset"); + } + args.push(self.handle(site, src, false, (10 | u, 0x409))?); + args.extend([index.unwrap_or(self.s.m.i32(0)), iu]); + for x in vals { + args.push(self.as_float(x)); + } + (69, "bufferStore.f32") + } else { + match index { + // A raw buffer (stride 1) written by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([byte, iu]); + } + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + args.push(self.handle(site, src, false, (12 | u, stride))?); + args.extend([index, off]); + } + None => { + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([off, iu]); + } + } + args.extend(&vals); + args.resize(3 + 4, iu); + (140, "rawBufferStore.i32") + }; + args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 })); + if !typed { + args.push(self.s.m.i32(4)); + } + let at = self.begin_guarded(guard); + let void = self.s.t.void; + self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args); + self.end_guarded(at, &[]); + return Ok(()); + } + if let Some(f) = *format { + if index.is_some() { + return Err("a typed-format load by index"); + } + let h = self.handle(site, src, false, (11 | u, 0))?; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let r = if typed { + if *offen || matches!(off, V::Inst(_)) || *offset != 0 { + return Err("a typed buffer load at an offset"); + } + if uav { + self.s.flags |= flags::TYPED_UAV_LOADS; + } + let h = self.handle(site, src, false, (10 | u, 0x409))?; + let index = index.unwrap_or(self.s.m.i32(0)); + self.s.op( + c, + "bufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 68, + &[h, index, iu], + ) + } else { + let mask = self.s.m.i8((1u8 << count) - 1); + let align = self.s.m.i32(4); + match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + let h = self.handle(site, src, false, (11 | u, 0))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ) + } + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let h = self.handle(site, src, false, (12 | u, stride))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, index, off, mask, align], + ) + } + None => { + let h = self.handle(site, src, false, (11 | u, 0))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, off, iu, mask, align], + ) + } + } + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + if d16 { + // Two f16 channels per VGPR (an odd last high half 0). + let k16 = self.s.m.i32(16); + let i32t = self.s.t.i32; + for k in 0..count.div_ceil(2) { + let mut x = None; + for ch in (2 * k..(2 * k + 2).min(count)).rev() { + let f = self.s.m.extract(c, r, ch); + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + x = Some(match x { + Some(hi) => { + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, h, hi) + } + None => h, + }); + } + self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard); + } + return Ok(()); + } + for k in 0..count { + let x = self.s.m.extract(c, r, k); + let x = self.as_int(x); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + fn export(&mut self, b: usize, i: usize) -> Result<(), Why> { + let e = *self + .exports + .get(&(b, i)) + .ok_or("an export I/O raising did not see")?; + if e.compressed { + return Err("a compressed export"); + } + let guard = self.guard(b, i)?; + let mesh = self.s.mesh.is_some(); + let c = self.cur; + if let Some(g) = guard + && !mesh + { + if !(e.done && self.s.pixel) { + return Err("a conditional export"); + } + let t = self.s.m.bool(true); + let kill = self.s.m.bin(c, Bin::Xor, g, t); + self.s + .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); + } + if mesh && e.target == Target::Primitive { + return self.emit_indices(e, guard); + } + let param_row = |usage: Usage, row: u8| match usage { + // The 2020 compiler leaves a mesh program's first entry zeroed + // (usage "position"): its row is the one no other entry names. + Usage::Other(0) if mesh => self.unnamed_row(), + _ => Some(row), + }; + // (output element, channel) per exported channel; per-primitive + // outputs are elements of `prims`. + let mut stores = Vec::new(); + let primitive = matches!(e.target, Target::PrimitiveParam { .. }); + let outputs = if primitive { + &self.s.prims + } else { + &self.s.outputs + }; + let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind); + // 16-bit vertex outputs: the halves each dword carries, as (output + // element, channel, high half) per channel. + let halves = match e.target { + Target::Param { usage, row } => { + param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h))) + } + _ => None, + }; + if let Some((row, (pack2, _))) = halves { + let packs: Vec<(u8, Option<u8>)> = self + .half_outputs + .iter() + .filter(|(_, h)| h.0) + .map(|(&r, h)| (r, h.1)) + .collect(); + for ch in 0..4u8 { + let Some(value) = e.values[usize::from(ch)] else { + continue; + }; + for high in [false, true] { + let h = 2 * ch + u8::from(high); + let src = if pack2 { + packed_half(outputs, &packs, row, h) + } else { + (!high).then_some((row, ch)) + }; + let found = src.and_then(|(r, c)| { + outputs.iter().position(|o| { + o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols + }) + }); + if let Some(id) = found { + let col = src.expect("found").1 - outputs[id].col; + stores.push((id, col, value, Some(high))); + } + } + } + } + for ch in 0..4u8 { + let Some(value) = e.values[usize::from(ch)] else { + continue; + }; + if halves.is_some() { + break; + } + let found = match e.target { + Target::Color(n) => outputs + .iter() + .position(|o| o.kind == 16 && o.row == Some(u32::from(n))) + .map(|id| (id, ch)), + Target::Position(0) => by_kind(3).map(|id| (id, ch)), + Target::Depth => match ch { + 0 => by_kind(17) + .or(by_kind(18)) + .or(by_kind(19)) + .map(|id| (id, 0)), + 1 => by_kind(20).map(|id| (id, 0)), + 2 => by_kind(14).map(|id| (id, 0)), + _ => None, + }, + Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => { + let row = param_row(usage, row); + outputs + .iter() + .position(|o| { + row.is_some_and(|r| o.row == Some(u32::from(r))) + && ch >= o.col + && ch < o.col + o.cols + }) + .map(|id| (id, ch - outputs[id].col)) + } + Target::Null | Target::Unread => None, + Target::Position(n @ 1..=2) => { + // shortcut: without the misc vector (point size, render + // target or viewport index) pos1 and pos2 carry the clip + // then cull distances, in semantic order. + if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) { + return Err("render-target or viewport index exports"); + } + let mut dists: Vec<usize> = (0..outputs.len()) + .filter(|&i| matches!(outputs[i].kind, 6 | 7)) + .collect(); + dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index)); + let flat: Vec<(usize, u8)> = dists + .iter() + .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c))) + .collect(); + // Channels past the distances the signature declares are + // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`). + let k = usize::from(n - 1) * 4 + usize::from(ch); + flat.get(k).copied() + } + Target::Position(_) => return Err("clip, cull or point-size exports"), + Target::Primitive => return Err("a primitive export"), + }; + if let Some((id, col)) = found { + stores.push((id, col, value, None)); + } + } + fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> { + if primitive { + &mut l.s.prims + } else { + &mut l.s.outputs + } + } + if stores + .iter() + .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half) + { + return Err("a 16-bit output the stage data does not mark"); + } + // A mesh lane writes its own vertex or primitive, where it exports. + let at = if mesh { + let flat = self.mesh_thread(); + let limit = if let Some(m) = self.s.mesh { + if primitive { + m.max_primitives + } else { + m.max_vertices + } + } else { + 0 + }; + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + let mesh_guard = if limit > 0 && threads > limit { + let lim = self.s.m.i32(limit); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + }; + self.begin_guarded(mesh_guard) + } else { + None + }; + let (name, opcode) = match (mesh, primitive) { + (false, _) => ("storeOutput", 5), + (true, false) => ("storeVertexOutput", 171), + (true, true) => ("storePrimitiveOutput", 172), + }; + for (id, col, value, half) in stores { + let mut x = self.i32_of(value)?; + if let Some(high) = half { + // An f16 half, declared a 32-bit float on the host. + let c = self.cur; + 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); + } + let el = &mut elements(self, primitive)[id]; + el.usage |= 1 << col; + let (suffix, x) = match el.comp { + 9 if half.is_some() => (".f32", self.as_float(x)), + 9 => { + let f = match self.floats.get(&value) { + Some(&f) => f, + None => self.as_float(x), + }; + (".f32", f) + } + _ => (".i32", x), + }; + let mut args = vec![ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + x, + ]; + if mesh { + args.push(self.mesh_thread()); + } + let void = self.s.t.void; + self.s.op( + self.cur, + &format!("{name}{suffix}"), + Attr::NoUnwind, + void, + opcode, + &args, + ); + } + self.end_guarded(at, &[]); + Ok(()) + } + + /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all + /// indices 0: no area). + fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> { + let v = e.values[0].ok_or("a primitive export without its indices")?; + let x = self.i32_of(v)?; + let flat = self.mesh_thread(); + let guard = if let Some(mesh) = self.s.mesh { + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + if threads > mesh.max_primitives { + let p = self.s.m.i32(mesh.max_primitives); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + } + } else { + guard + }; + let at = self.begin_guarded(guard); + let c = self.cur; + let z = self.s.m.i32(0); + let mut culled = self.s.m.cmp(c, pred::SLT, x, z); + // A primitive that names a vertex past the declared count, or one + // no lane writes (lane n writes vertex n alone), is culled too: the + // host would read a vertex nothing set, at any position. + let written = self.s.mesh.map(|m| { + m.max_vertices + .min(self.s.threads.map_or(u32::MAX, |t| t[0])) + }); + let mut indices = [z; 3]; + for (k, slot) in indices.iter_mut().enumerate() { + let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF)); + let i = self.s.m.bin(c, Bin::LShr, x, shift); + let i = self.s.m.bin(c, Bin::And, i, mask); + if let Some(n) = written { + let n = self.s.m.i32(n); + let past = self.s.m.cmp(c, pred::IUGE, i, n); + culled = self.s.m.bin(c, Bin::Or, culled, past); + } + *slot = i; + } + let mut args = vec![flat]; + for i in indices { + args.push(self.s.m.select(c, culled, z, i)); + } + let void = self.s.t.void; + self.s + .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args); + self.end_guarded(at, &[]); + Ok(()) + } + + /// The per-vertex arbitrary row no mesh output entry names but one + /// (the 2020 compiler's zeroed entry). + fn unnamed_row(&self) -> Option<u8> { + let StageIo::Ms(ms) = &self.x.native.io else { + return None; + }; + let named = |r: u32| { + ms.outputs + .iter() + .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) + }; + let free: std::collections::BTreeSet<u32> = self + .s + .outputs + .iter() + .filter(|o| o.kind == 0) + .filter_map(|o| o.row) + .filter(|&r| !named(r)) + .collect(); + match free.into_iter().collect::<Vec<_>>()[..] { + [r] => u8::try_from(r).ok(), + _ => 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<bool> = std::sync::OnceLock::new(); + let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some()); + let mut work: Vec<Value> = 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 +/// pull model). +fn interp_mode(kind: Barycentric) -> Option<u8> { + Some(match kind { + Barycentric::PerspectiveCenter => 2, + Barycentric::PerspectiveCentroid => 3, + Barycentric::PerspectiveSample => 6, + Barycentric::LinearCenter => 4, + Barycentric::LinearCentroid => 5, + Barycentric::LinearSample => 7, + Barycentric::PerspectivePullModel => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; + use crate::{io, ir, resource, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + + #[test] + fn packed_pixel_inputs_find_their_second_row() { + use super::super::container::SigElement; + use super::half_input_partners; + use crate::native::{PsInput, Usage}; + let entry = |row, row2, pack2| PsInput { + usage: Usage::Generic, + row, + mask: 0xF, + attr: row, + flat: false, + fp16: true, + pack2, + row2, + }; + let element = |row| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: true, + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its + // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. + let io = StageIo::Ps { + inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); + let p = half_input_partners(&io, &sig); + assert_eq!(p.get(&0), Some(&1)); + assert_eq!(p.get(&3), Some(&4)); + assert_eq!(p.get(&5), None); + } + + /// The packed pedestrian layouts of 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<u8> = 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<RootParam>, + used: Vec<UsedResource>, + ) -> Result<Lowered, crate::ShaderError> { + lower_wave(words, layout, used, false) + } + + /// [`lower_with`] in wave64 if `wave64`. + fn lower_wave( + words: &[u32], + layout: Vec<RootParam>, + used: Vec<UsedResource>, + wave64: bool, + ) -> Result<Lowered, crate::ShaderError> { + let code: Vec<u8> = 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<u8> = 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<RootParam>, Vec<UsedResource>) { + 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<RootParam>, Vec<UsedResource>) { + 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<u32> = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } + } + + #[test] + #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] + fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); + } + + #[test] + fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); + } + + #[test] + fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); + } + + /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as + /// `legacyF16ToF32` widens it. + fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } + } + + #[test] + fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs new file mode 100644 index 000000000..3a7646ccd --- /dev/null +++ b/crates/victory-shader/src/emit/mod.rs @@ -0,0 +1,1743 @@ +//! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute +//! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts. +//! Compute shaders keep the console's thread-group size; one that depends +//! on the lane layout (cross-lane operations) declares the console's wave +//! size (`WaveSize`), so the host device must support it. +//! +//! What the host binds for a translated shader ([`HostShader`]): +//! +//! * **User data** at `b0, space 0` (32-bit root constants or a constant +//! buffer, per stage): dword `index` holds a root parameter's value, as +//! [`UserData`] lists. A root-constant dword is the constant. A +//! descriptor table is the byte offset of its first descriptor in its +//! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16 +//! for sampler tables (the console's descriptor sizes; the code adds +//! offsets in those units). The heap bases of dynamic resources are 0 +//! and not listed. +//! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and +//! `SamplerDescriptorHeap[]`, at the index the console address gives, so +//! the host heaps keep the title's descriptor order. The root signature +//! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and +//! `SAMPLER_HEAP_DIRECTLY_INDEXED`. +//! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the +//! position in [`HostShader::samplers`] (the console sampler words) and +//! [`HostShader::static_samplers`] (the same decoded into a D3D12 static +//! sampler description). Comparison sampling (added 2026-11-23): an +//! immediate sampler it uses has a comparison filter there (bit 0x80); +//! a heap sampler it uses must be a comparison sampler on the host. +//! * **Root CBVs and root SRVs** (raw buffers) as root descriptors +//! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter +//! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the +//! address the title sets is the buffer's. +//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI'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 +//! instruction, so the translation reads raw bytes and converts them +//! itself. Their descriptors are built around a root SRV (stride 1, no +//! record limit): the host binds the root SRV `t<slot>` above with the +//! address the title sets, nothing more. The vertex index, the stride +//! and the attribute offset are the shader's own arithmetic on data in +//! that buffer (per-stream headers), not descriptor fields. +//! * **Buffer views in the heap** are declared by how the shader reads +//! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and +//! typed-format loads without an index; structured with the used-resource +//! entry's stride when indexed; typed with four 32-bit float channels for +//! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at +//! that index must be of that kind and start at the console descriptor's +//! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the +//! title's view description says. Typed-format loads from heap +//! descriptors (1,024 world compute programs, ray-tracing material +//! resolves) read raw views this way. +//! +//! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT +//! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter +//! require SM 6.6 atomic support on typed and descriptor-heap resources. +//! +//! Entry points: [`translate`] (container bytes as the title passes them +//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the +//! earlier stages already run). The root constants of each stage must +//! cover [`HostShader::user_data_dwords`]. Stability: these types and the +//! binding scheme are what pipeline creation builds on; changes are +//! announced. +//! * **Signatures** as the console container has them (same semantics, +//! registers and masks), so the input layout and stage linking are the +//! title's; pixel outputs are plain 32-bit values. +//! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and +//! descriptors as above (the root constants visible to the mesh stage); +//! the pipeline is a mesh pipeline (pipeline-state stream, no input +//! layout) with the title's pixel shader. The thread group is the +//! console's in lanes (`[numthreads]` in the DXIL), the vertex and +//! primitive maxima its own, triangles only, no wave size required. The +//! console numbers groups in x only: the draw path passes the title's +//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are +//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the +//! console never exports them). +//! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a +//! rectangle from three vertices; the host has no such topology. A +//! pipeline the title makes for rectangles (topology type 19) gets a +//! geometry shader of ours between the translated vertex and pixel +//! shaders and draws triangle lists with the title's own vertex counts. +//! It binds nothing. + +mod bitcode; +mod container; +#[cfg(all(test, windows))] +mod diff_tests; +#[cfg(all(test, windows))] +mod intersect_tests; +#[cfg(all(windows, any(test, feature = "host")))] +pub mod host; +mod lower; +mod own_bits; +mod rect; +mod sampler; +mod shader; +mod threading; +#[cfg(windows)] +pub mod validator; +#[cfg(all(test, windows))] +mod valu_tests; +#[cfg(all(test, windows))] +mod waterfall_tests; +#[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 rect::rect_list_gs; +pub use shader::{ + MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + set_view_heap_limit, +}; + +/// 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 +/// per entry into the loop: [`DEFAULT_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 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 { + static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| { + if cfg!(feature = "diagnostics") { + parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref()) + } else { + lower::LOOP_LIMIT + } + }) +} + +/// 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 +/// reaches is undefined on the host, and NVIDIA's wait is for every +/// thread: the group stands until Windows resets the card. (The console's +/// barrier is the wave's, whatever lanes are live, and a wave that ended +/// is not waited for.) `VICTORY_GROUP_SYNC`: +/// - unset or `2`: every barrier waits, as before. +/// - `1`: the title's `s_barrier` waits only in a block every lane runs, +/// in a program no lane can be cut out of at the iteration limit. +/// - `0`: no barrier waits, neither the title's nor the ones the +/// translation adds (wave64 programs in two host waves exchange through +/// them, so such programs compute wrong values). For one run that tells +/// whether a barrier is what stops the card: with it no run can stand in +/// a barrier. +/// +/// Part of the translation: the shader cache keys on it (`victory-gpu`'s +/// does). +pub fn group_sync() -> u8 { + static MODE: std::sync::OnceLock<u8> = 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, + }) +} + +/// 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<u32> = 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 { + 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(), + }); + match parsed { + Some(n) if n > 0 => n, + _ => lower::LOOP_LIMIT, + } +} + +/// A translated shader and what the host binds for it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostShader { + pub stage: HwStage, + /// The DXIL container, hashed as D3D12 expects. + pub dxil: Vec<u8>, + /// The user-data dwords the shader reads. + pub user_data: Vec<UserData>, + /// Immediate samplers: the four sampler words of `s<n>`. + pub samplers: Vec<[u32; 4]>, + /// The same samplers decoded, `s<n>` at position n: the static sampler + /// descriptions the host's root signature declares. + pub static_samplers: Vec<StaticSampler>, + /// Root CBVs the shader reads: root parameter indices, each bound as + /// `b<index>` in [`ROOT_CBV_SPACE`]. + pub root_cbvs: Vec<u8>, + /// Root SRVs (raw buffers) the shader reads: `t<index>` in + /// [`ROOT_CBV_SPACE`]. + pub root_srvs: Vec<u8>, + /// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in + /// [`ROOT_CBV_SPACE`]. + pub root_uavs: Vec<u8>, + /// Heap descriptors that can be selected from root state at bind time. + pub root_indexed_views: Vec<crate::resource::RootIndexedView>, +} + +impl HostShader { + /// Size of the user-data buffer the shader declares, in dwords (a + /// multiple of 4; 0 when it reads none). Root constants must cover it. + pub fn user_data_dwords(&self) -> u32 { + let n = self + .user_data + .iter() + .map(|u| u.index + 1) + .max() + .unwrap_or(0); + n.next_multiple_of(4) + } +} + +/// One dword of user data and the root parameter that fills it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UserData { + /// Dword in the user-data buffer (the console's user-data index). + pub index: u32, + /// Root parameter index in the title's root signature. + pub slot: u8, + /// `Constants` or `Table` (see the module notes for the value). + pub root: RootType, + /// Dword within the parameter. + pub dword: u32, +} + +/// Translates the vertex, pixel, compute or mesh program of a console +/// shader container. +pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> { + let c = Container::parse(container)?; + let dxil = c + .part(FourCC::DXIL) + .ok_or(ShaderError::Malformed("no DXIL part"))?; + let native = crate::native_programs(dxil.data)? + .into_iter() + .find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms + ) + }) + .ok_or(ShaderError::Unsupported { + offset: 0, + what: "a container without a vertex, pixel, compute or mesh program", + })?; + let p = crate::spill::build(&native)?; + // Structurisation first: tracing per-lane descriptors needs it (its + // failure is reported after the earlier stages'). + let st = structure::structure(&p); + let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?; + let io = io::raise(&p, &native)?; + let st = st?; + emit(&c, &native, &p, &st, &io, &res) +} + +/// Emits a program whose earlier stages already ran. +pub fn emit( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<HostShader, ShaderError> { + // (what an earlier program's lowering on this thread left behind) + lower::take_needs(); + 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 + // ([`ir::without_early_outs`]), which is what usually keeps the whole + // body from being a block every lane runs. + let stuck = match &original { + Ok((_, wave)) => *wave == Some(64), + Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what), + Err(_) => false, + }; + // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave + // on its own) + let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE); + if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 { + let why = std::env::var_os("VICTORY_WAVE_WHY").is_some(); + let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| { + if why { + match r { + Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"), + Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"), + } + } + }; + let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64)); + // Each host wave as a wave of its own (`lower::with_local_waves`), + // for programs still stopped where not every lane runs. + let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0"); + // Where the wave operations are the allocation idiom + // ([`lower::wave_local`]) that is exact. Other programs are taken + // the same way last of all, each half-wave giving its own results + // (approximate: a tile-wide result becomes two half-tile ones); + // `VICTORY_WAVE_LOCAL=idiom` refuses those instead. + let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom"); + let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) { + Ok(()) => true, + Err((offset, what)) => { + if why { + eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}"); + } + false + } + }; + // The program in two other forms: without its early-outs, and + // without any branch that only skips code no lane is left for. + let form = |p: Option<ir::Program>| { + p.and_then(|p| { + let st = structure::structure(&p).ok()?; + let io = io::raise(&p, native).ok()?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?; + Some((p, st, io, res)) + }) + }; + let forms = [ + ("without early-outs", form(ir::without_early_outs(p))), + ("without skips", form(ir::without_skips(p, false))), + ]; + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let again = emit_program(c, native, p, st, io, res); + report(name, &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + // Off unless asked for (`VICTORY_WAVE_WIDE=1`), for a console wave run as two host + // waves: this form puts group barriers inside branches and loops, and runs 121-124 + // lost the card in a submission of two programs that had just moved to it + // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which + // has no barrier, stays on. + let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1"); + // exact first: each host wave on its own where that is exact (the idiom, every + // form; no barriers), then the other exact forms; then approximate + for exact in [true, false] { + if !exact { + // Before anything approximate, the exact forms that cost group barriers. + // Every skip left out that the code after it cannot see + // ([`ir::without_skips`], `deep`): most of the body is then code every + // 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 }; + if let Some((p, st, io, res)) = &deep { + let again = emit_program(c, native, p, st, io, res); + report("without skips, scalars followed", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + // Still stopped where not every lane runs: the per-lane branches around + // those places taken as the console takes them, by the whole wave at once + // ([`widen`]), at two group barriers per such branch. + if wide_on { + let bases = [ + deep.as_ref().map(|f| &f.0), + forms[1].1.as_ref().map(|f| &f.0), + forms[0].1.as_ref().map(|f| &f.0), + Some(p), + ]; + if let Some(base) = bases.into_iter().flatten().next() { + let again = widen(c, native, base, why); + report("wave-wide branches", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + if strict { + break; + } + } + if !local_on || exact_only { + continue; + } + for (name, f) in &forms { + if let Some((p, st, io, res)) = f + && idiom(p, st) == exact + { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if idiom(p, st) == exact { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if local_on && !exact_only { + // Last: every mask and lane read per host wave. + if !strict { + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + 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); + } + } + } + } + // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane + // trace programs): right once the wave takes that skip together ([`widen`]; the + // lowering has named the skipped blocks). + let original = match original { + Err(ShaderError::Unsupported { what, .. }) + if native.stage == HwStage::Cs + && what == lower::LANE_MASK + && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") => + { + 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), + } + } + other => other, + }; + let original = original.map(|(shader, _)| shader); + // Retry unsupported programs only. Threading can separate an unknown + // register value from its apparent use on a mutually exclusive path. + if !matches!(original, Err(ShaderError::Unsupported { .. })) { + return original; + } + let edges = threading::constant_edges(p, st); + if edges.is_empty() { + return original; + } + let p = ir::thread_edges(p, &edges)?; + let st = structure::structure(&p)?; + let io = io::raise(&p, native)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) +} + +/// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane +/// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the +/// lowering names the blocks where the two host waves must meet and could not +/// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until +/// it translates or a branch cannot be widened. Only where a thread group is one console +/// wave: with several, the waves of a group would decide differently and a barrier inside +/// such a branch would wait for threads that never come. +fn widen( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + why: bool, +) -> Result<(HostShader, Option<u32>), ShaderError> { + const NOT: ShaderError = ShaderError::Unsupported { + offset: 0, + what: "wave-wide branches in a thread group of several console waves", + }; + match native.io { + // (a program whose waves are the host's meets no one: no barrier, any group) + crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {} + crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64 => {} + crate::native::StageIo::Cs(cs) => { + if why { + eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads); + } + return Err(NOT); + } + _ => return Err(NOT), + } + let mut wide = std::collections::HashSet::new(); + loop { + let st = structure::structure_wide(p, &wide)?; + let io = io::raise(p, native)?; + let res = resource::track(p, &native.layout, native.stage, Some(&st))?; + lower::take_needs(); + let r = emit_program(c, native, p, &st, &io, &res); + let 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) + let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. }) + if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty()) + || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); + if !stuck { + if why { + eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); + } + return r; + } + let more: Vec<usize> = lower::branches_around(&st, &needs) + .unwrap_or_default() + .into_iter() + .filter(|b| !wide.contains(b)) + .collect(); + if more.is_empty() { + if why { + eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len()); + } + return r; + } + wide.extend(more); + } +} + +/// The translated program, and the wave size it requires of the host. +fn emit_program( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<(HostShader, Option<u32>), ShaderError> { + let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> { + match c.part(fourcc) { + Some(part) => signature(part.data), + None => Ok(Vec::new()), + } + }; + let pixel = native.stage == HwStage::Ps; + let mut inputs = sig(FourCC::ISG1)?; + let mut outputs = sig(FourCC::OSG1)?; + // 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 { + 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). + (13, _) => 1, + // Until a read says which mode (`lower`). + (28, _) => 2, + (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) { + e.interp = 5; + } + } + // Per-primitive outputs are constant. The console never exports a + // primitive id or cull flag a mesh shader writes (it culls with the + // primitive export), so those rows are left out. + let mut prims = sig(FourCC::PSG1)?; + prims.retain(|e| !matches!(e.kind, 10 | 30)); + for e in &mut prims { + e.interp = 1; + } + // A mesh group's id arrives multiplied by max(threads, vertices, + // 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). + let mesh_stride = match &native.io { + crate::native::StageIo::Ms(ms) => { + let psv = c.part(FourCC::PSV0).map(|p| p.data); + let threads = psv + .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48)) + .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok()); + threads.map_or(ms.threads, |t| { + t.max(ms.max_vertices).max(ms.max_primitives) + }) + } + _ => 0, + }; + let l = lower::lower(&lower::Parts { + native, + p, + st, + io, + res, + inputs, + outputs, + prims, + mesh_stride, + })?; + let wave_size = l.wave_size; + let shader = HostShader { + stage: native.stage, + dxil: l.dxil, + user_data: l.user_data, + 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, + root_uavs: l.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + }; + Ok((shader, wave_size)) +} + +/// The rows of an `ISG1`/`OSG1` part. +fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> { + use crate::dxbc::u32_at; + let count = u32_at(part, 0)? as usize; + let base = u32_at(part, 4)? as usize; + let mut out = Vec::with_capacity(count); + for i in 0..count { + let at = base + 32 * i; + let name_at = u32_at(part, at + 4)? as usize; + let name = part + .get(name_at..) + .and_then(|s| s.split(|&b| b == 0).next()) + .ok_or(ShaderError::Malformed("signature name out of bounds"))?; + let mask = *part + .get(at + 24) + .ok_or(ShaderError::Malformed("truncated"))?; + if u32_at(part, at + 28)? != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a minimum-precision signature element", + }); + } + if u32_at(part, at)? != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a signature element of another stream", + }); + } + let kind = match u32_at(part, at + 12)? { + 0 => 0, + 1 => 3, + 2 => 6, + 3 => 7, + 4 => 4, + 5 => 5, + 6 => 1, + 7 => 10, + 8 => 2, + 9 => 13, + 10 => 12, + 64 => 16, + 65 => 17, + 66 => 14, + 67 => 19, + 68 => 18, + 69 => 20, + 70 => 15, + 23 => 28, // barycentrics + 25 => 30, // cull primitive + _ => { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a system value in the signature", + }); + } + }; + // 16-bit elements are declared 32-bit; reading or writing one + // converts (16-bit values travel packed on the console). + let raw = u32_at(part, at + 16)?; + let comp = match (kind, raw) { + // DXIL declares the front face a uint (the validator insists). + (13, _) => 5, + (_, 1 | 4) => 5, + (_, 2 | 5) => 4, + (_, 3 | 6) => 9, + (_, c) => { + return Err(ShaderError::Unsupported { + offset: 0, + what: match c { + 0 => "a signature element of unknown type", + _ => "a 64-bit signature element", + }, + }); + } + }; + let register = u32_at(part, at + 20)?; + out.push(container::SigElement { + name: String::from_utf8_lossy(name).into_owned(), + index: u32_at(part, at + 8)?, + kind, + comp, + interp: 0, + row: (register != u32::MAX).then_some(register), + col: mask.trailing_zeros().min(3) as u8, + cols: mask.count_ones().max(1) as u8, + usage: 0, + half: (4..=6).contains(&raw), + }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::bitcode::Attr; + 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); + assert_eq!(parse_loop_limit(Some("4096")), 4096); + assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096); + assert_eq!(parse_loop_limit(Some("1")), 1); + for bad in ["", "0", "-5", "lots", "0x", "4294967296"] { + assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}"); + } + } + use super::container::SigElement; + use super::shader::Shader; + use super::*; + use crate::native::{ComputeIo, StageIo}; + + /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). + /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose + /// output signature has SV_StencilRef, and the feature bit + /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks + /// both against the module. + #[test] + fn a_stencil_export_declares_the_stencil_ref_feature() { + let words = [ + 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 + 0x7E02_0285, // v_mov_b32 v1, 5 + 0xF800_1883, + 0x0000_0100, // exp mrtz v0, v1, off, off done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, comp| SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row: None, + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let osg1 = + container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + 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 = io::raise(&p, &native).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks the flags against the module. + #[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(); + } + let host = Container::parse(&out.dxil).unwrap(); + let sfi0 = host.part(FourCC::SFI0).unwrap().data; + let features = u64::from_le_bytes(sfi0.try_into().unwrap()); + assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); + } + + /// A wave64 compute program that writes only EXEC's high dword + /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was + /// opaque and keyed by the unchanged low dword, so building its lane bit + /// needed the mask's own value: lowering recursed until the stack + /// overflowed, which takes the whole process down (found by + /// random-input testing). Now that low dword, seen with two high + /// dwords, has no mask, and the instruction fails like any other that + /// cannot be expressed: its result is missing, and only a side effect + /// that uses it would stop the translation. + #[test] + fn an_exec_high_write_does_not_overflow_the_stack() { + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm + let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + if let Err(e) = emit(&c, &native, &p, &st, &io, &res) { + assert!(e.to_string().contains("its own value"), "{e}"); + } + } + + /// A wave64 compute program: `body`, then a store of v1 to a UAV. + fn stores_v1(body: &[u32]) -> Result<(), ShaderError> { + use crate::native::RootParam; + use crate::{ResourceType, RootType, UsedResource}; + // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0 + let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000]; + words.extend_from_slice(body); + // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen; + // s_endpgm + words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 4, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2, + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + emit(&c, &native, &p, &st, &io, &res).map(|_| ()) + } + + /// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi` + /// or `exec_hi`): lanes 32-63 took the mask the low dword was first + /// written with (the compare's, EXEC's on entry). Now the store refuses; + /// without the write it translates. + #[test] + fn a_mask_whose_high_dword_is_rewritten_is_refused() { + // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc + let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480]; + // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc. + let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480]; + // v_mov_b32 v1, 7 + let mov = [0x7E02_0287]; + for body in [&select[..], &carry, &mov] { + stores_v1(body).unwrap(); + } + // s_mov_b32 vcc_hi, 0 after the compare. + let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480]; + let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480]; + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after + // s_mov_b64 s[2:3], exec. + let exec_hi = [0xBEFF_0380, 0x7E02_0287]; + let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287]; + for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] { + assert!(stores_v1(body).is_err(), "{body:x?}"); + } + } + + /// `ds_bpermute_b32` stores nothing: each lane reads the lane its address + /// names. It stopped as "LDS the program does not allocate" (sticky lips) + /// or "an LDS operation" (the checkerboard shadow masks). + #[test] + fn a_backward_permute_reads_the_lane_its_address_names() { + // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2 + stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap(); + } + + /// 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, so the join is no + /// per-lane phi: lowering refuses it. + #[test] + 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 + 0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc + 0xBF88_0001, // s_cbranch_execz 1 + 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ]; + 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. + #[cfg(windows)] + fn constant_color() -> Vec<u8> { + let mut s = 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: 15, + half: false, + }); + let b = s.entry; + for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() { + let args = [ + s.m.i32(0), + s.m.i32(0), + s.m.i8(c as u8), + s.m.f32(v.to_bits()), + ]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, super::bitcode::Term::Ret); + s.finish() + } + + #[test] + #[cfg(windows)] + fn stub_pipeline_is_created() { + let Ok(host) = super::host::Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let ps = super::HostShader { + stage: crate::HwStage::Ps, + dxil: constant_color(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }; + let file = |var: &str, stage| { + std::env::var(var).ok().map(|p| super::HostShader { + stage, + dxil: std::fs::read(p).unwrap(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }) + }; + let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); + let vs = file("VICTORY_REF_VS", crate::HwStage::Vs) + .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap()); + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut vs.dxil.clone()).unwrap(); + } + host.pipeline(&vs, &ps).unwrap(); + // 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.) + let mut wrong = ps.dxil[4..20].to_vec(); + wrong[0] ^= 1; + for digest in [&[0u8; 16][..], &wrong] { + let mut other = ps.clone(); + other.dxil[4..20].copy_from_slice(digest); + assert!( + host.pipeline(&vs, &other).is_err(), + "digest {digest:02x?} accepted" + ); + } + } + + #[test] + #[cfg(windows)] + fn constant_color_validates() { + let mut c = constant_color(); + let path = super::validator::Validator::default_path(); + let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else { + eprintln!("no dxil.dll; skipped"); + return; + }; + let ours = c[4..20].to_vec(); + v.validate(&mut c).unwrap(); + assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); + } + + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE + /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: + /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) + /// whenever an input is interpolated per sample. + #[test] + fn sample_interpolated_inputs_set_psv_sample_frequency() { + let words = [ + 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + 0xBF81_0000, + ]; + let psv_of = |input_addr: u32| { + 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: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, usage| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage, + half: false, + }; + let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true); + let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false); + let bytes = + crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (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(); + let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks PSV0 against the module. + #[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(); + } + let host = super::Container::parse(&out.dxil).unwrap(); + host.part(super::FourCC::PSV0).unwrap().data.to_vec() + }; + // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}. + let center = psv_of(1 << 1); + assert_eq!(center[4 + 1], 0, "center interpolation is per pixel"); + let sample = psv_of(1 << 0); + assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency"); + } + + /// 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 + /// checks (tests, debug) any read below an element that starts at z or + /// w panicked, whichever row it was in (found by random-input testing). + #[test] + fn reading_a_channel_below_an_input_element_does_not_underflow() { + // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm + let words = [0xC80E_0202u32, 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: 0b1000, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let w_only = SigElement { + name: "TEXCOORD".into(), + index: 0, + kind: 0, + comp: 9, + interp: 0, + row: Some(0), + col: 3, + cols: 1, + usage: 0, + half: false, + }; + let isg1 = super::container::signature(&[w_only], true); + let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]); + 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(); + // Translated or refused with a reason; it must not panic. + let _ = super::emit(&c, &native, &p, &st, &io, &res); + } + + #[test] + fn valu_div_f32_sequence_executes_on_gpu() { + let words: &[u32] = &[ + 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 + 0x340E_0083, // v_lshlrev_b32 v7, 3, v0 + 0xE034_1000, + 0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen + 0xD56D_6A03, + 0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1 + 0xD56D_1008, + 0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1 + 0x7E08_5503, // v_rcp_f32 v4, v3 + 0xD54B_0005, + 0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0 + 0xD54B_0004, + 0x0412_0905, // v_fma_f32 v4, v5, v4, v4 + 0x100A_0908, // v_mul_f32 v5, v8, v4 + 0xD54B_0006, + 0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8 + 0xD56F_0004, + 0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5 + 0xD55F_0001, + 0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0xE070_1000, + 0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen + 0xBF81_0000, // s_endpgm + ]; + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 9, + layout: vec![ + crate::RootParam { + root: crate::RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + crate::RootParam { + root: crate::RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![ + crate::UsedResource { + kind: crate::ResourceType::Srv, + root: crate::RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + crate::UsedResource { + kind: crate::ResourceType::Uav, + root: crate::RootType::Table, + table_offset_dwords: 8, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + ], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { + rsrc2: 5 << 1, + threads: [7, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + 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(); + 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, + }) + .unwrap(); + let mut dxil = l.dxil; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut dxil).unwrap(); + } + #[cfg(windows)] + if let Ok(host) = super::host::Host::new(false) { + let cs = super::HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data, + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: Vec::new(), + }; + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + let inputs: Vec<u32> = [ + 7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35, + ] + .into_iter() + .map(f32::to_bits) + .collect(); + let out = host + .dispatch( + &root, + &pso, + &super::host::Dispatch { + roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))], + views: &[ + super::host::View::Buffer { + data: &inputs, + stride: super::host::Stride::Raw, + }, + super::host::View::RawUav(64), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect(); + assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got); + assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits()); + assert!( + (got[2] - 1e-35).abs() <= 1e-40, + "lane 2 got {:?} ({:#x})", + got[2], + out[0][2] + ); + assert!( + (got[3] - 10.0).abs() < 1e-5, + "lane 3 got {:?} ({:#x})", + got[3], + out[0][3] + ); + assert_eq!(out[0][4], 0xFFC0_0000); + assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits()); + assert!( + (got[6] - (-1.0)).abs() < 1e-6, + "lane 6 got {:?} ({:#x})", + got[6], + out[0][6] + ); + } + } +} + +#[cfg(test)] +mod atomic_tests { + use super::*; + use crate::native::{ComputeIo, RootParam, StageIo}; + + #[test] + fn heap_texture_atomic_widths() { + // A synthetic compute shader loads a 2D UAV from a root table, + // compares or adds at (0, 0), then uses the returned register(s). + for (opcode, mask, wide) in [ + (16u32, 3, false), + (16, 15, true), + (17, 1, false), + (17, 3, true), + ] { + let words = [ + 0xBE81_0380, // s_mov_b32 s1, 0 (table address high) + 0xF40C_0200, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0 + 0x7E00_0280, + 0x7E02_0280, // v0, v1 = coordinates + 0x7E04_0281, + 0x7E06_0282, + 0x7E08_0283, + 0x7E0A_0284, // v2..v5 = 1..4 + 0xF000_2008 | opcode << 18 | mask << 8, + 0x0002_0200, + // Use the old value in a second atomic at the same location. + 0xF044_0008 | (if wide { 3 } else { 1 }) << 8, + 0x0002_0200, + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 6, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 2, + threads: [32, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, false, native.vgprs).unwrap(); + let bytes = crate::dxbc::build(&[]); + let shader = emit( + &Container::parse(&bytes).unwrap(), + &native, + &p, + &structure::structure(&p).unwrap(), + &io::raise(&p, &native).unwrap(), + &resource::track(&p, &native.layout, native.stage, None).unwrap(), + ) + .unwrap(); + let container = Container::parse(&shader.dxil).unwrap(); + let features = u64::from_le_bytes( + container + .part(FourCC::SFI0) + .unwrap() + .data + .try_into() + .unwrap(), + ); + let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops + assert_eq!(features & required, if wide { required } else { 0 }); + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()).unwrap(); + } + } + } +} + +#[cfg(test)] +mod barycentric_tests { + use super::container::SigElement; + use super::*; + use crate::native::{PsInput, StageIo, Usage}; + + /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER. + const PERSP_CENTER: u32 = 1 << 1; + const LINEAR_CENTER: u32 = 1 << 5; + + /// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`. + fn exp_mrt0(r: u32) -> [u32; 2] { + [0xF800_180F, r * 0x0101_0101] + } + + /// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`. + fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 { + 3 << 25 | dst << 17 | b << 9 | (256 + a) + } + + fn element(name: &str, kind: u8, row: u32) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: false, + } + } + + /// Translates a pixel program with the input VGPRs `input_addr` + /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0). + fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> { + 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: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true); + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let res = resource::track(&p, &native.layout, native.stage, None)?; + let io = io::raise(&p, &native)?; + let st = structure::structure(&p)?; + emit(&c, &native, &p, &st, &io, &res) + } + + /// The translation's `SFI0` features and `ISG1` rows. + fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) { + let c = Container::parse(&shader.dxil).unwrap(); + let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap(); + ( + u64::from_le_bytes(sfi0), + signature(c.part(FourCC::ISG1).unwrap().data).unwrap(), + ) + } + + fn validate(shader: &HostShader) { + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()).unwrap(); + } + let _ = shader; + } + + /// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as + /// plain floats: they are channels y and z of `SV_Barycentrics`, the + /// weights of vertices 1 and 2. + #[test] + fn barycentrics_read_as_values_are_sv_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect(); + assert_eq!(bary.len(), 1, "{inputs:?}"); + assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3)); + // Not packed: the validator wants packing location -1. + assert_eq!(bary[0].row, None); + // Only y and z (I and J) are read. + let isg1 = Container::parse(&shader.dxil).unwrap(); + let isg1 = isg1.part(FourCC::ISG1).unwrap().data; + let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect(); + assert!(rw.contains(&0b110), "{rw:?}"); + validate(&shader); + } + + /// Two kinds of barycentrics read directly: one element per mode. + #[test] + fn two_barycentric_modes_get_two_elements() { + // v0-v1 perspective i, j; v2-v3 linear i, j. + let [e0, e1] = exp_mrt0(4); + let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + let mut indices: Vec<u32> = inputs + .iter() + .filter(|e| e.kind == 28) + .map(|e| e.index) + .collect(); + indices.sort(); + assert_eq!(indices, [0, 1], "{inputs:?}"); + validate(&shader); + } + + /// I and J only fed to `v_interp_*` stay host interpolation: no + /// barycentrics are declared. + #[test] + fn interpolation_alone_declares_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_eq!(features & 0x2_0000, 0); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + validate(&shader); + } + + /// Both: the attribute is interpolated and J is used as a value. + #[test] + fn interpolation_and_a_barycentric_value_together() { + let [e0, e1] = exp_mrt0(3); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + v_add_f32(3, 2, 1), // v3 = attribute + j + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + validate(&shader); + } + /// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float). + fn texcoord_mode(shader: &HostShader) -> u8 { + let c = Container::parse(&shader.dxil).unwrap(); + let psv = c.part(FourCC::PSV0).unwrap().data; + let row = [1, 0, 0x44, 0, 3]; + let at = psv.windows(5).position(|w| w == row).unwrap(); + psv[at + 5] + } + + const S_ENDPGM: u32 = 0xBF81_0000; + + /// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads + /// the attribute's vertices: TEXCOORD0 becomes constant, read with + /// `attributeAtVertex`; i and j are `SV_Barycentrics` values. + #[test] + fn computed_barycentrics_read_the_vertices() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0x1006_00F0, // v_mul_f32 v3, 0.5, v0 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// Weights from constants alone: the vertices, no `SV_Barycentrics`. + #[test] + fn constant_weights_need_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// The same attribute interpolated with the loaded i and j and with a + /// computed j: both from its vertices, the first weighed with + /// `SV_Barycentrics`. + #[test] + fn computed_and_loaded_barycentrics_on_one_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y + 0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y + 0x1006_02F0, // v_mul_f32 v3, 0.5, v1 + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// P10 of an attribute the program interpolates is P1 - P0. + #[test] + fn p10_of_an_interpolated_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + // Alone, what the hardware holds is not known. + let [e0, e1] = exp_mrt0(4); + let words = [0xC812_0000, e0, e1, S_ENDPGM]; + assert!(pixel(&words, PERSP_CENTER).is_err()); + } +} diff --git a/crates/victory-shader/src/emit/own_bits.rs b/crates/victory-shader/src/emit/own_bits.rs new file mode 100644 index 000000000..64aaba8f5 --- /dev/null +++ b/crates/victory-shader/src/emit/own_bits.rs @@ -0,0 +1,914 @@ +//! Wave ORs that only steer a loop over each lane's own bits. +//! +//! The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and +//! the wave walks the set bits of the result together, each lane working only where its own +//! mask has the bit: +//! +//! ```text +//! merged = WaveActiveBitOr(mask); // over the lanes that run +//! while (merged != 0) { +//! bit = firstbitlow(merged); +//! if (mask & (1 << bit)) { ... } // the body +//! merged ^= 1 << bit; +//! } +//! ``` +//! +//! A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not +//! every lane runs (a group barrier must be reached by every thread). It does not have to: as +//! one thread runs it, the loop visits the bits of `merged` in rising order and does something +//! only at the bits of the thread's own mask, so any `merged` that holds the thread's own bits +//! gives that thread the same run. The host wave's own OR is such a value. +//! +//! That holds only if the OR is used for nothing else, and if a round of the loop at a bit the +//! thread does not have leaves nothing behind. [`find`] proves both for each wave OR, with no +//! instruction sequence taken on trust: +//! +//! - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the +//! first-lane read of it, the set less the visited bit) are read only by the loop's own +//! steps: the test for an empty set, the lowest set bit, the removal of that bit, the test +//! that ends the loop; +//! - the lane's test is its own bit of the very value that was ORed, and "the body" is what a +//! lane only reaches with that test true in the same round; +//! - outside the body the loop has no side effect and no cross-lane step, writes nothing that +//! is read after the loop or carried into a later round, and is left only by the test for +//! "no bits left"; +//! - no lane mask that depends on the test is used outside the round that made it. +//! +//! Anything else is refused there as before ("a wave reduction where not every lane runs") and +//! left to the forms of the program in which every lane runs that code (`emit`'s retries: the +//! skips left out, the branches around it taken wave-wide), where the halves do exchange. +//! `VICTORY_WAVE_OWN_BITS=0` turns this off. + +use std::collections::{HashMap, HashSet}; + +use super::wave::{self, Op, Shape}; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; + +type Why = &'static str; + +const USED: Why = "a wave OR used as data"; +const NO_LOOP: Why = "a wave OR that steers no loop over its bits"; +const SHAPE: Why = "a loop over a wave OR's bits of another shape"; +const TEST: Why = "a loop over a wave OR's bits whose lanes do not test their own bit"; +const LEAVES: Why = "a value of a round over a wave OR's bits that outlives the round"; +const EFFECT: Why = "an effect in a loop over a wave OR's bits outside the lanes' own bits"; +const CROSS: Why = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits"; +const EXIT: Why = "a loop over a wave OR's bits left another way"; +const STALE: Why = "a lane's own-bit test used outside its round"; +const MASK: Why = "a wave OR over a mask a running lane may be outside"; + +/// What [`find`] proved. +#[derive(Debug, Default)] +pub(super) struct OwnBits { + /// Wave ORs (the values their sections leave) a host wave may take over its own lanes. + pub totals: HashSet<Value>, + /// VGPR values of those loops that every lane of a host wave holds alike (the bits still + /// to visit): a first-lane read of one is the lane's own value. + pub alike: HashSet<Value>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum User { + Inst(usize, usize), + Phi(usize, usize), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Arg { + Val(Value), + K(u32), + Other, +} + +struct Ctx<'a> { + p: &'a Program, + st: &'a Structured, + users: HashMap<Value, Vec<User>>, + /// The instruction writing each value. + def: HashMap<Value, (usize, usize)>, + /// Values an instruction reads, directly or through joins. + live: HashSet<Value>, + idom: Vec<usize>, + sections: Vec<HashMap<usize, wave::Section>>, +} + +/// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane +/// masks are followed as booleans) and without the old value of a VGPR it writes, which only +/// lanes outside a guard keep. +fn used(p: &Program, st: &Structured, b: usize, i: usize) -> Vec<Value> { + let inst = &p.blocks[b].insts[i]; + let ops = crate::ir::operand_reads(p, inst); + let guarded = st.guards[b][i].is_some(); + inst.reads + .iter() + .filter(|&&(r, _)| match r { + Reg::S(c) if c == EXEC || c == EXEC + 1 => false, + Reg::V(_) => ops.contains(&r) || guarded, + _ => true, + }) + .map(|r| r.1) + .collect() +} + +fn value(inst: &Inst, op: &Operand) -> Option<Value> { + match *op { + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + _ => None, + } +} + +/// The sources of a scalar or unmodified vector operation. +fn args(inst: &Inst) -> Vec<Arg> { + let src: &[Operand] = match &inst.fields { + Fields::Sop { src, .. } => src, + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && v.abs == 0 + && v.neg == 0 + && !v.clamp + && v.omod == 0 => + { + &v.src + } + _ => &[], + }; + src.iter() + .map(|o| match (value(inst, o), o) { + (Some(v), _) => Arg::Val(v), + (None, &Operand::Const(c)) => crate::resource::inline(c).map_or(Arg::Other, Arg::K), + (None, &Operand::Literal(x)) => Arg::K(x), + _ => Arg::Other, + }) + .collect() +} + +/// The other source of a two-source operation that reads `a`. +fn other(inst: &Inst, a: Value) -> Option<Arg> { + match args(inst)[..] { + [Arg::Val(x), o] if x == a => Some(o), + [o, Arg::Val(x)] if x == a => Some(o), + _ => None, + } +} + +/// The scalar (not SCC) or vector dword an instruction writes, if it writes one. +fn result(inst: &Inst) -> Option<Value> { + let mut w = inst.writes.iter().filter(|w| w.0 != Reg::Scc); + match (w.next(), w.next()) { + (Some(&(_, v)), None) => Some(v), + _ => None, + } +} + +/// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program +/// sends. +fn effect(inst: &Inst) -> bool { + let name = inst.name(); + matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")) + || matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt") +} + +impl Ctx<'_> { + fn new<'a>(p: &'a Program, st: &'a Structured) -> Ctx<'a> { + let mut users: HashMap<Value, Vec<User>> = HashMap::new(); + let mut def = HashMap::new(); + let mut live: HashSet<Value> = HashSet::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (k, phi) in block.phis.iter().enumerate() { + for &a in &phi.args { + users.entry(a).or_default().push(User::Phi(b, k)); + } + } + for (i, inst) in block.insts.iter().enumerate() { + for v in used(p, st, b, i) { + users.entry(v).or_default().push(User::Inst(b, i)); + live.insert(v); + } + for &(_, w) in &inst.writes { + def.insert(w, (b, i)); + } + } + } + // through joins + let mut changed = true; + while changed { + changed = false; + for block in &p.blocks { + for phi in &block.phis { + if live.contains(&phi.value) { + for &a in &phi.args { + changed |= live.insert(a); + } + } + } + } + } + let order = crate::ir::reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + let idom = crate::ir::idoms(&p.blocks, &order, &index); + let sections = (0..p.blocks.len()).map(|b| wave::sections(p, b)).collect(); + Ctx { + p, + st, + users, + def, + live, + idom, + sections, + } + } + + fn inst(&self, u: (usize, usize)) -> &Inst { + &self.p.blocks[u.0].insts[u.1] + } + + fn at(&self, u: (usize, usize)) -> usize { + self.inst(u).machine.offset + } + + /// Whether block `a` dominates block `b`. + fn dominates(&self, a: usize, mut b: usize) -> bool { + loop { + if a == b { + return true; + } + let d = self.idom.get(b).copied().unwrap_or(usize::MAX); + if d == b || d == usize::MAX { + return false; + } + b = d; + } + } + + fn readers(&self, v: Value) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = self + .users + .get(&v) + .into_iter() + .flatten() + .filter_map(|u| match *u { + User::Inst(b, i) => Some((b, i)), + User::Phi(..) => None, + }) + .collect(); + out.sort_unstable(); + out.dedup(); + out + } + + /// The joins reading `v` whose value something reads. + fn joins(&self, v: Value) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = self + .users + .get(&v) + .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)), + _ => None, + }) + .collect(); + out.sort_unstable(); + out.dedup(); + out + } + + /// The loop of header `h`: the blocks that reach one of its back edges without passing it. + fn natural_loop(&self, h: usize) -> Vec<bool> { + let mut inside = vec![false; self.p.blocks.len()]; + let mut work: Vec<usize> = self.p.blocks[h] + .preds + .iter() + .copied() + .filter(|&q| self.dominates(h, q)) + .collect(); + if work.is_empty() { + return inside; + } + inside[h] = true; + while let Some(b) = work.pop() { + if inside[b] { + continue; + } + inside[b] = true; + work.extend(self.p.blocks[b].preds.iter().copied()); + } + inside + } + + /// Whether `b` holds only in lanes where `a` does. + fn implied(&self, b: Bool, a: Atom, memo: &mut HashMap<Bool, bool>) -> bool { + if b == Bool::FALSE { + return true; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let r = match self.st.bools.node(b) { + None => false, + Some((x, lo, _)) if x == a => lo == Bool::FALSE, + Some((_, lo, hi)) => self.implied(lo, a, memo) && self.implied(hi, a, memo), + }; + memo.insert(b, r); + r + } + + /// The conditional branch reading `scc`, as (its place, the block it goes to when SCC is + /// set, the other one). + fn branch(&self, scc: Value) -> Option<((usize, usize), usize, usize)> { + let [u] = self.readers(scc)[..] else { + return None; + }; + let Exit::Branch { taken, not_taken } = self.p.blocks[u.0].exit else { + return None; + }; + if u.1 + 1 != self.p.blocks[u.0].insts.len() { + return None; + } + match self.inst(u).name() { + "s_cbranch_scc1" => Some((u, taken, not_taken)), + "s_cbranch_scc0" => Some((u, not_taken, taken)), + _ => None, + } + } + + /// 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. + fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result<Vec<Value>, (usize, Why)> { + let p = self.p; + let st = self.st; + let n = p.blocks.len(); + let here = p.blocks[sb].offset; + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + // every lane that runs the section is one of the lanes ORed + let &mb = st.masks.get(&mask).ok_or((here, MASK))?; + if st.bools.meet(&[(st.reach[sb], true), (mb, false)]) { + return Err((here, MASK)); + } + // ---- the bits still to visit, and the loop's own steps ---- + let mut rem: HashSet<Value> = HashSet::from([t]); + let mut pattern: HashSet<(usize, usize)> = HashSet::new(); + let mut alike: Vec<Value> = Vec::new(); + // an unguarded copy + let copy = |u: (usize, usize)| -> Option<Value> { + 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() + }; + let mut init = vec![t]; + // (SCC, whether it is set when the OR is empty) + let mut zero: Option<(Value, bool)> = None; + 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)) + && zero.is_none() + && let Some(scc) = i.write(Reg::Scc) + { + zero = Some((scc, name.contains("_eq_"))); + rem.insert(scc); + } else if let Some(w) = copy(u) { + init.push(w); + rem.insert(w); + if matches!(i.writes[0].0, Reg::V(_)) { + alike.push(w); + } + } else { + return Err((self.at(u), USED)); + } + pattern.insert(u); + } + // the loop's join of them + let mut join: Option<(usize, usize)> = None; + for &v in &init { + if v != t + && let Some(&u) = self.readers(v).first() + { + return Err((self.at(u), USED)); + } + for j in self.joins(v) { + if join.is_some_and(|q| q != j) { + return Err((p.blocks[j.0].offset, USED)); + } + join = Some(j); + } + } + let (h, k) = join.ok_or((here, NO_LOOP))?; + let phi = &p.blocks[h].phis[k]; + let r = phi.value; + rem.insert(r); + let head = p.blocks[h].offset; + let lp = self.natural_loop(h); + if !lp[h] || lp[sb] { + return Err((head, NO_LOOP)); + } + // the set as a scalar: the first lane's copy of it + let cur = if matches!(phi.reg, Reg::V(_)) { + alike.push(r); + let [u] = self.readers(r)[..] else { + return Err((head, USED)); + }; + let i = self.inst(u); + if i.name() != "v_readfirstlane_b32" || args(i).len() != 1 || !lp[u.0] { + return Err((self.at(u), USED)); + } + pattern.insert(u); + let c = result(i).ok_or((self.at(u), SHAPE))?; + if !self.joins(r).is_empty() { + return Err((head, USED)); + } + c + } else { + r + }; + rem.insert(cur); + // its lowest bit, the set without it, the tests for "that was the last" + let mut idx: Option<Value> = None; + let mut next: Option<(Value, Value)> = None; + // (SCC, whether it is set while bits remain) + let mut more: Vec<(Value, bool)> = Vec::new(); + let mut bits: Vec<Value> = Vec::new(); + for u in self.readers(cur) { + let i = self.inst(u); + let name = i.name(); + if !lp[u.0] { + return Err((self.at(u), USED)); + } + 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() => { + 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) { + Some(Arg::Val(b)) if b != cur => b, + _ => return Err((self.at(u), USED)), + }, + _ => return Err((self.at(u), USED)), + }; + let w = result(i).ok_or((self.at(u), SHAPE))?; + next = Some((w, bit)); + bits.push(bit); + if let Some(scc) = i.write(Reg::Scc) { + more.push((scc, true)); + rem.insert(scc); + } + } + ("s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32", _) => { + let (Some(Arg::Val(b)), Some(scc)) = (other(i, cur), i.write(Reg::Scc)) else { + return Err((self.at(u), USED)); + }; + bits.push(b); + more.push((scc, name.contains("_lg_"))); + rem.insert(scc); + } + _ => return Err((self.at(u), USED)), + } + pattern.insert(u); + } + if cur != r && !self.joins(cur).is_empty() { + return Err((head, USED)); + } + let (Some(idx), Some((nx, bit))) = (idx, next) else { + return Err((head, SHAPE)); + }; + if bits.iter().any(|&b| b != bit) { + return Err((head, SHAPE)); + } + // the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it) + let made = |v: Value| self.def.get(&v).map(|&u| (u, self.inst(u))); + let shifted = match made(bit) { + Some((u, i)) if i.name() == "s_lshl_b32" && lp[u.0] => match args(i)[..] { + [Arg::K(1), Arg::Val(sh)] => Some(sh), + _ => None, + }, + _ => None, + }; + 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))) + }); + if !by_idx { + return Err((head, SHAPE)); + } + // the set less the bit: back into the join, or tested for empty + rem.insert(nx); + let mut nexts = vec![nx]; + 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)) + && let Some(scc) = i.write(Reg::Scc) + { + more.push((scc, name.contains("_lg_"))); + rem.insert(scc); + } else if let Some(w) = copy(u) { + nexts.push(w); + rem.insert(w); + if matches!(i.writes[0].0, Reg::V(_)) { + alike.push(w); + } + } else { + return Err((self.at(u), USED)); + } + pattern.insert(u); + } + for &v in &nexts { + if v != nx + && let Some(&u) = self.readers(v).first() + { + return Err((self.at(u), USED)); + } + if self.joins(v).iter().any(|&j| j != (h, k)) { + return Err((head, USED)); + } + } + for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) { + let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) }; + if !ok { + return Err((head, SHAPE)); + } + } + // the loop goes on while bits remain and is left when none does + let mut leaves: HashSet<usize> = HashSet::new(); + for &(scc, set_while_more) in &more { + if !self.joins(scc).is_empty() { + return Err((head, USED)); + } + if self.readers(scc).is_empty() { + continue; + } + let (u, set, clear) = self.branch(scc).ok_or((head, USED))?; + 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)); + } + leaves.insert(u.0); + pattern.insert(u); + } + if leaves.is_empty() { + return Err((head, SHAPE)); + } + // "no bit at all" skips the loop; what lies between that test and the loop runs only + // when there is one + let mut pre = vec![false; n]; + if let Some((scc, set_when_empty)) = zero { + if !self.joins(scc).is_empty() { + return Err((here, USED)); + } + 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) }; + if none == some || lp[u.0] { + return Err((self.at(u), SHAPE)); + } + if some != h { + if p.blocks[some].preds[..] != [u.0] || !self.dominates(some, h) { + return Err((self.at(u), SHAPE)); + } + for b in 0..n { + pre[b] = self.dominates(some, b) && !self.dominates(h, b); + } + for b in (0..n).filter(|&b| pre[b]) { + let inside = match p.blocks[b].exit { + Exit::End | Exit::Indirect => false, + ref e => e.successors().iter().all(|&s| pre[s] || s == h), + }; + if !inside { + return Err((p.blocks[b].offset, SHAPE)); + } + } + } + pattern.insert(u); + } + } + // ---- the lane's test of its own bit ---- + // (the atom of the compare, its block, its index) + 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() { + continue; + } + let Some(y) = result(i) else { continue }; + for c in self.readers(y) { + 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" + ) && other(ci, y) == Some(Arg::K(0)) + && lp[c.0] + { + tests.extend(ci.writes.iter().map(|w| (Atom::Lane(w.1), c.0, c.1))); + } + } + } + if tests.is_empty() { + return Err((head, TEST)); + } + let mut memo: Vec<HashMap<Bool, bool>> = vec![HashMap::new(); tests.len()]; + // what a lane only reaches with its own bit set, in the round of that test + let mut body_block = vec![false; n]; + for b in (0..n).filter(|&b| lp[b]) { + body_block[b] = tests.iter().enumerate().any(|(j, &(a, tb, _))| { + b != tb && self.dominates(tb, b) && self.implied(st.reach[b], a, &mut memo[j]) + }); + } + let body_inst = |b: usize, i: usize, memo: &mut Vec<HashMap<Bool, bool>>| { + body_block[b] + || 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]) + }) + }) + }; + // ---- a round outside the body leaves nothing behind ---- + for b in (0..n).filter(|&b| lp[b] || pre[b]) { + for (i, inst) in p.blocks[b].insts.iter().enumerate() { + if lp[b] && body_inst(b, i, &mut memo) { + continue; + } + 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) { + continue; + } + for user in self.users.get(&w).into_iter().flatten() { + let stays = match *user { + User::Inst(b2, _) => lp[b2] || pre[b2], + User::Phi(b2, k2) => { + body_block[b2] || !self.live.contains(&p.blocks[b2].phis[k2].value) + } + }; + if !stays { + return Err((self.at(u), LEAVES)); + } + } + } + if pattern.contains(&u) { + continue; + } + if effect(inst) { + return Err((self.at(u), EFFECT)); + } + let name = inst.name(); + let cross = name.starts_with("ds_swizzle") + || name.contains("permute") + || name.starts_with("v_mbcnt") + || 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); + if cross { + return Err((self.at(u), CROSS)); + } + if used(p, st, b, i).iter().any(|v| rem.contains(v)) { + return Err((self.at(u), USED)); + } + } + // left only by "no bits left"; the body may leave it as it likes + if lp[b] && !body_block[b] { + let ok = match p.blocks[b].exit { + Exit::End | Exit::Indirect => false, + ref e => leaves.contains(&b) || e.successors().iter().all(|&s| lp[s]), + }; + if !ok { + return Err((p.blocks[b].offset, EXIT)); + } + } + } + // ---- no mask that depends on the test outlives its round ---- + let mut dep: HashSet<Atom> = tests.iter().map(|t| t.0).collect(); + let mut changed = true; + while changed { + 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))) + { + dep.insert(Atom::Phi(id)); + changed = true; + } + } + } + let mut seen: HashMap<Bool, bool> = HashMap::new(); + let mut tainted = |b: Bool| -> bool { + *seen + .entry(b) + .or_insert_with(|| st.bools.support(b).iter().any(|a| dep.contains(a))) + }; + for b in 0..n { + if lp[b] && tests.iter().any(|&(_, tb, _)| self.dominates(tb, b)) { + continue; + } + let stale = st.guards[b].iter().flatten().any(|&g| tainted(g)) + || matches!(st.exits[b], LaneExit::Branch { when, .. } if tainted(when)); + if stale { + return Err((p.blocks[b].offset, STALE)); + } + } + for (&v, &m) in &st.masks { + if !tainted(m) { + continue; + } + 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), + }; + if outside { + return Err((head, STALE)); + } + } + } + Ok(alike) + } +} + +/// The wave ORs of `p` that only steer a loop over each lane's own bits (see the module +/// notes). `why`: one line on stderr for each wave OR that is not one. +pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits { + let mut out = OwnBits::default(); + let mut ctx: Option<Ctx> = None; + for b in 0..p.blocks.len() { + let sections = wave::sections(p, b); + let mut starts: Vec<_> = sections.keys().copied().collect(); + starts.sort_unstable(); + for s in starts { + let sec = §ions[&s]; + let mut left: Vec<_> = sec.shapes.iter().collect(); + left.sort_unstable_by_key(|(v, _)| v.0); + for (&t, &shape) in left { + let Shape::Active(Op::Or, x, mask, 0) = shape else { + continue; + }; + 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); + if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) { + continue; + } + match ctx.site(b, t, x, mask) { + Ok(alike) => { + out.totals.insert(t); + out.alike.extend(alike); + } + Err((offset, what)) => { + if why { + eprintln!( + "WAVE64-OWN-BITS the wave OR at {:#x}: not a loop over the lanes' own bits at {offset:#x}: {what}", + p.blocks[b].insts[s].machine.offset + ); + } + } + } + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::emit::wave::WAVE_OR_V7_TO_S7; + + const ADD_BIT_NUMBER: u32 = 0x4A0A_0A0A; // v_add_nc_u32 v5, s10, v5 + + /// The title's scalarised light loop (`indirect_light_probes:CS_IrradianceCache_Shade`, + /// 0x71f8 on), in small: the wave OR of v7 in s7, a loop over its bits with the lowest + /// one's number in s10 and the bit in s11, and `body` for the lanes whose v7 has the bit + /// (`own`) or for every lane; `latch` runs in every lane after the body, `after` after + /// the loop. + fn light_loop(own: bool, body: &[u32], latch: &[u32], after: &[u32]) -> Program { + let mut w = WAVE_OR_V7_TO_S7.to_vec(); + let test: &[u32] = if own { + &[ + 0x3608_0E0B, // v_and_b32 v4, s11, v7 + 0xBE8C_047E, // s_mov_b64 s[12:13], exec + 0x7DAA_0880, // v_cmpx_ne_u32 exec, 0, v4 + ] + } else { + &[0xBE8C_047E] // s_mov_b64 s[12:13], exec + }; + // from the loop's head to its last branch + let head = 3 + test.len() + usize::from(own) + body.len() + 1 + latch.len() + 3; + w.extend_from_slice(&[ + 0xBF06_8007, // s_cmp_eq_u32 s7, 0 + 0xBF85_0000 | (3 + head) as u32, // s_cbranch_scc1 past the loop + 0x7E06_0207, // v_mov_b32 v3, s7 + 0xBF82_0001, // s_branch to the loop's head + 0x7E06_0209, // again: v_mov_b32 v3, s9 + 0x7E10_0503, // head: v_readfirstlane_b32 s8, v3 + 0xBE8A_1308, // s_ff1_i32_b32 s10, s8 + 0x8F0B_0A81, // s_lshl_b32 s11, 1, s10 + ]); + w.extend_from_slice(test); + if own { + w.push(0xBF88_0000 | body.len() as u32); // s_cbranch_execz past the body + } + w.extend_from_slice(body); + 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 + 0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again + ]); + w.extend_from_slice(after); + w.push(0xBF81_0000); // s_endpgm + let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect(); + crate::ir::build(&code, true, 256).unwrap() + } + + fn found(p: &Program) -> OwnBits { + let st = crate::structure::structure(p).unwrap(); + find(p, &st, false) + } + + #[test] + fn a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() { + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[]); + let insts = || p.blocks.iter().flat_map(|b| &b.insts); + let names: Vec<&str> = insts().map(|i| i.name()).collect(); + for n in [ + "s_ff1_i32_b32", + "s_lshl_b32", + "v_and_b32", + "v_cmpx_ne_u32", + "s_xor_b32", + "v_readfirstlane_b32", + "s_cbranch_execz", + ] { + 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))); + 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() + .rfind(|i| i.name() == "v_readlane_b32") + .and_then(|i| i.write(Reg::S(7))) + .unwrap(); + assert_eq!(own.totals, HashSet::from([total])); + let first = insts().find(|i| i.name() == "v_readfirstlane_b32").unwrap(); + assert!(own.alike.contains(&first.read(Reg::V(3)).unwrap())); + } + + #[test] + fn a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() { + // (the same title's volume loops, 0xa668 on: no test of the lane's own mask) + let p = light_loop(false, &[ADD_BIT_NUMBER], &[], &[]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn a_bit_number_read_after_the_loop_is_not_the_lanes_own() { + // v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020A]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() { + // v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too + let p = light_loop(true, &[0x4A0A_0A08], &[], &[]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn a_count_of_the_rounds_is_not_the_lanes_own() { + // 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!(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]); + assert_eq!(found(&p).totals.len(), 1); + } + + #[test] + 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!(found(&p).totals.is_empty()); + } +} diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs new file mode 100644 index 000000000..c05f28b44 --- /dev/null +++ b/crates/victory-shader/src/emit/rect.rs @@ -0,0 +1,484 @@ +//! The geometry shader that completes the console's rectangle lists (list +//! topology 17, pipeline topology type 19). A rectangle comes as three +//! vertices, three corners of a screen-aligned rectangle; the hardware +//! draws the whole rectangle and continues every vertex shader output +//! linearly into the fourth corner. The host has no such topology: the +//! draw goes out as a triangle list with this shader behind the translated +//! vertex shader, so vertex counts, vertex numbers, indices and indirect +//! 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 +//! 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, +//! `a + b - corner` for the position and every float output. That holds +//! for three vertices with one positive w (then it is the same in clip +//! space and on the screen, whatever the interpolation mode); three that +//! differ in w, or are not such corners, stay the triangle they make. +//! +//! Flat values are the first vertex's: both triangles start with it (the +//! halves on either side of the diagonal through it, turning as the three +//! vertices do), which is the vertex the host takes a flat input from, and +//! the fourth vertex's integer outputs are the first vertex's. +//! +//! shortcut: that the console takes a rectangle's flat values from its +//! first vertex follows from the hardware's provoking-vertex setting for +//! triangles; it is not measured on a rectangle. + +use super::bitcode::{Attr, Bin, Term, V, pred}; +use super::container::SigElement; +use super::shader::{Geometry, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// Vertices emitted per rectangle: two triangles. +const VERTICES: u32 = 6; + +/// The scalars a geometry shader may emit per invocation (vertices times +/// output components). +const MAX_SCALARS: u32 = 1024; + +/// The geometry shader (a DXIL container) for rectangle lists drawn with +/// the translated vertex shader `vs` and, if the pipeline has one, the +/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its +/// inputs and outputs are the vertex shader's outputs, register for +/// register, so it links with both. A pixel shader that declares a +/// primitive id gets the rectangle's number, which the host leaves to the +/// geometry stage when there is one. +pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> { + let sig = |dxil: &[u8], fourcc| -> Result<Vec<SigElement>, ShaderError> { + let c = Container::parse(dxil)?; + match c.part(fourcc) { + Some(part) => super::signature(part.data), + None => Ok(Vec::new()), + } + }; + let outputs = sig(vs, FourCC::OSG1)?; + let wanted = match ps { + Some(ps) => sig(ps, FourCC::ISG1)?, + None => Vec::new(), + }; + build(outputs, &wanted) +} + +/// [`rect_list_gs`] from the vertex shader's outputs and the pixel +/// shader's inputs. +fn build(mut outputs: Vec<SigElement>, ps_inputs: &[SigElement]) -> Result<Vec<u8>, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if outputs.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a rectangle list output without a register")); + } + let Some(position) = outputs + .iter() + .position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4) + else { + return Err(unsupported("a rectangle list without a four-component position")); + }; + for e in &mut outputs { + // Interpolation as `emit_program` declares a vertex shader's + // outputs; a geometry shader's inputs carry the same modes. + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + (0 | 6 | 7, 9) => 2, + (0, _) => 1, + _ => 0, + }; + e.usage = (1 << e.cols) - 1; + } + let mut s = Shader::new(false); + s.geometry = Some(Geometry { + max_vertices: VERTICES, + }); + s.inputs = outputs.clone(); + // The primitive id the pixel shader declares, as one more output. + let wanted = ps_inputs + .iter() + .find(|e| e.kind == 10 && e.row.is_some()) + .filter(|_| !outputs.iter().any(|o| o.kind == 10)); + let primitive = match wanted { + Some(e) => { + // Alone in its columns, and in a row of constant elements. + let clash = outputs.iter().any(|o| { + let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols; + o.row == e.row && (o.interp != 1 || overlap) + }); + if clash { + return Err(unsupported( + "a rectangle list whose primitive id shares a register with a vertex output", + )); + } + outputs.push(SigElement { + interp: 1, + usage: (1 << e.cols) - 1, + ..e.clone() + }); + Some(outputs.len() - 1) + } + None => None, + }; + let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum(); + if scalars * VERTICES > MAX_SCALARS { + return Err(unsupported( + "a rectangle list with more output components than a geometry shader emits", + )); + } + s.outputs = outputs; + let b = s.entry; + + // Every input of the three vertices: [element][column][vertex]. + let mut corners: Vec<Vec<[V; 3]>> = Vec::new(); + for id in 0..s.inputs.len() { + let mut columns = Vec::new(); + for col in 0..s.inputs[id].cols { + columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex))); + } + corners.push(columns); + } + + // One positive w, and no two vertices in one place. + let (x, y, w) = ( + corners[position][0], + corners[position][1], + corners[position][3], + ); + let zero = s.m.f32(0); + let mut plain = s.m.cmp(b, pred::OGT, w[0], zero); + for &other in &w[1..] { + let one_w = same(&mut s, other, w[0]); + plain = both(&mut s, plain, one_w); + } + for (i, j) in [(0, 1), (0, 2), (1, 2)] { + let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j])); + let together = both(&mut s, same_x, same_y); + let apart = not(&mut s, together); + plain = both(&mut s, plain, apart); + } + // corner[i]: vertex i is the corner between the other two (the first + // that shares x with one of them and y with the other). + let mut corner: Vec<V> = Vec::new(); + for i in 0..3 { + let (a, c) = ((i + 1) % 3, (i + 2) % 3); + let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c])); + let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a])); + let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya)); + let shares = either(&mut s, one, other); + let mut here = both(&mut s, shares, plain); + for &found in &corner { + let earlier = not(&mut s, found); + here = both(&mut s, here, earlier); + } + corner.push(here); + } + + // What the six emitted vertices carry: [element][column][vertex]. + let mut emitted: Vec<Vec<[V; 6]>> = Vec::new(); + for (id, columns) in corners.iter().enumerate() { + let float = s.inputs[id].comp == 9; + let mut out = Vec::new(); + for &[p0, p1, p2] in columns { + // The fourth vertex: `a + b - corner`. Integers (flat), and + // three vertices without a corner, keep the first vertex's + // value; the second triangle of the latter is then empty. + let mut fourth = p0; + if float { + for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)] + .into_iter() + .enumerate() + { + let sum = s.m.bin(b, Bin::Add, a, c); + let opposite = s.m.bin(b, Bin::Sub, sum, at); + fourth = s.m.select(b, corner[k], opposite, fourth); + } + } + // Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1, + // v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1). + let third = s.m.select(b, corner[0], fourth, p2); + let fifth = s.m.select(b, corner[1], p2, fourth); + let sixth = s.m.select(b, corner[0], p2, p1); + let sixth = s.m.select(b, corner[1], fourth, sixth); + out.push([p0, p1, third, p0, fifth, sixth]); + } + emitted.push(out); + } + + // The rectangle's number: the triangle's, three vertices a rectangle. + let mut number = None; + if let Some(id) = primitive { + let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]); + number = Some((id, n)); + } + let stream = s.m.i8(0); + for vertex in 0..VERTICES as usize { + for (id, columns) in emitted.iter().enumerate() { + let name = if s.outputs[id].comp == 9 { + "storeOutput.f32" + } else { + "storeOutput.i32" + }; + for (col, values) in columns.iter().enumerate() { + let args = [ + s.m.i32(id as u32), + s.m.i32(0), + s.m.i8(col as u8), + values[vertex], + ]; + s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); + } + } + if let Some((id, n)) = number { + let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n]; + s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]); + // The strip ends after the first triangle. + if vertex == 2 { + s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]); + } + } + s.m.terminate(b, Term::Ret); + Ok(s.finish()) +} + +/// Column `col` of input `id` at vertex `vertex` of the triangle. +fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V { + let (name, ty) = if s.inputs[id].comp == 9 { + ("loadInput.f32", s.t.f32) + } 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 entry = s.entry; + s.op(entry, name, Attr::ReadNone, ty, 4, &args) +} + +/// Two floats are equal. +fn same(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.cmp(entry, pred::OEQ, a, b) +} + +fn both(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.bin(entry, Bin::And, a, b) +} + +fn either(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.bin(entry, Bin::Or, a, b) +} + +fn not(s: &mut Shader, a: V) -> V { + let (entry, on) = (s.entry, s.m.bool(true)); + s.m.bin(entry, Bin::Xor, a, on) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement { + SigElement { + name: name.into(), + index, + kind, + comp, + interp: 0, + row: Some(row), + col: 0, + cols, + usage: 0, + half: false, + } + } + + /// A position, a float interpolant and an integer one. + fn outputs() -> Vec<SigElement> { + vec![ + element("SV_Position", 0, 3, 9, 0, 4), + element("TEXCOORD", 0, 0, 9, 1, 4), + element("TEXCOORD", 1, 0, 5, 2, 2), + ] + } + + /// The stage is a geometry shader of triangles in and six strip + /// vertices out, with the vertex shader's outputs on both sides and + /// the primitive id the pixel shader declares; the validator, where + /// there is one, accepts it. + #[test] + fn the_rectangle_stage_is_a_geometry_shader() { + let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)]; + let gs = build(outputs(), &wanted).unwrap(); + let c = Container::parse(&gs).unwrap(); + // Program version: geometry (2), shader model 6.6. + assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]); + let psv = c.part(FourCC::PSV0).unwrap().data; + // Triangles in, triangle strips out, stream 0, a position. + assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]); + // Geometry stage, six vertices, three inputs, four outputs. + assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]); + let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap(); + let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1)); + assert_eq!(ins.len(), 3); + assert_eq!(outs.len(), 4); + for (i, o) in ins.iter().zip(&outs) { + assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row)); + assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp)); + } + assert_eq!((outs[3].kind, outs[3].row), (10, Some(3))); + #[cfg(windows)] + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut gs.clone()).unwrap(); + let plain = build(outputs(), &[]).unwrap(); + v.validate(&mut plain.clone()).unwrap(); + } + } + + /// Refused with a reason: no position, a primitive id in a register a + /// vertex output has, more components than six vertices may carry. + #[test] + fn rectangle_stages_that_cannot_be_made_are_refused() { + assert!(build(outputs()[1..].to_vec(), &[]).is_err()); + let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)]; + assert!(build(outputs(), &taken).is_err()); + let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)]; + many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4))); + assert!(build(many, &[]).is_err()); + } + + /// A vertex shader that passes a position and a float4 through, and a + /// pixel shader that writes the float4. + #[cfg(windows)] + fn pass_through() -> (super::super::HostShader, super::super::HostShader) { + let position = SigElement { + interp: 4, + usage: 15, + ..element("SV_Position", 0, 3, 9, 0, 4) + }; + let coord = SigElement { + interp: 2, + usage: 15, + ..element("TEXCOORD", 0, 0, 9, 1, 4) + }; + let mut vs = Shader::new(false); + vs.inputs = vec![ + SigElement { + usage: 15, + ..element("POSITION", 0, 0, 9, 0, 4) + }, + SigElement { + interp: 0, + ..coord.clone() + }, + ]; + vs.outputs = vec![position.clone(), coord.clone()]; + let mut ps = Shader::new(true); + ps.inputs = vec![ + SigElement { + usage: 0, + ..position + }, + coord, + ]; + ps.outputs = vec![SigElement { + usage: 15, + ..element("SV_Target", 0, 16, 9, 0, 4) + }]; + // Vertex: output id from input id. Pixel: target 0 from input 1. + for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] { + let b = s.entry; + for &(from, to) in copies { + for col in 0..4 { + let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.m.terminate(b, Term::Ret); + } + let host = |stage, s: Shader| super::super::HostShader { + stage, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + }; + ( + host(crate::native::HwStage::Vs, vs), + host(crate::native::HwStage::Ps, ps), + ) + } + + /// Three corners of the whole target, the corner between the other two + /// first (as the tiled lighting sends its tiles), second (as + /// full-screen rectangles come) or third: with the stage every texel + /// is drawn and the interpolant continues into the fourth corner's + /// half; without it part of the target is not drawn. + #[test] + #[cfg(windows)] + fn rectangles_are_drawn_whole() { + use super::super::host::{Draw, Host}; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let (vs, ps) = pass_through(); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut vs.dxil.clone()).unwrap(); + v.validate(&mut ps.dxil.clone()).unwrap(); + } + let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap(); + let root = host.root_signature(&vs, &ps).unwrap(); + // Position (z 0.5, w 1) and an interpolant that is the position. + let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0]; + for (name, corners) in [ + ("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]), + ("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]), + ("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]), + ] { + let vertices = corners.map(vertex).concat(); + let draw = |gs: Option<&[u8]>| { + let pso = host + .pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil) + .unwrap(); + let d = Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 32, + size: (8, 8), + mesh_groups: 0, + }; + host.draw(&root, &pso, &d).unwrap() + }; + let whole = draw(Some(&gs[..])); + for (i, texel) in whole.iter().enumerate() { + let (x, y) = ((i % 8) as f32, (i / 8) as f32); + let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0]; + assert!( + texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), + "{name}: texel {i} is {texel:?}, not {want:?}" + ); + } + 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"); + } + } +} diff --git a/crates/victory-shader/src/emit/sampler.rs b/crates/victory-shader/src/emit/sampler.rs new file mode 100644 index 000000000..e10c0c16e --- /dev/null +++ b/crates/victory-shader/src/emit/sampler.rs @@ -0,0 +1,125 @@ +//! Immediate samplers: the console's four sampler words (the GPU's public +//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler. +//! +//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum +//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0 +//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD +//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8), +//! magnification and minification filters (20-21, 22-23: point, linear, +//! anisotropic point, anisotropic linear), mip filter (26-27: none, point, +//! linear). Word 3: border colour (30-31: transparent black, opaque black, +//! opaque white, custom). +//! +//! Comparison is the sampling instruction's, not the sampler's: the console +//! encodes a comparison function in every sampler (D3D's default, less or +//! equal, when unused). + +/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`, +/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and +/// `D3D12_STATIC_BORDER_COLOR` values. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct StaticSampler { + pub filter: u32, + /// U, V, W. + pub address: [u32; 3], + pub mip_lod_bias: f32, + pub max_anisotropy: u32, + pub comparison: u32, + pub border: u32, + pub min_lod: f32, + pub max_lod: f32, +} + +// The floats come from fixed-point fields: never NaN. +impl Eq for StaticSampler {} + +impl StaticSampler { + /// Decodes the four sampler words. + pub fn from_words(w: [u32; 4]) -> Self { + let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1); + // wrap, mirror, clamp, mirror once; the half-border modes have no + // D3D form and become their nearest. + let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize]; + let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2)); + let reduction = match bits(w[0], 29, 2) { + 1 => 2, + 2 => 3, + _ => 0, + }; + let filter = if mag >= 2 || min >= 2 { + 0x55 | reduction << 7 + } else { + (min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7 + }; + let lod = |v: u32| v as f32 / 256.0; + // Without a mip filter the base level is sampled. + let (min_lod, max_lod) = if mip == 0 { + (0.0, 0.0) + } else { + (lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12))) + }; + StaticSampler { + filter, + address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))), + mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0, + max_anisotropy: 1 << bits(w[0], 9, 3).min(4), + comparison: bits(w[0], 12, 3) + 1, + // shortcut: a custom border colour (type 3, a table entry) becomes + // transparent black; upgrade when a title uses one. + border: bits(w[3], 30, 2) % 3, + min_lod, + max_lod, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn console_compiled_samplers_decode() { + // Words the console compiler wrote for static samplers of known + // descriptions. + let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]); + assert_eq!( + point, + StaticSampler { + filter: 0, + address: [1, 2, 3], + mip_lod_bias: 0.5, + max_anisotropy: 1, + comparison: 4, + border: 2, + min_lod: 1.0, + max_lod: 5.25, + } + ); + let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]); + assert_eq!( + (aniso.filter, aniso.address, aniso.max_anisotropy), + (0x55, [4, 5, 3], 8) + ); + assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0)); + let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]); + assert_eq!( + (compare.filter, compare.address, compare.border), + (0x14, [4, 1, 1], 1) + ); + let minimum = + StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]); + assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5)); + let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]); + assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0)); + let max_aniso = + StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]); + assert_eq!( + ( + max_aniso.filter, + max_aniso.max_anisotropy, + max_aniso.mip_lod_bias + ), + (0x1D5, 16, 15.0) + ); + } +} diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs new file mode 100644 index 000000000..b49bc6def --- /dev/null +++ b/crates/victory-shader/src/emit/shader.rs @@ -0,0 +1,881 @@ +//! 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). + +use super::bitcode::{Attr, Md, Module, Ty, V}; +use super::container::{self, Binding, Psv, SigElement}; + +/// Where the shader reads its user data: `b0` in this space. +pub const USER_DATA_SPACE: u32 = 0; +/// Where immediate samplers are bound: `s<n>` in this space. +pub const SAMPLER_SPACE: u32 = 0; +/// Where root CBVs and SRVs are bound: `b<root parameter index>` and +/// `t<root parameter index>` in this space. +pub const ROOT_CBV_SPACE: u32 = 1; + +/// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that +/// reads buffers through descriptors it picks from the view heap at an +/// index it computes (SM 6.6 dynamic resources): a raw buffer of +/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per +/// element of the buffer view at heap slot `i` (0: none or not a buffer). +/// The console's descriptor holds that stride and its hardware multiplies +/// the element index by it; the program's code does not say it, and the +/// used-resource list only names what tables hold. A shader that has this +/// root SRV also tells the host that the buffer views of the whole heap +/// must be ready when it runs, not only those its tables name. +pub const SLOT_STRIDES: u8 = 255; +/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it. +pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; + +/// Title memory by address (`resource::MEMORY`): console code reads and +/// writes through raw 40-bit addresses it takes from root constants, +/// descriptors and other memory (the ray-tracing structure builder and the +/// programs that walk its structures). The host keeps copies of the title +/// memory shaders use; a shader with such an access finds the copy by the +/// address: +/// +/// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of +/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title +/// address space: the number of the host copy holding that page (0: none +/// yet) and the page's byte offset in that copy; +/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base` +/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself +/// reads zeros and drops writes; +/// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that +/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the +/// host reads afterwards to make those copies for the frames to come. +pub const SLOT_MEMORY: u8 = 254; +/// See [`SLOT_MEMORY`]. +pub const SLOT_FAULTS: u8 = 253; +/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB. +pub const MEMORY_PAGES: u32 = 1 << 21; +/// Dwords of the [`SLOT_FAULTS`] buffer. +pub const MEMORY_FAULTS: u32 = 4096; +/// `RootType::Other` code of a user-data dword the host computes: the view +/// heap slot of the memory copies' views ([`SLOT_MEMORY`]). +pub const USER_MEMORY_BASE: u32 = 0x100; +/// `RootType::Other` code of a user-data dword the host computes: the low +/// 32 bits of the title address of the buffer view at dword `dword` of the +/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1: +/// its bits from 32 up. (Console code reads the address out of a buffer +/// descriptor and uses it as a pointer.) +pub const USER_VIEW_ADDRESS: u32 = 0x101; +/// `RootType::Other` code of a user-data dword the host computes: the +/// bytes (0 to 15) by which the raw view the host binds for the root view +/// of root parameter `slot` begins before the title's address. A raw view +/// begins on 16 bytes of its host buffer; the console's root views begin +/// anywhere (the structure builder's counters sit at addresses ending in +/// 4 and c). The shader adds the dword to every byte offset through that +/// view. Asked for every root UAV, and for the root SRVs of programs with +/// a spilled user-data table. +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 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_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(crate) struct Types { + pub void: Ty, + pub i1: Ty, + pub i32: Ty, + pub f32: Ty, + pub handle: Ty, + pub props: Ty, + pub bind: Ty, + pub cbuf_ret: Ty, + pub res_ret: Ty, +} + +/// What a mesh shader declares beyond its thread-group size. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Mesh { + pub max_vertices: u32, + pub max_primitives: u32, + /// 1 lines, 2 triangles. + pub topology: u8, +} + +/// What a geometry shader declares: triangles in, triangle strips out on +/// stream 0, one instance. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Geometry { + pub max_vertices: u32, +} + +/// The null slot a host view heap keeps at its end when the title's heap did not fit in it +/// (0: no limit). Shaders translated while it is set read that slot for any view index at or +/// past it: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is +/// larger) hung its GPU on reads past the end (GPU-based validation: "descriptor heap index +/// out of bounds"), which AMD's driver forgives. +static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null. +pub fn set_view_heap_limit(null_slot: u32) { + VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed); +} + +pub(crate) struct Shader { + pub m: Module, + pub t: Types, + pub pixel: bool, + pub inputs: Vec<SigElement>, + pub outputs: Vec<SigElement>, + /// A mesh shader's per-primitive outputs. + pub prims: Vec<SigElement>, + /// A mesh shader (`threads` is its thread-group size). + pub mesh: Option<Mesh>, + /// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false. + pub geometry: Option<Geometry>, + /// Dwords of user data the shader reads (0: no user-data buffer). + pub user_data: u32, + /// 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)>, + /// Root UAVs (raw buffers) read or written, likewise. + pub root_uavs: Vec<(u8, V)>, + pub flags: u64, + /// Heap handles made with a non-uniform index. + pub nonuniform_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<u32>, + /// Thread-group shared memory, in dwords. + pub lds_dwords: u32, + lds: Option<V>, + main: V, + pub entry: usize, +} + +impl Shader { + pub fn new(pixel: bool) -> Self { + let mut m = Module::default(); + let void = m.void(); + let i1 = m.int(1); + let i8 = m.int(8); + let i32 = m.int(32); + let f32 = m.float(); + let i8p = m.ptr(i8); + let handle = m.named_struct("dx.types.Handle", vec![i8p]); + let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]); + let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]); + let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]); + let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + let main = m.function("main", main_ty, None, true); + let entry = m.new_block(); + Shader { + m, + t: Types { + void, + i1, + i32, + f32, + handle, + props, + bind, + cbuf_ret, + res_ret, + }, + pixel, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh: None, + geometry: None, + user_data: 0, + samplers: 0, + cmp_samplers: 0, + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + flags: 0, + nonuniform_handles: 0, + threads: None, + wave_size: None, + lds_dwords: 0, + lds: None, + main, + entry, + } + } + + /// The thread-group shared memory: `[lds_dwords x i32]` in address + /// space 3. + pub fn lds(&mut self) -> V { + if let Some(g) = self.lds { + return g; + } + let arr = self.m.array(self.lds_dwords, self.t.i32); + let g = self.m.global("lds", arr, 3); + self.lds = Some(g); + g + } + + /// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`. + pub fn op( + &mut self, + block: usize, + name: &str, + attr: Attr, + ret: Ty, + opcode: u32, + args: &[V], + ) -> V { + 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); + self.m.ptr(fty); + let f = self + .m + .function(&format!("dx.op.{name}"), fty, Some(attr), false); + let mut all = vec![self.m.i32(opcode)]; + all.extend(args); + self.m.call(block, f, all) + } + + /// The handle of the user-data constant buffer, made in the entry block. + pub fn user_data_handle(&mut self) -> V { + let bind = [ + self.m.i32(0), + self.m.i32(0), + self.m.i32(USER_DATA_SPACE), + self.m.i8(2), // CBV + ]; + let bind = self.m.aggregate(self.t.bind, &bind); + let block = self.entry; + let (i, f) = (self.m.i32(0), self.m.bool(false)); + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, i, f], + ); + // The size is known in `finish`, which fixes this placeholder. + self.annotate(block, h, 13, u32::MAX) + } + + /// The handle of the root CBV of root parameter `slot`, made in the + /// entry block. + pub fn root_cbv_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)]; + let bind = 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, 13, 65536); + self.root_cbvs.push((slot, h)); + h + } + + /// The handle of the root SRV (a raw buffer) of root parameter `slot`. + pub fn root_srv_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(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; + self.root_srvs.push((slot, h)); + h + } + + /// The handle of the root UAV (a raw buffer) of root parameter `slot`: + /// `u<slot>` in [`ROOT_CBV_SPACE`]. + pub fn root_uav_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(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, r, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.root_uavs.push((slot, h)); + h + } + + /// The handle of immediate sampler `n` (a comparison sampler when its + /// bit in `cmp_samplers` is set). + pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { + let bind = [ + self.m.i32(n), + self.m.i32(n), + self.m.i32(SAMPLER_SPACE), + self.m.i8(3), // sampler + ]; + let bind = self.m.aggregate(self.t.bind, &bind); + let (i, f) = (self.m.i32(n), self.m.bool(false)); + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, i, f], + ); + let cmp = if self.cmp_samplers >> n & 1 != 0 { + 0x8000 + } else { + 0 + }; + self.annotate(block, h, 14 | cmp, 0) + } + + pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V { + let p = [self.m.i32(props0), self.m.i32(props1)]; + let p = self.m.aggregate(self.t.props, &p); + self.op( + block, + "annotateHandle", + Attr::ReadNone, + self.t.handle, + 216, + &[h, p], + ) + } + + /// A descriptor heap handle, annotated with `props`; `nonuniform` when + /// the index may differ between lanes (`NonUniformResourceIndex`). + pub fn heap_handle( + &mut self, + block: usize, + index: V, + sampler: bool, + nonuniform: bool, + props: (u32, u32), + ) -> V { + // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead + let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) + let index = if !sampler && limit != 0 { + let null = self.m.i32(limit); + let i32t = self.t.i32; + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]); + 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 + // got yet) stays inside the largest heap there is. + // shortcut: not the bound heap's own count, which a title + // heap smaller than 2,048 would need. + let last = self.m.i32(2047); + let i32t = self.t.i32; + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + self.m.tag(v, super::bitcode::Tag::Clamp); + v + } else { + index + }; + self.flags |= if sampler { + flags::SAMPLER_HEAP + } else { + flags::RESOURCE_HEAP + }; + self.nonuniform_handles += u32::from(nonuniform); + let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform)); + let h = self.op( + block, + "createHandleFromHeap", + Attr::ReadNone, + self.t.handle, + 218, + &[index, s, n], + ); + self.annotate(block, h, props.0, props.1) + } + + /// The finished container. + pub fn finish(mut self) -> Vec<u8> { + 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| { + let c = s.m.i32(v); + s.m.md_value(c) + }; + if self.user_data > 0 + || self.samplers > 0 + || !self.root_cbvs.is_empty() + || !self.root_srvs.is_empty() + || !self.root_uavs.is_empty() + { + let empty = self.m.md_str(""); + let mut cbvs = None; + let mut cbv_list = Vec::new(); + if self.user_data > 0 { + let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32); + let ty = self.m.named_struct("UserData", vec![arr]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let ops = vec![ + Some(i32c(&mut self, 0)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, USER_DATA_SPACE)), + Some(i32c(&mut self, 0)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, ud_size)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: USER_DATA_SPACE, + register: 0, + dxil_kind: 13, + }); + } + let blob = self.m.array(16384, self.t.i32); + let ty = self.m.named_struct("RootCbv", vec![blob]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + for (slot, _) in self.root_cbvs.clone() { + let ops = vec![ + Some(i32c(&mut self, cbv_list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 65536)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 13, + }); + } + if !cbv_list.is_empty() { + cbvs = Some(self.m.md_node(cbv_list)); + } + let mut srvs = None; + if !self.root_srvs.is_empty() { + let ty = self + .m + .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let mut list = Vec::new(); + for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { + let ops = vec![ + Some(i32c(&mut self, n as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(i32c(&mut self, 0)), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 4, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 11, + }); + } + srvs = Some(self.m.md_node(list)); + } + let mut uavs = None; + if !self.root_uavs.is_empty() { + let ty = self + .m + .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let no = self.m.bool(false); + let no = self.m.md_value(no); + let mut list = Vec::new(); + for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() { + // Id, variable, name, space, lower bound, range size, + // shape (11: raw buffer), globally coherent, counter, + // rasterizer ordered, no extra properties. + let ops = vec![ + Some(i32c(&mut self, n as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(no), + Some(no), + Some(no), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 7, + 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 > 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 { + let kind = (self.cmp_samplers >> n & 1) as u32; + let ops = vec![ + Some(i32c(&mut self, n)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, SAMPLER_SPACE)), + Some(i32c(&mut self, n)), + Some(i32c(&mut self, 1)), + // Sampler kind: 1 comparison. + Some(i32c(&mut self, kind)), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 1, + space: SAMPLER_SPACE, + register: n, + dxil_kind: 14, + }); + } + samplers = Some(self.m.md_node(list)); + } + resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers])); + // PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs. + bindings.sort_by_key(|b| match b.kind { + 2 => 0, + 1 => 1, + 7 => 3, + _ => 2, + }); + } + if let Some(r) = resources { + self.m.named_md("dx.resources", vec![r]); + } + + let graphics = self.threads.is_none() || self.mesh.is_some(); + if graphics { + // shortcut: every output is declared to depend on every input; the + // exact sets need a dependence pass. Drivers read this state. + let scalars = |els: &[SigElement]| { + els.iter() + .filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols))) + .max() + .unwrap_or(0) + }; + let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs)); + let mut view = vec![ni, no]; + // Mesh shaders have no inputs: then the primitive outputs' count. + if self.mesh.is_some() { + view.push(scalars(&self.prims)); + } + for _ in 0..ni { + for k in 0..no.div_ceil(32) { + let bits = (no - 32 * k).min(32); + view.push(if bits == 32 { + u32::MAX + } else { + (1 << bits) - 1 + }); + } + } + // A geometry shader lists four streams: the other three have + // no outputs. + if self.geometry.is_some() { + view.extend([0, 0, 0]); + } + let arr = self.m.array(view.len() as u32, self.t.i32); + let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect(); + let arr = self.m.aggregate(arr, &elems); + let arr = self.m.md_value(arr); + let view_node = self.m.md_node(vec![Some(arr)]); + self.m.named_md("dx.viewIdState", vec![view_node]); + } + + let sigs = if graphics { + let ins = self.signature_md(self.inputs.clone()); + let outs = self.signature_md(self.outputs.clone()); + let prims = self.signature_md(self.prims.clone()); + Some(self.m.md_node(vec![ins, outs, prims])) + } else { + None + }; + // A pixel shader with an SV_StencilRef output (as DXC collects it). + if self.pixel && self.outputs.iter().any(|o| o.kind == 20) { + self.flags |= flags::STENCIL_REF; + } + // Entry properties: shader flags (tag 0), geometry state (1), + // thread-group size (4), wave size (11). + let mut props = Vec::new(); + if self.flags != 0 { + props.push(i32c(&mut self, 0)); + let i64t = self.m.int(64); + let f = self.m.int_const(i64t, self.flags as i64); + props.push(self.m.md_value(f)); + } + if let Some(g) = self.geometry { + // Input primitive (3: triangles), maximum vertices, stream + // mask, output topology (5: triangle strips), instances. + props.push(i32c(&mut self, 1)); + let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n))); + props.push(self.m.md_node(state.to_vec())); + } + if let Some(threads) = self.threads { + let t = threads.map(|n| Some(i32c(&mut self, n))); + let t = self.m.md_node(t.to_vec()); + match self.mesh { + // Mesh state (tag 9): threads, maximum vertices and + // primitives, topology, payload bytes. + Some(mesh) => { + props.push(i32c(&mut self, 9)); + let state = [ + mesh.max_vertices, + mesh.max_primitives, + mesh.topology.into(), + 0, + ] + .map(|n| Some(i32c(&mut self, n))); + let mut node = vec![Some(t)]; + node.extend(state); + props.push(self.m.md_node(node)); + } + None => { + props.push(i32c(&mut self, 4)); + props.push(t); + } + } + } + if let Some(n) = self.wave_size { + props.push(i32c(&mut self, 11)); + let n = Some(i32c(&mut self, n)); + props.push(self.m.md_node(vec![n])); + } + let props = + (!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect())); + let main = self.m.md_value(self.main); + let name = self.m.md_str("main"); + let entry = self + .m + .md_node(vec![Some(main), Some(name), sigs, resources, props]); + + let ident = self.m.md_str("victory"); + let ident = self.m.md_node(vec![Some(ident)]); + self.m.named_md("llvm.ident", vec![ident]); + let one = i32c(&mut self, 1); + 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]); + 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), + _ if self.geometry.is_some() => ("gs", 2), + (Some(_), _) => ("cs", 5u32), + (None, true) => ("ps", 0), + (None, false) => ("vs", 1), + }; + let name = self.m.md_str(name); + let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]); + self.m.named_md("dx.shaderModel", vec![sm]); + 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()); + dxil.extend(b"DXIL"); + dxil.extend(0x106u32.to_le_bytes()); + dxil.extend(16u32.to_le_bytes()); + dxil.extend((bitcode.len() as u32).to_le_bytes()); + dxil.extend(&bitcode); + + let mut features = 0u64; + if self.flags & flags::STENCIL_REF != 0 { + features |= 0x200; + } + if self.flags & flags::TYPED_UAV_LOADS != 0 { + features |= 0x800; + } + if self.flags & flags::WAVE_OPS != 0 { + features |= 0x4000; + } + if self.flags & flags::INT64 != 0 { + features |= 0x8000; + } + if self.flags & flags::BARYCENTRICS != 0 { + features |= 0x2_0000; + } + if self.flags & flags::RESOURCE_HEAP != 0 { + features |= 0x200_0000; + } + if self.flags & flags::SAMPLER_HEAP != 0 { + features |= 0x400_0000; + } + 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(); + let isg1 = container::signature(&self.inputs, true); + let osg1 = container::signature(&self.outputs, false); + let flag = if self.pixel { + self.outputs.iter().any(|o| (17..=19).contains(&o.kind)) + } else { + self.outputs.iter().any(|o| o.kind == 3) + }; + let psv0 = container::psv(&Psv { + stage: kind as u8, + flag: flag && self.threads.is_none(), + inputs: &self.inputs, + outputs: &self.outputs, + prims: &self.prims, + mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)), + geometry: self.geometry.map(|g| g.max_vertices), + bindings: &bindings, + threads: self.threads.unwrap_or_default(), + wave_size: self.wave_size, + }); + let hash = [0u8; 20]; + let psg1 = container::signature(&self.prims, false); + let mut parts: Vec<(&[u8; 4], &[u8])> = + vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)]; + if self.mesh.is_some() { + parts.push((b"PSG1", &psg1)); + } + parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]); + container::build(&parts) + } + + /// The user-data buffer's annotation carries its size, known only now. + fn fix_user_data_size(&mut self, size: u32) { + let old = [self.m.i32(13), self.m.i32(u32::MAX)]; + let old = self.m.aggregate(self.t.props, &old); + let new = [self.m.i32(13), self.m.i32(size)]; + let new = self.m.aggregate(self.t.props, &new); + self.m.replace_const(old, new); + } + + fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> { + if elements.is_empty() { + return None; + } + let mut list = Vec::new(); + for (id, e) in elements.iter().enumerate() { + let c32 = |s: &mut Self, v: u32| { + let c = s.m.i32(v); + Some(s.m.md_value(c)) + }; + let c8 = |s: &mut Self, v: u8| { + let c = s.m.i8(v); + Some(s.m.md_value(c)) + }; + let idx = c32(self, e.index); + let indices = Some(self.m.md_node(vec![idx])); + let usage = if e.usage != 0 { + let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage))); + Some(self.m.md_node(vec![tag, mask])) + } else { + None + }; + let ops = vec![ + c32(self, id as u32), + Some(self.m.md_str(&e.name)), + c8(self, e.comp), + c8(self, e.kind), + indices, + c8(self, e.interp), + c32(self, 1), + c8(self, e.cols), + c32(self, e.row.unwrap_or(u32::MAX)), + c8(self, if e.row.is_some() { e.col } else { u8::MAX }), + usage, + ]; + list.push(Some(self.m.md_node(ops))); + } + Some(self.m.md_node(list)) + } +} diff --git a/crates/victory-shader/src/emit/threading.rs b/crates/victory-shader/src/emit/threading.rs new file mode 100644 index 000000000..01bd4feba --- /dev/null +++ b/crates/victory-shader/src/emit/threading.rs @@ -0,0 +1,218 @@ +//! Jump threading for uniform diamonds. One arm can set a flag that fixes +//! the join's next branch. Registers recycled on that arm then never reach +//! the other successor, even if an ordinary SSA phi joins their values. +use crate::gfx10::{Fields, Operand, Valu}; +use crate::ir::{Exit, Program, Reg, Value}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; +use std::collections::HashMap; + +fn plain(v: &Valu) -> bool { + v.abs == 0 + && v.neg == 0 + && v.opsel == 0 + && !v.clamp + && v.omod == 0 + && v.sdwa.is_none() + && v.dpp.is_none() +} + +fn immediate(op: Operand) -> Option<u32> { + match op { + Operand::Const(c) => crate::resource::inline(c), + Operand::Literal(n) => Some(n), + _ => None, + } +} + +pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> { + let mut constants = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + if inst.name() == "v_mov_b32" + && st.guards[b][i].is_none() + && let Fields::Valu(v) = &inst.fields + && plain(v) + && let [src] = v.src.as_slice() + && let Some(word) = immediate(*src) + && let [(_, dst)] = inst.writes.as_slice() + { + constants.insert(*dst, word); + } + } + } + let mut edges = Vec::new(); + for (join, block) in p.blocks.iter().enumerate() { + let LaneExit::Branch { + when, + taken, + not_taken, + } = st.exits[join] + else { + continue; + }; + if when == Bool::TRUE || when == Bool::FALSE { + continue; + } + // Keep memory accesses and wave operations at their original + // reconvergence point. Only duplicate scalar ALU and comparisons. + if !block.insts.iter().all(|i| match &i.fields { + Fields::Sop { .. } => true, + Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"), + Fields::Valu(_) => i.name().starts_with("v_cmp_"), + _ => false, + }) { + continue; + } + let [a, b] = block.preds.as_slice() else { + continue; + }; + // A triangle has a direct edge from the fork to the join. A full + // diamond has an unconditional jump at the end of each arm. + let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() { + &[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork), + _ => None, + }; + let fork = match (arm_from(*a), arm_from(*b)) { + (Some(f), Some(g)) if f == g => f, + (_, Some(f)) if f == *a => f, + (Some(f), _) if f == *b => f, + _ => continue, + }; + if fork == join || a == b { + continue; + } + let LaneExit::Branch { when: entry, .. } = st.exits[fork] else { + continue; + }; + if !st + .bools + .support(entry) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { + continue; + } + for (edge, &pred) in block.preds.iter().enumerate() { + let value = |v: Value| { + let input = block + .phis + .iter() + .find(|p| p.value == v) + .map_or(v, |p| p.args[edge]); + constants.get(&input).copied() + }; + // Restrict the branch's decision diagram to known comparisons. + // Unknown tests stop the proof. Keep the original join for the + // other arm, which may still go either way. + let mut cond = when; + while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) { + let Some(inst) = block + .insts + .iter() + .find(|i| i.writes.iter().any(|&(_, v)| v == id)) + else { + break; + }; + let Fields::Valu(v) = &inst.fields else { break }; + let [left, right] = v.src.as_slice() else { + break; + }; + let operand = |op| match op { + Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?), + _ => immediate(op), + }; + let (Some(x), Some(y)) = (operand(*left), operand(*right)) else { + break; + }; + if !plain(v) { + break; + } + let yes = match inst.name() { + "v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y, + "v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y, + _ => break, + }; + cond = if yes { hi } else { lo }; + } + if cond == Bool::TRUE || cond == Bool::FALSE { + edges.push(( + pred, + join, + if cond == Bool::TRUE { taken } else { not_taken }, + )); + break; + } + } + } + edges +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir; + use crate::structure; + + // s8 initially holds a descriptor address. One arm overwrites it with + // a buffer load and sets v1. Only that arm can use s8 as the stored value. + const WORDS: [u32; 19] = [ + 0xbe810380, // s1 = 0 (table address high) + 0xf4080200, 0xfa000000, // load SRV into s[8:11] + 0xf4080300, 0xfa000020, // load UAV into s[12:15] + 0x7e020280, // v1 = 0 + 0xbf068002, 0xbf850003, // if s2 == 0, jump to join + 0xf4200204, 0xfa00000c, // s8 = buffer.Load(12) + 0x7e020281, // v1 = 1 + 0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant + 0x7e060208, 0xbf820001, // v3 = s8, jump to store + 0x7e060293, // constant: v3 = 19 + 0xe0700000, 0x80030300, // store v3 at byte 0 + 0xbf810000, // end + ]; + + fn program(words: &[u32]) -> Program { + ir::build( + &words + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect::<Vec<_>>(), + false, + 4, + ) + .unwrap() + } + + #[test] + fn only_the_buffer_load_reaches_the_numeric_read() { + let p = program(&WORDS); + let st = structure::structure(&p).unwrap(); + let edges = constant_edges(&p, &st); + assert_eq!(edges, [(0, 2, 4)]); + let p = ir::thread_edges(&p, &edges).unwrap(); + let load = &p.blocks[1].insts[0]; + assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8))); + assert_eq!( + p.blocks[0].exit, + Exit::Branch { + taken: 6, + not_taken: 1 + } + ); + assert_eq!(p.blocks[6].exit, Exit::Jump(4)); + assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len()); + } + + #[test] + fn leaves_unknown_flags_and_divergent_forks_alone() { + let mut words = WORDS; + words[5] = 0x7e020202; // v1 = s2 + words[10] = 0x7e020203; // v1 = s3 + let p = program(&words); + assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty()); + let mut words = WORDS; + words[6] = 0x7d840080; // compare 0 with lane-dependent v0 + words[7] = 0xbf870003; // branch on VCC + let p = program(&words); + assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty()); + } +} diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs new file mode 100644 index 000000000..32171c748 --- /dev/null +++ b/crates/victory-shader/src/emit/validator.rs @@ -0,0 +1,221 @@ +//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the +//! offline batch. Translated shaders do not need it: they carry the +//! container hash we compute (`container::hash`). +//! +//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's +//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it. + +use std::ffi::c_void; +use std::path::PathBuf; + +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; + +type Hresult = i32; + +#[repr(C)] +struct Guid(u32, u16, u16, [u8; 8]); + +const CLSID_DXC_VALIDATOR: Guid = Guid( + 0x8ca3_e215, + 0xf728, + 0x4cf3, + [0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1], +); +const IID_IDXC_VALIDATOR: Guid = Guid( + 0xa6e8_2bd2, + 0x1fd7, + 0x4826, + [0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a], +); +/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass. +const IN_PLACE_EDIT: u32 = 1; + +type CreateInstance = + unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult; + +/// COM object: a pointer to a table of method pointers. +type Object = *mut *const usize; + +unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F { + // SAFETY: the caller names a slot of the object's interface. + unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) } +} + +unsafe fn release(obj: Object) { + if !obj.is_null() { + // SAFETY: slot 2 of every COM interface is Release. + unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) }; + } +} + +/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release, +/// GetBufferPointer, GetBufferSize. Lives on the caller's stack. +#[repr(C)] +struct Blob { + vtable: *const BlobVtable, + data: *mut u8, + len: usize, +} + +/// IUnknown and IDxcBlob, as raw GUID bytes. +const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46]; +const IDXC_BLOB: [u8; 16] = [ + 0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02, +]; + +unsafe extern "system" fn blob_qi( + this: *mut Blob, + iid: *const [u8; 16], + out: *mut *mut c_void, +) -> Hresult { + // SAFETY: the validator passes valid pointers. + unsafe { + if *iid == IUNKNOWN || *iid == IDXC_BLOB { + *out = this.cast(); + 0 + } else { + *out = std::ptr::null_mut(); + 0x8000_4002_u32 as i32 // E_NOINTERFACE + } + } +} +unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 { + 1 +} +unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 { + // SAFETY: `this` is our blob. + unsafe { (*this).data } +} +unsafe extern "system" fn blob_len(this: *mut Blob) -> usize { + // SAFETY: `this` is our blob. + unsafe { (*this).len } +} + +#[repr(C)] +struct BlobVtable { + qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult, + add_ref: unsafe extern "system" fn(*mut Blob) -> u32, + release: unsafe extern "system" fn(*mut Blob) -> u32, + ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8, + len: unsafe extern "system" fn(*mut Blob) -> usize, +} + +static BLOB_VTABLE: BlobVtable = BlobVtable { + qi: blob_qi, + add_ref: blob_ref, + release: blob_ref, + ptr: blob_ptr, + len: blob_len, +}; + +pub struct Validator { + object: Object, +} + +// SAFETY: the validator object is free-threaded (DXC's validator has no +// thread affinity); calls are serialised by `&mut self`. +unsafe impl Send for Validator {} + +impl Validator { + /// Where `dxil.dll` is looked for. + pub fn default_path() -> Option<PathBuf> { + if let Some(p) = std::env::var_os("VICTORY_DXIL") { + return Some(p.into()); + } + let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin"); + let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits) + .ok()? + .filter_map(Result::ok) + .map(|e| e.path().join(r"x64\dxil.dll")) + .filter(|p| p.exists()) + .collect(); + versions.sort(); + versions.pop() + } + + /// Loads `path`'s validator (or `dxil.dll` from the DLL search path). + pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> { + let name: Vec<u16> = 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 {}", String::from_utf16_lossy(&name))); + } + 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(), + }) + } + } + + /// Validates `container` and signs it in place; the error text if it + /// is rejected. + pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> { + let mut blob = Blob { + vtable: &BLOB_VTABLE, + data: container.as_mut_ptr(), + len: container.len(), + }; + // SAFETY: IDxcValidator::Validate (slot 3) with our blob; then + // IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and + // IDxcBlob GetBufferPointer (3) / GetBufferSize (4). + unsafe { + let mut result: Object = std::ptr::null_mut(); + let validate: unsafe extern "system" fn( + Object, + *mut Blob, + u32, + *mut Object, + ) -> Hresult = method(self.object, 3); + let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result); + if hr < 0 || result.is_null() { + return Err(format!("Validate failed: {hr:#x}")); + } + let mut status = 0; + let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult = + method(result, 3); + get_status(result, &mut status); + let mut text = String::new(); + if status < 0 { + let mut errors: Object = std::ptr::null_mut(); + let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult = + method(result, 5); + 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 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() { + text = format!("rejected ({status:#x})"); + } + } + release(result); + if status < 0 { Err(text) } else { Ok(()) } + } + } +} + +impl Drop for Validator { + fn drop(&mut self) { + // SAFETY: we own one reference. + unsafe { release(self.object) }; + } +} diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs new file mode 100644 index 000000000..5072d6c51 --- /dev/null +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -0,0 +1,1266 @@ +//! End-to-end tests of synthetic GFX10 VALU shaders lowered to DXIL, validated +//! by `dxil.dll` when present, and executed on the host GPU and WARP. +//! +//! 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`, 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}; +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 +} + +/// SOP2 `op sdst, src0, src1`. +const fn sop2(op: u8, sdst: u8, src0: u8, src1: u8) -> u32 { + 0x8000_0000 + | (op as u32 & 0x7F) << 23 + | (sdst as u32 & 0x7F) << 16 + | (src1 as u32) << 8 + | src0 as u32 +} + +/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], 0` (soffset = null). +const fn s_load_dwordx4(dst: u8, base: u8) -> [u32; 2] { + [ + 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), + 125 << 25, + ] +} + +/// VOP1 `op vdst, src0` (`src0`: 0..105 = SGPR, 256..511 = VGPR). +const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) +} + +/// 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 + | (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, + ] +} + +/// MUBUF `buffer_store_dword vdata, off, s[srsrc:srsrc+3], 0 offset:byte_off`. +const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] { + [ + 0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF), + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8, + ] +} + +const fn sgpr(n: u8) -> u16 { + n as u16 +} + +const fn vgpr(n: u8) -> u16 { + 256 + n as u16 +} + +/// Builds and lowers a 1-thread synthetic RDNA2 compute shader that receives +/// 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_cs(body, 1, 0) +} + +/// [`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 + 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(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + 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![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: (5 << 1) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4 + threads: [threads, 1, 1], + }), + code, + }; + + 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, + }) + .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, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + }; + + 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 +} + +/// One GPU test at a time. With these tests on the hardware adapter and WARP +/// from several test threads at once, now and then none of their dispatches +/// ever completes and the test binary hangs; and two GPU tests at once on +/// WARP can end the test process with an access violation. Other GPU test +/// modules take this lock too. +pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for +/// each 4-dword input set and invokes `check(backend, case_index, inputs, result_dword)`. +fn run_cases( + shader: &HostShader, + cases: &[[u32; 4]], + check: impl FnMut(&str, usize, [u32; 4], u32), +) { + run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check); +} + +fn run_cases_on( + shader: &HostShader, + cases: &[[u32; 4]], + 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 devices { + 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 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 && 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 { + (bits & 0x7FFF) > 0x7C00 +} + +fn f16_to_f32(bits: u16) -> f32 { + let sign = u32::from(bits >> 15) << 31; + let exp = (bits >> 10) & 0x1F; + let mant = bits & 0x3FF; + let f32_bits = match exp { + 0 => { + if mant == 0 { + sign + } else { + let mut m = u32::from(mant); + let mut e = 127 - 14; + while (m & 0x400) == 0 { + m <<= 1; + e -= 1; + } + sign | (e << 23) | ((m & 0x3FF) << 13) + } + } + 0x1F => sign | (0xFF << 23) | (u32::from(mant) << 13), + _ => sign | ((u32::from(exp) + 112) << 23) | (u32::from(mant) << 13), + }; + f32::from_bits(f32_bits) +} + +#[test] +fn packed_add_selects_halves_of_inline_constants() { + // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. + // The same GFX10 source field (248) has a different bit pattern for a + // packed floating-point and a packed integer instruction. + let cases = [ + // v_pk_add_f16 v0, 0x3118, v1 + ([0xcc0f4000, 0x1a0202f8], 0x0000_3118), + // v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice) + ([0xcc0f4000, 0x120202f8], 0x3118_3118), + // v_pk_add_u16 v0, 0x3e22f983, v1 + ([0xcc0a4000, 0x1a0202f8], 0x3e22_f983), + ]; + for (words, expected) in cases { + let shader = build_valu_cs(&words); + run_cases(&shader, &[[0; 4]], |backend, _, _, got| { + assert_eq!(got, expected, "{backend}: {words:08x?}"); + }); + } +} + +#[test] +fn v_med3_f32_matches_rdna2_with_nan() { + // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) + let shader = build_valu_cs(&vop3(0x157, 0, vgpr(1), vgpr(2), vgpr(3))); + let nan = f32::NAN.to_bits(); + let f = f32::to_bits; + + let cases: &[([u32; 4], Option<f32>)] = &[ + // Normal medians (all orderings). + ([f(1.0), f(2.0), f(3.0), 0], Some(2.0)), + ([f(3.0), f(1.0), f(2.0), 0], Some(2.0)), + ([f(-5.0), f(0.0), f(5.0), 0], Some(0.0)), + ([f(1.0), f(1.0), f(2.0), 0], Some(1.0)), + // One NaN: RDNA2 returns min3 of the non-NaN operands. + ([f(1.0), f(2.0), nan, 0], Some(1.0)), + ([nan, f(1.0), f(0.0), 0], Some(0.0)), + ([nan, f(0.0), f(1.0), 0], Some(0.0)), + ([f(2.0), nan, f(1.0), 0], Some(1.0)), + ([f(-3.0), nan, f(4.0), 0], Some(-3.0)), + // Two NaNs: returns the sole non-NaN operand. + ([nan, f(5.0), nan, 0], Some(5.0)), + ([nan, nan, f(-2.0), 0], Some(-2.0)), + ([f(7.0), nan, nan, 0], Some(7.0)), + // Three NaNs: returns NaN. + ([nan, nan, nan, 0], None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert_eq!( + got_f, + want, + "{backend}: v_med3_f32({:?}, {:?}, {:?}) = {got_f} ({got:#010x}), want {want}", + f32::from_bits(inp[0]), + f32::from_bits(inp[1]), + f32::from_bits(inp[2]), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_med3_f32(NaN, NaN, NaN) = {got_f} ({got:#010x}), want NaN", + ), + } + }); +} + +/// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and +/// FMin compare and select, which can give either zero. +#[test] +fn max_and_min_order_negative_zero_below_positive_zero() { + let (pz, nz) = (0_u32, 0x8000_0000_u32); + // Each case has a -0 and a +0 among its first two operands. + let cases = [ + [nz, pz, nz, 0], + [pz, nz, nz, 0], + [nz, pz, pz, 0], + [pz, nz, pz, 0], + ]; + let ops = [ + ("v_max_f32", 0x110, pz), + ("v_min_f32", 0x10F, nz), + ("v_max3_f32", 0x154, pz), + ("v_min3_f32", 0x151, nz), + ]; + for (name, op, want) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + assert_eq!(got, want, "{backend}: {name} {inp:x?}"); + }); + } +} + +#[test] +fn v_med3_f16_matches_rdna2_with_nan() { + // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) + let shader = build_valu_cs(&vop3(0x357, 0, vgpr(1), vgpr(2), vgpr(3))); + let h0 = 0x0000u32; // 0.0 + let h1 = 0x3C00u32; // 1.0 + let h2 = 0x4000u32; // 2.0 + let h3 = 0x4200u32; // 3.0 + let h5 = 0x4500u32; // 5.0 + let hn2 = 0xC000u32; // -2.0 + let nan = 0x7E00u32; + + let cases: &[([u32; 4], Option<u16>)] = &[ + ([h1, h2, h3, 0], Some(h2 as u16)), + ([hn2, h0, h3, 0], Some(h0 as u16)), + ([h1, h2, nan, 0], Some(h1 as u16)), + ([nan, h1, h0, 0], Some(h0 as u16)), + ([nan, h0, h1, 0], Some(h0 as u16)), + ([h2, nan, h1, 0], Some(h1 as u16)), + ([nan, h5, nan, 0], Some(h5 as u16)), + ([nan, nan, nan, 0], None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => assert_eq!( + got_h, want, + "{backend}: v_med3_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_med3_f16(NaN, NaN, NaN) = {got_h:#06x}, want NaN", + ), + } + }); +} + +/// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when +/// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware). +#[test] +fn v_cmp_lg_is_false_for_nan() { + // v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3); + // v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101) + let nan = f32::NAN.to_bits(); + let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits()); + let f = f32::to_bits; + let f32_cases: &[([u32; 4], u32)] = &[ + ([f(1.0), f(2.0), 0, 0], 1), + ([f(2.0), f(1.0), 0, 0], 1), + ([f(1.0), f(1.0), 0, 0], 0), + ([f(0.0), f(-0.0), 0, 0], 0), + ([inf, ninf, 0, 0], 1), + ([inf, inf, 0, 0], 0), + ([nan, f(1.0), 0, 0], 0), + ([f(1.0), nan, 0, 0], 0), + ([nan, nan, 0, 0], 0), + ([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN + ]; + let f16_cases: &[([u32; 4], u32)] = &[ + ([0x3C00, 0x4000, 0, 0], 1), + ([0x4000, 0x3C00, 0, 0], 1), + ([0x3C00, 0x3C00, 0, 0], 0), + ([0x0000, 0x8000, 0, 0], 0), + ([0x7C00, 0xFC00, 0, 0], 1), + ([0x7E00, 0x3C00, 0, 0], 0), + ([0x3C00, 0x7E00, 0, 0], 0), + ([0x7E00, 0x7E00, 0, 0], 0), + ([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN + ([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read + ]; + for (op, what, cases) in [ + (0x005u16, "v_cmp_lg_f32", f32_cases), + (0x0cd, "v_cmp_lg_f16", f16_cases), + ] { + let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec(); + body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20))); + let shader = build_valu_cs(&body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } +} + +#[test] +fn v_fract_f32_never_returns_one() { + // v_fract_f32 v0, v1 (VOP1 opcode 0x020) + let shader = build_valu_cs(&[vop1(0x020, 0, vgpr(1))]); + let f = f32::to_bits; + let below_one = 0x3F7F_FFFFu32; + + let cases: &[(u32, Option<u32>)] = &[ + // Tiny negatives: must clamp strictly below 1.0 (not 0x3f800000). + (f(-1e-10), Some(below_one)), + (f(-1e-8), Some(below_one)), + (f(-2.0f32.powi(-25)), Some(below_one)), + (f(-2.0f32.powi(-24)), Some(below_one)), + // Normal values. + (f(0.0), Some(f(0.0))), + (f(-0.0), Some(f(0.0))), + (f(0.25), Some(f(0.25))), + (f(3.75), Some(f(0.75))), + (f(-0.25), Some(f(0.75))), + (f(-3.25), Some(f(0.75))), + (f(1.0), Some(f(0.0))), + (f(-1.0), Some(f(0.0))), + // Non-finite inputs yield NaN. + (f(f32::NAN), None), + (f(f32::INFINITY), None), + (f(f32::NEG_INFINITY), None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + match expect { + Some(want) => assert_eq!( + got, + want, + "{backend}: v_fract_f32({:?} / {:#010x}) = {got:#010x} ({:?}), want {want:#010x}", + f32::from_bits(inp[0]), + inp[0], + f32::from_bits(got), + ), + None => assert!( + f32::from_bits(got).is_nan(), + "{backend}: v_fract_f32({:?}) = {got:#010x}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); +} + +#[test] +fn v_fract_f16_never_returns_one() { + // v_fract_f16 v0, v1 (VOP1 opcode 0x05f) + let shader = build_valu_cs(&[vop1(0x05f, 0, vgpr(1))]); + let below_one = 0x3BFFu16; // 1.0 - 2^-11 + + assert_eq!(f16_to_f32(0x9400), -2.0f32.powi(-10)); + assert_eq!(f16_to_f32(0x9000), -2.0f32.powi(-11)); + assert_eq!(f16_to_f32(0x8C00), -2.0f32.powi(-12)); + + let cases: &[(u16, Option<u16>)] = &[ + // Negatives in (-2^-11, 0): must clamp to 0x3BFF, never 0x3C00 (1.0). + (0x8C00, Some(below_one)), // -2^-12 + (0x8400, Some(below_one)), // -2^-14 + (0x8001, Some(below_one)), // -2^-24 (smallest negative f16 subnormal) + (0x9000, Some(below_one)), // -2^-11 (exact 1 - 2^-11 = 0x3BFF) + (0x9400, Some(0x3BFE)), // -2^-10 (exact 1 - 2^-10 = 0x3BFE) + // Normal values. + (0x0000, Some(0x0000)), // 0.0 -> 0.0 + (0x3400, Some(0x3400)), // 0.25 -> 0.25 + (0xB400, Some(0x3A00)), // -0.25 -> 0.75 + (0x4300, Some(0x3800)), // 3.5 -> 0.5 + (0x3C00, Some(0x0000)), // 1.0 -> 0.0 + // Non-finite inputs yield NaN. + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + + let inputs: Vec<[u32; 4]> = cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => assert_eq!( + got_h, want, + "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want {want:#06x}", + inp[0], + ), + None => assert!( + is_f16_nan(got_h), + "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); +} + +/// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or +/// 65535, round the exact product to nearest even; NaN gives 0. +fn cvt_norm16_reference(bits: u16, signed: bool) -> u16 { + let x = f16_to_f32(bits); + if x.is_nan() { + return 0; + } + let (lo, scale) = if signed { + (-1.0, 32767.0) + } else { + (0.0, 65535.0) + }; + // f64 holds the product of an f16 and a 16-bit scale exactly. + let p = f64::from(x.clamp(lo, 1.0)) * scale; + p.round_ties_even() as i32 as u16 +} + +#[test] +fn v_cvt_norm_i16_and_u16_f16_round_the_exact_product() { + // Every 251st f16 pattern, plus the values where an f32 product would + // round before the rounding to an integer, ties, and the edges. + let mut bits: Vec<u16> = (0..=u16::MAX).step_by(251).collect(); + bits.extend([ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF, + 0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, + 0x3A9B, 0xBA9B, 0x2E66, 0x1400, + ]); + for (op, signed, what) in [ + (0x063u16, true, "v_cvt_norm_i16_f16"), + (0x064, false, "v_cvt_norm_u16_f16"), + ] { + // v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0. + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = bits.iter().map(|&b| [u32::from(b), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = cvt_norm16_reference(bits[i], signed); + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + bits[i], + ); + }); + } +} + +#[test] +fn v_sin_and_v_cos_f32_reduce_large_turns() { + let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]); + let cos_shader = build_valu_cs(&[vop1(0x036, 0, vgpr(1))]); + let f = f32::to_bits; + let half_sqrt2 = std::f32::consts::FRAC_1_SQRT_2; + + let sin_cases: &[(f32, Option<f32>)] = &[ + (0.0, Some(0.0)), + (0.25, Some(1.0)), + (255.0, Some(0.0)), + (255.25, Some(1.0)), + (255.5, Some(0.0)), + (-255.25, Some(-1.0)), + (10_000.125, Some(half_sqrt2)), + (f32::NAN, None), + (f32::INFINITY, None), + (f32::NEG_INFINITY, None), + ]; + let sin_inputs: Vec<[u32; 4]> = sin_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect(); + run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| { + let expect = sin_cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert!( + (got_f - want).abs() < 1e-5, + "{backend}: v_sin_f32({}) = {got_f}, want {want} (err = {})", + f32::from_bits(inp[0]), + (got_f - want).abs(), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_sin_f32({}) = {got_f}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); + + let cos_cases: &[(f32, Option<f32>)] = &[ + (0.0, Some(1.0)), + (0.25, Some(0.0)), + (255.0, Some(1.0)), + (255.25, Some(0.0)), + (255.5, Some(-1.0)), + (-255.5, Some(-1.0)), + (10_000.125, Some(half_sqrt2)), + (f32::NAN, None), + (f32::INFINITY, None), + (f32::NEG_INFINITY, None), + ]; + let cos_inputs: Vec<[u32; 4]> = cos_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect(); + run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| { + let expect = cos_cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert!( + (got_f - want).abs() < 1e-5, + "{backend}: v_cos_f32({}) = {got_f}, want {want} (err = {})", + f32::from_bits(inp[0]), + (got_f - want).abs(), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_cos_f32({}) = {got_f}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); + + // Main's `trig_turns` preserves sin(-0.0) = -0.0 and produces exact +0.0 at + // half-turns (sin) and quarter-turns (cos). + let exact_sin: &[(u32, u32)] = &[ + (0x8000_0000, 0x8000_0000), // sin(-0.0) = -0.0 + (f(255.0), 0), // sin(255.0) = +0.0 + (f(255.5), 0), // sin(255.5) = +0.0 + ]; + let exact_sin_in: Vec<[u32; 4]> = exact_sin.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&sin_shader, &exact_sin_in, |backend, i, inp, got| { + let want = exact_sin[i].1; + assert_eq!( + got, want, + "{backend}: v_sin_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + let exact_cos: &[(u32, u32)] = &[ + (f(0.25), 0), // cos(0.25) = +0.0 + (f(255.25), 0), // cos(255.25) = +0.0 + ]; + let exact_cos_in: Vec<[u32; 4]> = exact_cos.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&cos_shader, &exact_cos_in, |backend, i, inp, got| { + let want = exact_cos[i].1; + assert_eq!( + got, want, + "{backend}: v_cos_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); +} + +#[test] +fn v_cvt_u16_and_i16_f16_saturate() { + // v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053). + let cases: &[(u16, u16, u16)] = &[ + // (f16 input, u16 result, i16 result) + (0x0000, 0, 0), // 0 + (0x8000, 0, 0), // -0 + (0x3E00, 1, 1), // 1.5 -> 1 (toward zero) + (0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1 + (0x57D0, 125, 125), // 125.0 + (0x7800, 32768, 32767), // 32768 saturates i16 + (0x77FF, 32752, 32752), // 32752, the largest f16 below 32768 + (0xF800, 0, 0x8000), // -32768 fits i16 + (0xF801, 0, 0x8000), // -32800 saturates i16 + (0x7BFF, 65504, 32767), // max finite f16 + (0xFBFF, 0, 0x8000), // -65504 + (0x7C00, 0xFFFF, 32767), // +inf + (0xFC00, 0, 0x8000), // -inf + (0x7E00, 0, 0), // NaN + (0xFE00, 0, 0), // -NaN + (0x0001, 0, 0), // smallest subnormal + ]; + for (op, what, pick) in [ + (0x052u16, "v_cvt_u16_f16", 0usize), + (0x053, "v_cvt_i16_f16", 1), + ] { + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = if pick == 0 { cases[i].1 } else { cases[i].2 }; + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + cases[i].0, + ); + }); + } +} + +#[test] +fn v_sin_and_v_cos_f16_reduce_large_turns() { + let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); + let cos_shader = build_valu_cs(&[vop1(0x061, 0, vgpr(1))]); + + // Sanity-check the f16 bit encodings of large turns. + assert_eq!(f16_to_f32(0x5BF8), 255.0); + assert_eq!(f16_to_f32(0x5BFA), 255.25); + assert_eq!(f16_to_f32(0x5BFC), 255.5); + assert_eq!(f16_to_f32(0x7BFF), 65504.0); + + let sin_cases: &[(u16, Option<f32>)] = &[ + (0x5BF8, Some(0.0)), // 255.0 + (0x5BFA, Some(1.0)), // 255.25 + (0x5BFC, Some(0.0)), // 255.5 + (0xDBFA, Some(-1.0)), // -255.25 + (0x7BFF, Some(0.0)), // 65504.0 (largest finite f16, exact integer) + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + let sin_inputs: Vec<[u32; 4]> = sin_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| { + let expect = sin_cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => { + let got_f = f16_to_f32(got_h); + assert!( + (got_f - want).abs() < 1e-3, + "{backend}: v_sin_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}", + inp[0], + f16_to_f32(inp[0] as u16), + ); + } + None => assert!( + is_f16_nan(got_h), + "{backend}: v_sin_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); + + let cos_cases: &[(u16, Option<f32>)] = &[ + (0x5BF8, Some(1.0)), // 255.0 + (0x5BFA, Some(0.0)), // 255.25 + (0x5BFC, Some(-1.0)), // 255.5 + (0x7BFF, Some(1.0)), // 65504.0 (largest finite f16, exact integer) + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + let cos_inputs: Vec<[u32; 4]> = cos_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| { + let expect = cos_cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => { + let got_f = f16_to_f32(got_h); + assert!( + (got_f - want).abs() < 1e-3, + "{backend}: v_cos_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}", + inp[0], + f16_to_f32(inp[0] as u16), + ); + } + None => assert!( + is_f16_nan(got_h), + "{backend}: v_cos_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); +} + +#[test] +fn bfe_signed_and_unsigned_match_rdna2() { + // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) + let v_signed = build_valu_cs(&vop3(0x149, 0, vgpr(1), vgpr(2), vgpr(3))); + // v_bfe_u32 v0, v1, v2, v3 (VOP3 opcode 0x148) + let v_unsigned = build_valu_cs(&vop3(0x148, 0, vgpr(1), vgpr(2), vgpr(3))); + // s_bfe_i32 s6, s0, s1 (SOP2 opcode 0x28: s1 = off[4:0] | width[22:16]); v_mov_b32 v0, s6 + let s_signed = build_valu_cs(&[sop2(0x28, 6, 0, 1), vop1(0x001, 0, sgpr(6))]); + + let signed_cases: &[([u32; 4], u32)] = &[ + // Field crosses bit 31: extends from bit 31. + ([0xd2f9_0159, 28, 16, 0], 0xffff_fffd), + ([0x8000_0000, 31, 4, 0], 0xffff_ffff), + ([0x7000_0000, 28, 8, 0], 0x0000_0007), + // Normal fields inside 32 bits. + ([0x0000_0080, 4, 4, 0], 0xffff_fff8), + ([0x0000_0070, 4, 4, 0], 0x0000_0007), + // Edge widths: 0 yields 0; v_bfe masks width to 5 bits (32 -> 0), + // while 31 extracts all remaining bits from offset 4. + ([0xffff_ffff, 4, 0, 0], 0), + ([0x8000_0000, 4, 31, 0], 0xf800_0000), + ]; + let v_in: Vec<[u32; 4]> = signed_cases.iter().map(|c| c.0).collect(); + run_cases(&v_signed, &v_in, |backend, i, inp, got| { + let want = signed_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_bfe_i32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + // v_bfe_i32 width is 5-bit (src2[4:0]), so width=32 wraps to 0. + run_cases( + &v_signed, + &[[0x8000_0000, 4, 32, 0]], + |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: v_bfe_i32 width 32 should mask to 0"); + }, + ); + + // s_bfe_i32 width is 7-bit (src1[22:16]), so width=32 keeps all 32 bits. + let mut s_cases = signed_cases.to_vec(); + s_cases.push(([0x8000_0000, 4, 32, 0], 0xf800_0000)); + let s_in: Vec<[u32; 4]> = s_cases + .iter() + .map(|&(inp, _)| [inp[0], (inp[1] & 31) | ((inp[2] & 0x7F) << 16), 0, 0]) + .collect(); + run_cases(&s_signed, &s_in, |backend, i, inp, got| { + let want = s_cases[i].1; + assert_eq!( + got, want, + "{backend}: s_bfe_i32({:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], + ); + }); + + let unsigned_cases: &[([u32; 4], u32)] = &[ + ([0xd2f9_0159, 28, 16, 0], 0x0000_000d), + ([0x8000_0000, 31, 4, 0], 0x0000_0001), + ([0xffff_ffff, 4, 0, 0], 0), + ([0x8000_0000, 4, 31, 0], 0x0800_0000), + ]; + let u_in: Vec<[u32; 4]> = unsigned_cases.iter().map(|c| c.0).collect(); + run_cases(&v_unsigned, &u_in, |backend, i, inp, got| { + let want = unsigned_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_bfe_u32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); +} + +#[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<u32> = 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 + let cmp_lo = build_valu_cs(&[ + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0], + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1). + let [mut w0, mut w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0); + w0 |= 1 << 11; // opsel[0] = 1 (high half) + w1 |= 1 << 29; // neg[0] = 1 + let cmp_hi_neg = build_valu_cs(&[ + w0, + w1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + + // All 10 IEEE-754 binary16 classes: bit k corresponds to class k. + let classes: &[(u32, u32)] = &[ + (0x7C01, 0), // sNaN (+sNaN, quiet bit 0x0200 clear) + (0xFDFF, 0), // -sNaN (sign ignored for NaNs) + (0x7E00, 1), // +qNaN + (0xFE01, 1), // -qNaN + (0xFC00, 2), // -inf + (0xBC00, 3), // -normal (-1.0) + (0x8001, 4), // -denormal + (0x8000, 5), // -0.0 + (0x0000, 6), // +0.0 + (0x0001, 7), // +denormal + (0x3C00, 8), // +normal (+1.0) + (0x7C00, 9), // +inf + ]; + let mut cases = Vec::new(); + for &(bits, cls) in classes { + // Exact class bit -> true; complement of class bit across all 10 bits -> false. + cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + } + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_lo, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f16({:#06x}, {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + + // High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3); + // high half 0x7C01 (+sNaN) negated -> still sNaN (class 0, not quieted). + let hi_cases: &[([u32; 4], u32)] = &[ + ([0x3C00_0000, 1 << 3, 0, 0], 1), + ([0x3C00_0000, 1 << 8, 0, 0], 0), + ([0x7C01_FFFF, 1 << 0, 0, 0], 1), + ([0x7C01_FFFF, 1 << 1, 0, 0], 0), + ]; + let hi_in: Vec<[u32; 4]> = hi_cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_hi_neg, &hi_in, |backend, i, inp, got| { + let want = hi_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs new file mode 100644 index 000000000..18425e06c --- /dev/null +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -0,0 +1,251 @@ +//! End-to-end tests of waterfall loops over per-lane descriptors: the +//! synthetic GFX10 programs of `resource::tests` lowered to DXIL, validated +//! by `dxil.dll` when present, and run on the host GPU and WARP, each lane +//! reading the resource its own descriptor names. + +use windows::Win32::Graphics::Direct3D12::*; + +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +/// Lowers a wave32 compute program of 32 threads with the table of views at +/// s0 (textures, or with `buffers` structured buffers of dwords, at entries +/// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1. +fn build(words: &[u32], buffers: bool) -> HostShader { + let table = |user_data: u8| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: user_data, + }; + let range = |kind, table_offset_dwords, dwords, stride, user_data| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data, + slot: user_data, + }; + let views = if buffers { + range(ResourceType::Srv, 0, 4, 4, 0) + } else { + range(ResourceType::Srv, 0, 8, 0, 0) + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![table(0), table(1)], + used: vec![ + views, + range(ResourceType::Uav, 16, 4, 0, 0), + range(ResourceType::Sampler, 0, 4, 0, 1), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [32, 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("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, + }) + .expect("lower"); + // One access with each lane's own heap index, no wave operation. + assert_eq!(lowered.nonuniform_handles, 1); + assert!(!lowered.wave_ops); + 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, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + }; + 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 +} + +/// 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<u32>)> { + 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 + // access violation (7 of 24 runs of these four tests). + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = match host.compute_pipeline(shader) { + Ok(p) => p, + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + // Both tables start at heap index 0. + 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 words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views, + samplers: &samplers, + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, words[0].clone())); + } + out +} + +/// 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<f32>)> { + let first = [[1.0f32, 0.0, 0.0, 1.0]]; + let second = [[2.0f32, 0.0, 0.0, 1.0]]; + let views = [ + View::Texture(1, 1, &first), + View::Texture(1, 1, &second), + View::RawUav(32), + ]; + run(shader, &views) + .into_iter() + .map(|(label, words)| (label, words.into_iter().map(f32::from_bits).collect())) + .collect() +} + +#[test] +fn lanes_sample_the_texture_their_if_else_arm_chose() { + use crate::resource::tests::WATERFALL_JOINED_WAVE32; + let shader = build(WATERFALL_JOINED_WAVE32, false); + for (label, red) in sampled(&shader) { + // Lanes below 16 took the first texture, the others the second. + let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_sample_the_texture_their_arm_loaded_or_picked() { + use crate::resource::tests::WATERFALL_JOINED_MIXED_WAVE32; + let shader = build(WATERFALL_JOINED_MIXED_WAVE32, false); + for (label, red) in sampled(&shader) { + // Lanes below 16 loaded entry (lane & 1); of the others, lanes + // below 24 picked the first, the rest the second. + let want: Vec<f32> = (0..32) + .map(|l| match l { + 0..16 => [1.0, 2.0][l & 1], + 16..24 => 1.0, + _ => 2.0, + }) + .collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_load_from_the_buffer_their_nested_arms_chose() { + use crate::resource::tests::WATERFALL_JOINED_BUFFER_WAVE32; + let shader = build(WATERFALL_JOINED_BUFFER_WAVE32, true); + let first: Vec<u32> = (0..32).map(|i| 100 + i).collect(); + let second: Vec<u32> = (0..32).map(|i| 200 + i).collect(); + let views = [ + View::Buffer { + data: &first, + stride: Stride::Structured(4), + }, + View::Buffer { + data: &second, + stride: Stride::Structured(4), + }, + View::RawUav(32), + ]; + for (label, got) in run(&shader, &views) { + // Dword `lane` of the first buffer below 16, of the second from 16 + // to 23; lanes from 24 on load and store nothing. + let want: Vec<u32> = (0..32) + .map(|l| match l { + 0..16 => 100 + l, + 16..24 => 200 + l, + _ => 0, + }) + .collect(); + assert_eq!(got, want, "{label}"); + } +} + +#[test] +fn lanes_sample_the_entry_their_offset_names_in_the_console_waterfall() { + use crate::resource::tests::WATERFALL_INDEXED_WAVE32; + let shader = build(WATERFALL_INDEXED_WAVE32, false); + let results = sampled(&shader); + assert!(!results.is_empty()); + for (label, red) in results { + // Even lanes hold entry 0's offset, odd lanes entry 1's. + let want: Vec<f32> = (0..32).map(|l| [1.0, 2.0][l & 1]).collect(); + assert_eq!(red, want, "{label}"); + } +} + +#[test] +fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { + use crate::resource::tests::cmpx_waterfall; + // Lanes below 16 hold the first descriptor, the others the second. + let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect(); + for folded in [false, true] { + let shader = build(&cmpx_waterfall(false, folded), false); + let results = sampled(&shader); + assert!(!results.is_empty()); + for (label, red) in results { + assert_eq!(red, want, "{label}, folded {folded}"); + } + } +} diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs new file mode 100644 index 000000000..c74e08374 --- /dev/null +++ b/crates/victory-shader/src/emit/wave.rs @@ -0,0 +1,1064 @@ +//! Whole-wave sections (decision 0003): code between `s_or_saveexec -1` +//! (or `s_nand_saveexec 0`) and the restore of the saved mask runs in every lane of the console's +//! wave, the inactive ones included, which is how the compiler expands +//! HLSL wave reductions and prefix sums (an identity put into the inactive +//! lanes with `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane` +//! steps). A host lane that is elsewhere cannot run that code, so each +//! section is simulated on the console's lanes with symbolic values, and a +//! value it leaves is lowered by what it turned out to be: the reduction or +//! prefix of one operation over the lanes' (masked) inputs, which DXIL's +//! wave operations compute over the host's active lanes. No instruction +//! sequence is matched; any step the simulation does not model leaves the +//! values it writes unknown. + +use std::collections::HashMap; + +use crate::gfx10::{Dpp, Fields, NULL, Operand}; +use crate::ir::{EXEC, Inst, Program, Reg, Value}; + +/// An associative operation and its identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Op { + AddU, + AddF, + /// A sum of 16-bit floats in the low halves (`v_add_f16`), each addition rounded to 16 + /// bits: not associative, so only the balanced tree over the lanes in their order is + /// followed (see [`buddies`]), which is how the compiler sums a wave. + AddH, + MinU, + MaxU, + MinI, + MaxI, + MinF, + MaxF, + Or, + And, + Xor, +} + +impl Op { + fn of(name: &str) -> Option<Op> { + Some(match name { + // the low dword of a 64-bit sum (`v_add_co_ci_u32` carries into + // the high one) is the 32-bit sum of the low dwords + "v_add_nc_u32" | "v_add_co_u32" => Op::AddU, + "v_add_f32" => Op::AddF, + "v_add_f16" => Op::AddH, + "v_min_u32" => Op::MinU, + "v_max_u32" => Op::MaxU, + "v_min_i32" => Op::MinI, + "v_max_i32" => Op::MaxI, + "v_min_f32" => Op::MinF, + "v_max_f32" => Op::MaxF, + "v_or_b32" => Op::Or, + "v_and_b32" => Op::And, + "v_xor_b32" => Op::Xor, + _ => return None, + }) + } + + /// Whether `k` leaves the other operand unchanged. + fn identity(self, k: u32) -> bool { + match self { + Op::AddU | Op::AddH | Op::Or | Op::Xor | Op::MaxU => k == 0, + Op::AddF => k == 0 || k == 0x8000_0000, + Op::MinU | Op::And => k == u32::MAX, + Op::MinI => k == 0x7FFF_FFFF, + Op::MaxI => k == 0x8000_0000, + Op::MinF => k == 0x7F80_0000, + Op::MaxF => k == 0xFF80_0000, + } + } + + /// Counting a lane twice changes the result. + fn counts(self) -> bool { + matches!(self, Op::AddU | Op::AddF | Op::AddH | Op::Xor) + } +} + +/// Whether the lane sets `a` and `b` are the two halves of one aligned run of lanes: lanes +/// 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). +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; + } + let run = |s: u64| { + let first = s.trailing_zeros(); + (first.is_multiple_of(n) && s >> first == (1u64 << n) - 1).then_some(first) + }; + match (run(a), run(b)) { + (Some(x), Some(y)) => x.min(y) % (2 * n) == 0 && x.abs_diff(y) == n, + _ => false, + } +} + +/// A lane's value inside a section. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Sym { + Unknown, + K(u32), + /// The lane's own value of a VGPR value from before the section. + Own(Value), + /// A uniform value from before the section. + Uni(Value), + /// `op` over `lanes` of `mask ? src : ident` (`op` none: one lane). + Red { + op: Option<Op>, + src: Value, + mask: Value, + ident: u32, + lanes: u64, + }, +} + +/// What a value a section leaves holds in every lane. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Shape { + K(u32), + Value(Value), + /// The lane's own `mask ? src : ident`. + Masked(Value, Value, u32), + /// `op` over every lane. + Active(Op, Value, Value, u32), + /// `op` over the lanes below (`inclusive`: and including) each lane. + Prefix(Op, Value, Value, u32, bool), +} + +/// The section starting at instruction `start` of a block: its restore +/// index and the shapes of the values it writes. +pub(crate) struct Section { + pub end: usize, + pub shapes: HashMap<Value, Shape>, +} + +/// Every whole-wave section of `block`, by start index. +pub(crate) fn sections(p: &Program, block: usize) -> HashMap<usize, Section> { + let insts = &p.blocks[block].insts; + let wave: u32 = if p.wave64 { 64 } else { 32 }; + let mut out = HashMap::new(); + let mut i = 0; + while i < insts.len() { + let inst = &insts[i]; + // EXEC becomes every lane: `s_or_saveexec -1` or `s_nand_saveexec 0`. + let all = match inst.name() { + "s_or_saveexec_b64" | "s_or_saveexec_b32" => Some(Operand::Const(193)), + "s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Some(Operand::Const(128)), + _ => None, + }; + let start = all.is_some_and( + |k| matches!(&inst.fields, Fields::Sop { src, .. } if src.first() == Some(&k)), + ); + let saved = match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } if start => inst.write(Reg::S(*code)), + _ => None, + }; + let Some(saved) = saved else { + i += 1; + continue; + }; + let end = (i + 1..insts.len()).find(|&j| { + insts[j].write(Reg::S(EXEC)).is_some() + && insts[j].read(Reg::S(saved_code(inst))) == Some(saved) + }); + let Some(end) = end else { + break; + }; + let shapes = simulate(&insts[i + 1..end], wave, saved); + out.insert(i, Section { end, shapes }); + i = end + 1; + } + out +} + +fn saved_code(inst: &Inst) -> u8 { + match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } => *code, + _ => NULL, + } +} + +/// The lane `l` reads with DPP, whether it reads 0 instead, and whether it +/// writes; `None` for patterns not modelled. +fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> { + match d { + Dpp::Lanes { sel, .. } => Some(((l & !7) | (sel >> (3 * (l & 7)) & 7), false, true)), + Dpp::Row { + ctrl, + row_mask, + bank_mask, + bound_ctrl, + .. + } => { + let (row, pos, n) = (l & !15, l & 15, u32::from(ctrl & 15)); + let enabled = row_mask >> (l >> 4 & 3) & 1 != 0 && bank_mask >> (l >> 2 & 3) & 1 != 0; + let (src, inside) = match ctrl { + 0..=0xFF => ((l & !3) | (u32::from(ctrl) >> (2 * (l & 3)) & 3), true), + 0x101..=0x10F => (l + n, pos + n < 16), + 0x111..=0x11F => (l.wrapping_sub(n), pos >= n), + 0x121..=0x12F => (row | (pos.wrapping_sub(n) & 15), true), + 0x140 => (l ^ 15, true), + 0x141 => (l ^ 7, true), + 0x150..=0x15F => (row | n, true), + 0x160..=0x16F => (l ^ n, true), + _ => return None, + }; + match (inside, bound_ctrl) { + (true, _) => Some((src, false, enabled)), + (false, true) => Some((l, true, enabled)), + (false, false) => Some((l, false, false)), + } + } + } +} + +fn combine(op: Op, a: Sym, b: Sym) -> Sym { + match (a, b) { + (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x, + ( + Sym::Red { + op: oa, + src, + mask, + ident, + lanes: la, + }, + Sym::Red { + op: ob, + src: sb, + mask: mb, + ident: ib, + lanes: lb, + }, + ) if (src, mask, ident) == (sb, mb, ib) + && op.identity(ident) + && oa.is_none_or(|o| o == op) + && ob.is_none_or(|o| o == op) + && (!op.counts() || la & lb == 0) + && (op != Op::AddH || buddies(la, lb)) => + { + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes: la | lb, + } + } + _ => Sym::Unknown, + } +} + +fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> { + let all = if wave == 64 { + u64::MAX + } else { + u64::from(u32::MAX) + }; + let mut exec = all; + let mut vec: HashMap<Value, Vec<Sym>> = HashMap::new(); + let mut uni: HashMap<Value, Sym> = HashMap::new(); + // Masks the section derives from the saved EXEC (`s_and` with it). + let mut masked = vec![saved]; + for inst in insts { + let name = inst.name(); + if inst.write(Reg::S(EXEC)).is_some() { + // Constant lane sets (prefix sums); anything else ends what + // the simulation can follow. + let lo = name + .starts_with("s_mov_b") + .then(|| constant(inst)) + .flatten(); + let Some(k) = lo else { + return shapes(vec, uni, wave); + }; + exec = (if name == "s_mov_b64" { + k + } else { + (exec & !0xFFFF_FFFF) | (k & 0xFFFF_FFFF) + }) & all; + continue; + } + if inst.write(Reg::S(EXEC + 1)).is_some() { + let Some(k) = name + .starts_with("s_mov_b") + .then(|| constant(inst)) + .flatten() + else { + return shapes(vec, uni, wave); + }; + exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; + continue; + } + if let Fields::Sop { 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); + } + for &(_, w) in &inst.writes { + uni.entry(w).or_insert(Sym::Unknown); + } + continue; + } + let Fields::Valu(v) = &inst.fields else { + for &(_, w) in &inst.writes { + vec.insert(w, vec![Sym::Unknown; wave as usize]); + } + continue; + }; + let lanes = |op: &Operand, + vec: &HashMap<Value, Vec<Sym>>, + uni: &HashMap<Value, Sym>| + -> Vec<Sym> { + let one = |s: Sym| vec![s; wave as usize]; + match *op { + Operand::Vector { reg, .. } => match inst.read(Reg::V(reg)) { + Some(x) => vec + .get(&x) + .cloned() + .unwrap_or_else(|| (0..wave).map(|_| Sym::Own(x)).collect()), + None => one(Sym::Unknown), + }, + Operand::Scalar { code, .. } if code != NULL => match inst.read(Reg::S(code)) { + Some(x) => one(uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + None => one(Sym::Unknown), + }, + Operand::Const(c) => one(crate::resource::inline(c).map_or(Sym::Unknown, Sym::K)), + Operand::Literal(x) => one(Sym::K(x)), + _ => one(Sym::Unknown), + } + }; + let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some(); + if name == "v_readlane_b32" { + let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) = + (v.dst, v.src.first(), v.src.get(1)) + else { + continue; + }; + let l = match *lane { + Operand::Const(c) => crate::resource::inline(c), + Operand::Literal(x) => Some(x), + _ => None, + }; + let x = lanes(src, &vec, &uni); + if let Some(w) = inst.write(Reg::S(code)) { + let s = l + .and_then(|l| x.get(l as usize).copied()) + .unwrap_or(Sym::Unknown); + uni.insert(w, s); + } + continue; + } + let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { + for &(_, w) in &inst.writes { + uni.insert(w, Sym::Unknown); + } + continue; + }; + let Some(dst) = inst.write(Reg::V(dreg)) else { + continue; + }; + let old = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + // src0 as each lane fetches it (DPP), with the lanes that write. + let src0 = v.src.first().map(|o| lanes(o, &vec, &uni)); + let mut writes = exec; + let fetched: Option<Vec<Sym>> = match (v.dpp, &src0) { + (Some(d), Some(s)) => { + if exec != all { + vec.insert(dst, vec![Sym::Unknown; wave as usize]); + continue; + } + let mut f = Vec::with_capacity(wave as usize); + let mut ok = true; + for l in 0..wave { + match dpp_lane(d, l) { + Some((src, zero, on)) if src < wave => { + f.push(if zero { Sym::K(0) } else { s[src as usize] }); + if !on { + writes &= !(1u64 << l); + } + } + _ => ok = false, + } + } + ok.then_some(f) + } + (None, Some(s)) => Some(s.clone()), + _ => None, + }; + let src = |k: usize| v.src.get(k).map(|o| lanes(o, &vec, &uni)); + let result: Vec<Sym> = match (name, fetched) { + _ if modifiers => vec![Sym::Unknown; wave as usize], + ("v_mov_b32", Some(a)) => a, + ("v_bfrev_b32", Some(a)) => a + .into_iter() + .map(|s| match s { + Sym::K(k) => Sym::K(k.reverse_bits()), + _ => Sym::Unknown, + }) + .collect(), + ("v_cndmask_b32", Some(a)) => { + let mask = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + let b = src(1).unwrap_or_default(); + (0..wave as usize) + .map(|l| match (a[l], b.get(l).copied(), mask) { + (Sym::K(ident), Some(Sym::Own(x)), Some(m)) if masked.contains(&m) => { + Sym::Red { + op: None, + src: x, + mask: m, + ident, + lanes: 1 << l, + } + } + _ => Sym::Unknown, + }) + .collect() + } + ("v_permlanex16_b32", Some(a)) => { + // Lanes of each row read the other row of their half; lane + // i's pick is nibble i of {src2, src1}. + let sel = |k: usize| match v.src.get(k) { + Some(&Operand::Const(c)) => crate::resource::inline(c), + Some(&Operand::Literal(x)) => Some(x), + _ => None, + }; + match (sel(1), sel(2)) { + (Some(s1), Some(s2)) => { + let s = u64::from(s1) | u64::from(s2) << 32; + (0..wave) + .map(|l| { + let other = (l & !31) | ((l & 16) ^ 16); + let pick = (s >> (4 * (l & 15)) & 15) as u32; + a[(other | pick) as usize] + }) + .collect() + } + _ => vec![Sym::Unknown; wave as usize], + } + } + ("v_sub_nc_u32", Some(a)) => { + // A prefix sum less the lane's own term: the exclusive one. + let b = src(1).unwrap_or_default(); + (0..wave as usize) + .map(|l| match (a[l], b.get(l).copied()) { + ( + Sym::Red { + op: None | Some(Op::AddU), + src, + mask, + ident: 0, + lanes, + }, + Some(Sym::Red { + op: None | Some(Op::AddU), + src: s2, + mask: m2, + ident: 0, + lanes: l2, + }), + ) if (src, mask) == (s2, m2) && lanes & l2 == l2 => { + let rest = lanes & !l2; + if rest == 0 { + Sym::K(0) + } else { + Sym::Red { + op: Some(Op::AddU), + src, + mask, + ident: 0, + lanes: rest, + } + } + } + _ => Sym::Unknown, + }) + .collect() + } + (n, Some(a)) => match (Op::of(n), src(1)) { + (Some(op), Some(b)) => (0..wave as usize) + .map(|l| combine(op, a[l], b[l])) + .collect(), + _ => vec![Sym::Unknown; wave as usize], + }, + _ => vec![Sym::Unknown; wave as usize], + }; + let merged = (0..wave as usize) + .map(|l| { + if writes >> l & 1 != 0 { + result[l] + } else { + old[l] + } + }) + .collect(); + vec.insert(dst, merged); + } + shapes(vec, uni, wave) +} + +fn constant(inst: &Inst) -> Option<u64> { + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + let wide = inst.name() == "s_mov_b64"; + match *src.first()? { + Operand::Scalar { code: NULL, .. } => Some(0), + Operand::Const(c @ 128..=208) => { + let x = crate::resource::inline(c)?; + Some(if wide { + i64::from(x as i32) as u64 + } else { + u64::from(x) + }) + } + Operand::Const(c) if !wide => crate::resource::inline(c).map(u64::from), + Operand::Literal(x) => Some(u64::from(x)), + _ => None, + } +} + +/// The shape of each value, where every lane agrees on one. +fn shapes( + vec: HashMap<Value, Vec<Sym>>, + uni: HashMap<Value, Sym>, + wave: u32, +) -> HashMap<Value, Shape> { + let all = if wave == 64 { + u64::MAX + } else { + u64::from(u32::MAX) + }; + let mut out = HashMap::new(); + let single = |s: Sym| match s { + Sym::K(k) => Some(Shape::K(k)), + Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)), + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes, + } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + _ => None, + }; + for (v, s) in uni { + if let Some(sh) = single(s) { + out.insert(v, sh); + } + } + for (v, lanes) in vec { + if let Some(sh) = per_lane(&lanes, all) { + out.insert(v, sh); + } + } + out +} + +fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> { + let first = lanes[0]; + let own = |l: usize, s: Sym| match s { + Sym::Red { + op: None, + src, + mask, + ident, + lanes, + } if lanes == 1 << l => Some((src, mask, ident)), + _ => None, + }; + if let Some(m) = own(0, first) + && lanes.iter().enumerate().all(|(l, &s)| own(l, s) == Some(m)) + { + return Some(Shape::Masked(m.0, m.1, m.2)); + } + if lanes.iter().all(|&s| s == first) { + return match first { + Sym::K(k) => Some(Shape::K(k)), + Sym::Uni(x) | Sym::Own(x) => Some(Shape::Value(x)), + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes, + } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + _ => None, + }; + } + // Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive). + let mut meta: Option<(Value, Value, u32, bool)> = None; + let mut op_found: Option<Op> = None; + for (l, &s) in lanes.iter().enumerate() { + let below = (1u64 << l) - 1; + let (op, src, mask, ident, set) = match s { + Sym::Red { + op, + src, + mask, + ident, + lanes, + } => (op, src, mask, ident, lanes), + // Lane 0 of an exclusive prefix holds the identity. + Sym::K(_) if l == 0 => continue, + _ => return None, + }; + let inclusive = set == below | (1u64 << l); + if !inclusive && set != below { + return None; + } + if l == 0 && !inclusive { + return None; + } + if op.is_none() && set.count_ones() != 1 { + return None; + } + let lane_meta = (src, mask, ident, inclusive); + match meta { + None => meta = Some(lane_meta), + Some(prev) if prev == lane_meta => {} + _ => return None, + } + if let Some(o) = op { + match op_found { + None => op_found = Some(o), + Some(prev) if prev == o => {} + _ => return None, + } + } + } + let (src, mask, ident, inclusive) = meta?; + let op = op_found?; + if !op.identity(ident) { + return None; + } + match lanes[0] { + Sym::K(k) if !inclusive && k == ident => {} + Sym::Red { .. } if inclusive => {} + _ => return None, + } + Some(Shape::Prefix(op, src, mask, ident, inclusive)) +} + +/// `WaveActiveBitOr(v7)` into s7 as the console compiler expands it: every lane takes part, +/// those outside the saved EXEC (s[4:5]) with 0. +#[cfg(test)] +pub(super) const WAVE_OR_V7_TO_S7: [u32; 20] = [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + 0x3802_02E9, + 0xDE54_C101, // v_or_b32 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + 0x3802_02E9, + 0x9360_1201, // v_or_b32 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + 0x3802_02E9, + 0x0009_2401, // v_or_b32 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x3802_02FA, + 0xFF09_4001, // v_or_b32 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x3802_0302, // v_or_b32 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x3802_0207, // v_or_b32 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] +]; + +#[cfg(test)] +mod tests { + use super::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + const fn sop1(sdst: u8, op: u8, ssrc0: u8) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | (op as u32) << 8 | ssrc0 as u32 + } + + const fn vop1(vdst: u8, op: u8, src0: u16) -> u32 { + (0x3F << 25) | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop2(vdst: u8, op: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn dpp16(vsrc0: u8, ctrl: u16, row_mask: u8, bank_mask: u8, bound_ctrl: bool) -> u32 { + (row_mask as u32) << 28 + | (bank_mask as u32) << 24 + | (bound_ctrl as u32) << 19 + | (ctrl as u32) << 8 + | vsrc0 as u32 + } + + const fn vop3(vdst: u8, op: u16, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0xD400_0000 | (op as u32) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | ((src1 as u32 & 0x1FF) << 9) | ((src2 as u32 & 0x1FF) << 18), + ] + } + + fn build(words: &[u32], wave64: bool) -> Program { + let code: Vec<u8> = words + .iter() + .copied() + .chain(std::iter::once(S_ENDPGM)) + .flat_map(u32::to_le_bytes) + .collect(); + crate::ir::build(&code, wave64, 256).unwrap() + } + + #[test] + fn dpp_lanes_follow_the_isa() { + // row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16. + let shr = Dpp::Row { + ctrl: 0x111, + row_mask: 0xF, + bank_mask: 0xF, + bound_ctrl: true, + fi: false, + }; + assert_eq!(dpp_lane(shr, 16), Some((16, true, true))); + assert_eq!(dpp_lane(shr, 17), Some((16, false, true))); + // row_mirror: lane 3 reads lane 12. + let mirror = Dpp::Row { + ctrl: 0x140, + row_mask: 0xF, + bank_mask: 0xF, + bound_ctrl: true, + fi: false, + }; + assert_eq!(dpp_lane(mirror, 3), Some((12, false, true))); + // dpp8 [1,0,3,2,5,4,7,6] swaps neighbours. + let swap = Dpp::Lanes { + sel: 1 | 3 << 6 | 2 << 9 | 5 << 12 | 4 << 15 | 7 << 18 | 6 << 21, + fi: false, + }; + assert_eq!(dpp_lane(swap, 8), Some((9, false, true))); + } + + #[test] + fn prefixes_are_recognised() { + let (x, m) = (Value(1), Value(2)); + let red = |lanes: u64| Sym::Red { + op: Some(Op::AddU), + src: x, + mask: m, + ident: 0, + lanes, + }; + let inclusive: Vec<Sym> = (0..64).map(|l| red(u64::MAX >> (63 - l))).collect(); + assert_eq!( + per_lane(&inclusive, u64::MAX), + Some(Shape::Prefix(Op::AddU, x, m, 0, true)) + ); + let mut exclusive: Vec<Sym> = (0..64).map(|l| red((1u64 << l) - 1)).collect(); + exclusive[0] = Sym::K(0); + assert_eq!( + per_lane(&exclusive, u64::MAX), + Some(Shape::Prefix(Op::AddU, x, m, 0, false)) + ); + assert_eq!( + per_lane(&vec![red(u64::MAX); 64], u64::MAX), + Some(Shape::Active(Op::AddU, x, m, 0)) + ); + } + + #[test] + fn constant_decodes_width_and_inline_kinds() { + let b64 = 0x04; + let b32 = 0x03; + let check = |words: &[u32], wave64: bool| -> Option<u64> { + let p = build(words, wave64); + constant(&p.blocks[0].insts[0]) + }; + + assert_eq!( + check(&[sop1(EXEC, b64, 194)], true), + Some(0xFFFF_FFFF_FFFF_FFFE) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 196)], true), + Some(0xFFFF_FFFF_FFFF_FFFC) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 208)], true), + Some(0xFFFF_FFFF_FFFF_FFF0) + ); + assert_eq!(check(&[sop1(EXEC, b64, 193)], true), Some(u64::MAX)); + assert_eq!(check(&[sop1(EXEC, b64, NULL)], true), Some(0)); + assert_eq!(check(&[sop1(EXEC, b64, 243)], true), None); + assert_eq!( + check(&[sop1(EXEC, b64, 255), 0x1234_5678], true), + Some(0x1234_5678) + ); + + assert_eq!(check(&[sop1(EXEC, b32, 194)], false), Some(0xFFFF_FFFE)); + assert_eq!(check(&[sop1(EXEC, b32, 243)], false), Some(0xBF80_0000)); + assert_eq!(check(&[sop1(EXEC, b32, NULL)], false), Some(0)); + assert_eq!( + check(&[sop1(EXEC, b32, 255), 0x1234_5678], false), + Some(0x1234_5678) + ); + assert_eq!(check(&[sop1(EXEC, b32, 0)], false), None); + } + + #[test] + fn exec_minus_two_masks_lane_zero_and_enforces_dpp_guard() { + for wave64 in [false, true] { + let mut w = Vec::new(); + let save_op = if wave64 { 0x25 } else { 0x3D }; + let mov_exec = if wave64 { 0x04 } else { 0x03 }; + let push_exec = |w: &mut Vec<u32>, k: u8| w.push(sop1(EXEC, mov_exec, k)); + let push_exec_lit = |w: &mut Vec<u32>, lit: u32| { + w.push(sop1(EXEC, mov_exec, 255)); + w.push(lit); + }; + + w.push(sop1(0, save_op, 193)); + w.extend(vop3(1, 0x101, 128, 256, 0)); + for shift in [1u16, 2, 4, 8] { + w.push(vop2(1, 0x25, 0xFA, 1)); + w.push(dpp16(1, 0x110 + shift, 0xF, 0xF, false)); + } + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0000_FFFF); + w.push(vop2(1, 0x25, 2, 1)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + } + + push_exec(&mut w, 193); + w.push(vop1(3, 0x01, 257)); + w.push(vop1(3, 0x01, 0xFA)); + w.push(dpp16(1, 0x111, 0xF, 0xF, false)); + + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0x0001_0000); + w.push(vop1(3, 0x01, 2)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 129)); + w.push(vop1(3, 0x01, 2)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0001_0000); + w.push(vop1(3, 0x01, 2)); + } + + push_exec(&mut w, 193); + w.push(vop1(2, 0x01, 128)); + w.push(vop1(5, 0x01, 135)); + push_exec(&mut w, 194); + w.push(vop1(2, 0x01, 259)); + w.push(vop1(4, 0x01, 0xFA)); + w.push(dpp16(5, 0xE4, 0xF, 0xF, false)); + w.push(sop1(EXEC, mov_exec, 0)); + + let p = build(&w, wave64); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(0)).unwrap(); + let v0_in = p + .inputs + .iter() + .find_map(|&(r, v)| (r == Reg::V(0)).then_some(v)) + .unwrap(); + let v2_val = insts[insts.len() - 4].write(Reg::V(2)).unwrap(); + let v4_val = insts[insts.len() - 3].write(Reg::V(4)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!( + sec.shapes.get(&v2_val), + Some(&Shape::Prefix(Op::AddU, v0_in, saved, 0, false)) + ); + assert_eq!(sec.shapes.get(&v4_val), None); + } + } + + /// `WaveActiveSum` of 16-bit floats, as compiled in + /// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the + /// lowering reproduces. A tree in another order is not followed. + #[test] + fn a_sum_of_halves_over_the_wave_is_followed_in_the_order_of_its_tree() { + let words = |first: [u32; 2], second: [u32; 2]| { + [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + first[0], + first[1], + second[0], + second[1], + 0x6402_02E9, + 0x0009_2401, // v_add_f16 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x6402_02FA, + 0xFF09_4001, // v_add_f16 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x6402_0302, // v_add_f16 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x6402_0207, // v_add_f16 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + ] + }; + let pairs = [0x6402_02E9, 0xDE54_C101]; // v_add_f16 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + let quads = [0x6402_02E9, 0x9360_1201]; // v_add_f16 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + let shape = |w: &[u32]| { + 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(); + // ..., 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)) + }; + let (found, want) = shape(&words(pairs, quads)); + assert_eq!(found, Some(want)); + // lanes two apart first, neighbours second: every lane counted once, but + // (x0 + x2) + (x1 + x3) rounds differently from (x0 + x1) + (x2 + x3) + let (found, _) = shape(&words(quads, pairs)); + assert_eq!(found, None); + } + + #[test] + fn buddies_are_the_two_halves_of_an_aligned_run() { + assert!(buddies(0b01, 0b10)); + assert!(buddies(0b1100, 0b0011)); + assert!(buddies(0xF0, 0x0F)); + assert!(buddies(u64::from(u32::MAX), u64::from(u32::MAX) << 32)); + assert!(!buddies(0b010, 0b100)); // lanes 1 and 2: not one pair + assert!(!buddies(0b0011, 0b110000)); // pairs 0 and 2 + assert!(!buddies(0b0101, 0b1010)); // not runs + assert!(!buddies(0b01, 0b1100)); // unequal + assert!(!buddies(0b11, 0b11)); + } + + #[test] + fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() { + let w = [ + sop1(0, 0x3D, 193), + vop1(1, 0x01, 135), + sop1(EXEC, 0x04, 193), + vop1(2, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC + 1, 0x03, 193), + vop1(3, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC, 0x03, 0), + ]; + let p = build(&w, false); + let insts = &p.blocks[0].insts; + let v2_val = insts[3].write(Reg::V(2)).unwrap(); + let v3_val = insts[5].write(Reg::V(3)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!(sec.shapes.get(&v2_val), Some(&Shape::K(7))); + assert_eq!(sec.shapes.get(&v3_val), Some(&Shape::K(7))); + } + + #[test] + fn per_lane_prefix_soundness() { + let (v0, v_other, m0, m_other) = (Value(1), Value(2), Value(3), Value(4)); + let red = |op: Option<Op>, src: Value, mask: Value, ident: u32, lanes: u64| Sym::Red { + op, + src, + mask, + ident, + lanes, + }; + + for (wave, all) in [(32usize, u64::from(u32::MAX)), (64usize, u64::MAX)] { + let below_mask = |l: usize| if l == 0 { 0 } else { (1u64 << l) - 1 }; + + let mut valid_inc: Vec<Sym> = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l) | (1u64 << l))) + .collect(); + valid_inc[0] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_inc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, true)) + ); + + let mut valid_exc: Vec<Sym> = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l))) + .collect(); + valid_exc[0] = Sym::K(0); + valid_exc[1] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_exc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, false)) + ); + + let mut mixed_other_src = valid_exc.clone(); + mixed_other_src[0] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&mixed_other_src, all), None); + + let mut mixed_same_src = valid_exc.clone(); + mixed_same_src[0] = red(None, v0, m0, 0, 1); + assert_eq!(per_lane(&mixed_same_src, all), None); + + let mut exc_bad_lane1_src = valid_exc.clone(); + exc_bad_lane1_src[1] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&exc_bad_lane1_src, all), None); + + let mut exc_bad_lane1_set = valid_exc.clone(); + exc_bad_lane1_set[1] = red(None, v0, m0, 0, 0b11); + assert_eq!(per_lane(&exc_bad_lane1_set, all), None); + + for bad0 in [ + red(None, v0, m0, 1, 1), + red(None, v_other, m0, 0, 1), + red(None, v0, m_other, 0, 1), + red(None, v0, m0, 0, 0), + Sym::K(0), + ] { + let mut bad_inc = valid_inc.clone(); + bad_inc[0] = bad0; + assert_eq!(per_lane(&bad_inc, all), None); + } + + let mut bad_ident: Vec<Sym> = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 1, below_mask(l) | (1u64 << l))) + .collect(); + bad_ident[0] = red(None, v0, m0, 1, 1); + assert_eq!(per_lane(&bad_ident, all), None); + } + } +} diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs new file mode 100644 index 000000000..db82f33bc --- /dev/null +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -0,0 +1,452 @@ +//! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a +//! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`]) +//! so that the two host waves can exchange their halves inside it. Lowered, validated by +//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32. + +use std::collections::HashSet; + +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::{ShaderError, io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads +/// below s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store +/// the result to dword 0 of the raw UAV. +/// `skip`: the branch past the body when no thread is below s0: `s_cbranch_execz`, or +/// `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left"). +fn program(skip: u32) -> NativeProgram { + let mut words = vec![ + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0 + 0x340E_0B06, // v_lshlrev_b32 v7, v6, v5 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + skip | 23, // the branch to the restore of EXEC + ]; + words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + ]); + native(&words) +} + +/// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4 +/// root constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`. +fn native(body: &[u32]) -> NativeProgram { + native_of(body, true, 64) +} + +/// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads. +fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + ]; + words.extend_from_slice(body); + words.push(S_ENDPGM); + NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 16, + 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![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [threads, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// `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<usize>) -> Result<HostShader, ShaderError> { + let st = structure::structure_wide(p, wide).expect("structure"); + let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(p, native).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let lowered = lower::lower(&lower::Parts { + native, + p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered?; + Ok(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, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + }) +} + +#[test] +fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { + // thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd + // mantissas, so that additions round); all of them store the wave's sum + let mut words = vec![ + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + ]; + // (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_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + 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); + 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(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // 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 narrow = |f: f32| { + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); + let terms: Vec<u16> = (0..64u16).map(|t| 0x3C00 + 37 * t).collect(); + let mut tree = terms.clone(); + while tree.len() > 1 { + 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()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + 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"); + return; + } + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .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]); +} + +/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 +/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The +/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the +/// translation gives the console's whatever the host does. +#[test] +fn a_16_bit_sum_rounds_to_nearest_when_asked_to() { + let words = [ + 0x7E0E_02FF, + 0x0000_3C03, // v_mov_b32 v7, 0x3c03 + 0x7E0C_02FF, + 0x0000_4000, // v_mov_b32 v6, 0x4000 + 0x6400_0D07, // v_add_f16 v0, v7, v6 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]; + 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()); + 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()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + eprintln!("the hardware device does not take this program; not run"); + return; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + let got = out[0][0] & 0xFFFF; + eprintln!("v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest {nearest}: {got:#x}"); + if nearest { + assert_eq!(got, 0x4202); + } else { + assert!(got == 0x4201 || got == 0x4202, "{got:#x}"); + } + } +} + +#[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")] { + a_wave_or_inside(skip, name); + } +} + +fn a_wave_or_inside(skip: u32, name: &str) { + let native = program(skip); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let branch = (0..p.blocks.len()) + .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == name)) + .expect("the branch"); + // per lane, the two host waves cannot meet inside the branch + lower::take_needs(); + let per_lane = lowered(&native, &p, &HashSet::new()); + assert!( + matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a wave reduction where not every lane runs"), + "{:?}", + per_lane.err() + ); + // ... and the lowering names the block, around which that branch is the one to widen + let needs = lower::take_needs(); + let st = structure::structure(&p).expect("structure"); + assert_eq!(lower::branches_around(&st, &needs), Some(vec![branch])); + // (taken, past the body, when every lane's bit is clear) + assert_eq!(st.wave_any[branch], Some(false)); + // wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there) + let wide = HashSet::from([branch]); + let st = structure::structure_wide(&p, &wide).expect("structure"); + let inside = match p.blocks[branch].exit { + ir::Exit::Branch { not_taken, .. } => not_taken, + _ => unreachable!(), + }; + assert!(st.guards[inside].iter().any(Option::is_some)); + let shader = lowered(&native, &p, &wide).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // 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 Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + 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"); + 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)] { + 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) { + ud[u.index as usize] = below; + } + } + 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!("dispatch failed: {e}")); + assert_eq!(out[0][0], expected, "{name}: {below} threads in the branch"); + } + eprintln!("ran on the hardware device ({name}): the OR of both halves in every case"); +} + +/// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0 +/// of the UAV; None (and a line) without a device that takes it. +fn on_the_card(shader: &HostShader, constants: [u32; 2]) -> Option<u32> { + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let Ok((root, pso)) = host.compute_pipeline(shader) else { + eprintln!("the hardware device does not take this program; not run"); + return None; + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = constants[d as usize]; + } + } + 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!("dispatch failed: {e}")); + Some(out[0][0]) +} + +/// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0) +/// and a number on the other, and is read as a number after the join, as the trace programs +/// keep their lanes' masks and their node numbers on one stack +/// (`deferred_tiled:CS_LaserLightShadowRaytracing`, s46 at 0x104, 0x75c and 0x188). The +/// mask arrives as the ballot of its lanes. +#[test] +fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE94_036A, // s_mov_b32 s20, vcc_lo + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0001, // s_cbranch_scc1 over the next + 0xBE94_0385, // s_mov_b32 s20, 5 + 0x7E00_0214, // v_mov_b32 v0, s20 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]; + let native = native_of(&words, false, 32); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + 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(); + 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 }; + assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}"); + } + eprintln!("ran on the hardware device: the mask's bits, or the number"); +} + +/// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after +/// the join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along +/// (`rtdirectionalshadows:CS_RTShadowTrace32HQ_TiledFarOnly`, 0x360-0x39c). On the console +/// the skip is taken by the wave, so with some lane inside every lane sees the inner test. +/// A lane that skipped on its own would see "some lane is left" instead: refused per lane, +/// right with the branch taken wave-wide. Lane 31 stores what it saw. +#[test] +fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE8D_3C6A, // s_and_saveexec_b32 s13, vcc_lo + 0xBF88_0001, // s_cbranch_execz over the next + 0xBF06_8701, // s_cmp_eq_u32 s1, 7 + 0xBEFE_030D, // s_mov_b32 exec_lo, s13 + 0xBF85_0002, // s_cbranch_scc1 to "seven" + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0xBF82_0001, // s_branch over the next + 0x7E0A_0282, // seven: v_mov_b32 v5, 2 + 0x7DA4_009F, // v_cmpx_eq_u32 exec_lo, 31, v0 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16 | 5 << 8, // buffer_store_dword v5, off, s[8:11], 0 + ]; + 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")) + .expect("the skip"); + lower::take_needs(); + let per_lane = lowered(&native, &p, &HashSet::new()); + assert!( + matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a lane mask read as data"), + "{:?}", + per_lane.err() + ); + let st = structure::structure(&p).expect("structure"); + 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()); + // (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 }; + 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"); +} diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs new file mode 100644 index 000000000..2773b3c84 --- /dev/null +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -0,0 +1,815 @@ +//! Operand fields of GFX10 instructions, by encoding. +//! +//! Layouts follow AMD's RDNA ISA reference. Register ranges carry their size +//! in dwords, which depends on the opcode (read from its name) and, for lane +//! masks (VCC, EXEC, compare results), on the wave size. + +use super::{Encoding, Instruction}; + +/// A source or destination of an instruction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +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`. 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, + }, + Vector { + reg: u8, + dwords: u8, + }, + /// Inline constant or read-only special source, by operand code + /// (128-192: 0-64, 193-208: -1 to -16, 240-248: floats, 251-254: vccz, + /// execz, scc, lds_direct). + Const(u8), + /// The 32-bit literal that follows the instruction. + Literal(u32), + /// Interpolation attribute and channel (0-3 = x-w); `high` selects the + /// upper f16 half. + Attr { + index: u8, + chan: u8, + high: bool, + }, +} + +/// Operand code of `null` (no register; reads as 0). +pub const NULL: u8 = 125; +const VCC: u8 = 106; +const EXEC: u8 = 126; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Cache { + pub glc: bool, + pub slc: bool, + pub dlc: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Fields { + /// SOP1, SOP2, SOPC, SOPK; `imm` is SOPK's 16-bit immediate. + Sop { + dst: Option<Operand>, + src: Vec<Operand>, + imm: Option<u16>, + }, + /// The 16-bit immediate: branch offset in dwords, wait counts, message... + Sopp { + imm: u16, + }, + Smem { + data: Option<Operand>, + base: Operand, + /// Signed byte offset, added to `soffset`. + offset: i32, + soffset: Operand, + cache: Cache, + }, + Valu(Valu), + Vintrp { + dst: Operand, + /// The i/j VGPR, or for `v_interp_mov_f32` the parameter (0 `p10`, + /// 1 `p20`, 2 `p0`) as [`Operand::Const`]. + src: Operand, + attr: Operand, + }, + Ds { + dst: Option<Operand>, + addr: Option<Operand>, + data: Vec<Operand>, + offset0: u8, + offset1: u8, + gds: bool, + }, + /// MUBUF, and MTBUF with `format` set. + Buffer { + /// Loaded, stored, or the atomic operand (and result with `glc`). + data: Option<Operand>, + addr: Operand, + rsrc: Operand, + soffset: Operand, + offset: u16, + offen: bool, + idxen: bool, + format: Option<u8>, + lds: bool, + tfe: bool, + cache: Cache, + }, + Image { + data: Operand, + /// One range, or one VGPR per address with the NSA form. + addr: Vec<Operand>, + rsrc: Operand, + sampler: Option<Operand>, + dmask: u8, + dim: u8, + unorm: bool, + r128: bool, + a16: bool, + d16: bool, + tfe: bool, + lwe: bool, + cache: Cache, + }, + /// FLAT, GLOBAL and SCRATCH. + Flat { + dst: Option<Operand>, + addr: Option<Operand>, + data: Option<Operand>, + saddr: Option<Operand>, + offset: i16, + lds: bool, + cache: Cache, + }, + Exp { + target: u8, + /// Per channel; `None` when disabled. + src: [Option<Operand>; 4], + compr: bool, + done: bool, + vm: bool, + }, +} + +/// VOP1, VOP2, VOPC, VOP3 and VOP3P, with their SDWA and DPP forms. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Valu { + /// A VGPR range, an SGPR (`v_readlane_b32`...) or a lane mask (compares). + pub dst: Option<Operand>, + /// Carry-out or the second result of VOP3B (`v_add_co_u32`, `v_div_scale_f32`...). + pub carry: Option<Operand>, + /// In operand order, including the implicit VCC of VOP2 `v_cndmask_b32` + /// and carry-in, and the literal of `v_madmk`/`v_madak` forms. + pub src: Vec<Operand>, + /// Bit i applies to `src[i]`. For VOP3P, `neg` is the low half's. + pub neg: u8, + pub abs: u8, + /// VOP3P: negate the high half (`v_fma_mix*`: absolute value). + pub neg_hi: u8, + /// VOP3: bit 3 is the destination. VOP3P with `opsel_hi`: the halves used. + pub opsel: u8, + pub opsel_hi: u8, + pub clamp: bool, + /// Output modifier: 1 ×2, 2 ×4, 3 ÷2. + pub omod: u8, + pub sdwa: Option<Sdwa>, + pub dpp: Option<Dpp>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Sdwa { + /// Selects: 0-3 byte, 4-5 word, 6 dword. Compares have no `dst_sel`. + pub dst_sel: u8, + /// 0 pad with zeros, 1 sign-extend, 2 preserve. + pub dst_unused: u8, + pub src_sel: [u8; 2], + /// Bit i sign-extends `src[i]`. + pub sext: u8, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dpp { + /// DPP16: `ctrl` is the 9-bit permutation (quad_perm, row shifts...). + Row { + ctrl: u16, + row_mask: u8, + bank_mask: u8, + bound_ctrl: bool, + fi: bool, + }, + /// DPP8: eight 3-bit lane selects. + Lanes { sel: u32, fi: bool }, +} + +impl Instruction { + /// Decodes the operand fields. `wave64` sizes lane masks. + pub fn fields(&self, wave64: bool) -> Fields { + let name = self.name().unwrap_or(""); + let w = |i: usize| self.words.get(i).copied().unwrap_or(0); + let (w0, w1) = (w(0), w(1)); + let bit = |word: u32, n: u32| word >> n & 1 != 0; + let cache = |glc, slc, dlc| Cache { glc, slc, dlc }; + match self.encoding { + Encoding::Sop2 | Encoding::Sop1 | Encoding::Sopc => { + let (dst, src0, src1) = salu_dwords(name); + let sdst = scalar((w0 >> 16 & 0x7F) as u8, dst); + let ssrc = |shift: u32, dwords| source(w0 >> shift & 0xFF, dwords, w1); + let (dst, src) = match self.encoding { + Encoding::Sop2 => (Some(sdst), vec![ssrc(0, src0), ssrc(8, src1)]), + Encoding::Sopc => (None, vec![ssrc(0, src0), ssrc(8, src1)]), + _ => match name { + "s_getpc_b64" => (Some(sdst), vec![]), + "s_setpc_b64" | "s_rfe_b64" => (None, vec![ssrc(0, src0)]), + _ => (Some(sdst), vec![ssrc(0, src0)]), + }, + }; + Fields::Sop { + dst, + src, + imm: None, + } + } + Encoding::Sopk => { + let sdst = scalar((w0 >> 16 & 0x7F) as u8, 1 + u8::from(name == "s_call_b64")); + let (dst, src) = match name { + "s_setreg_imm32_b32" => (None, vec![Operand::Literal(w1)]), + "s_version" => (None, vec![]), + n if n.starts_with("s_cmpk_") + || n.starts_with("s_waitcnt_") + || n == "s_setreg_b32" => + { + (None, vec![sdst]) + } + _ => (Some(sdst), vec![]), + }; + Fields::Sop { + dst, + src, + imm: Some(w0 as u16), + } + } + Encoding::Sopp => Fields::Sopp { imm: w0 as u16 }, + Encoding::Smem => { + 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_")); + Fields::Smem { + 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: cache(bit(w0, 16), false, bit(w0, 14)), + } + } + Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => { + Fields::Valu(self.valu(name, if wave64 { 2 } else { 1 })) + } + Encoding::Vintrp => { + let vsrc = (w0 & 0xFF) as u8; + Fields::Vintrp { + dst: vector(w0 >> 18, 1), + src: if name == "v_interp_mov_f32" { + Operand::Const(vsrc) + } else { + vector(vsrc.into(), 1) + }, + attr: Operand::Attr { + index: (w0 >> 10 & 0x3F) as u8, + chan: (w0 >> 8 & 3) as u8, + high: false, + }, + } + } + Encoding::Ds => { + let ty = data_dwords(name); + let pair = ds_pair(name); + let returns = name.contains("read") + || name.contains("_rtn") + || matches!( + name, + "ds_swizzle_b32" + | "ds_permute_b32" + | "ds_bpermute_b32" + | "ds_append" + | "ds_consume" + | "ds_ordered_count" + ); + let no_addr = name.starts_with("ds_gws") + || name.contains("addtid") + || matches!(name, "ds_nop" | "ds_append" | "ds_consume"); + let data = if name.contains("read") + || name.contains("src2") + || matches!( + name, + "ds_swizzle_b32" + | "ds_nop" + | "ds_append" + | "ds_consume" + | "ds_ordered_count" + | "ds_gws_sema_v" + | "ds_gws_sema_p" + | "ds_gws_sema_release_all" + ) { + 0 + } else if pair || name.contains("cmpst") || name.contains("mskor") { + 2 + } else { + 1 + }; + Fields::Ds { + dst: returns.then(|| vector(w1 >> 24, ty * (1 + u8::from(pair)))), + addr: (!no_addr).then(|| vector(w1 & 0xFF, 1)), + data: (0..data) + .map(|i| vector(w1 >> (8 + 8 * i) & 0xFF, ty)) + .collect(), + offset0: w0 as u8, + offset1: (w0 >> 8) as u8, + gds: bit(w0, 17), + } + } + Encoding::Mubuf | Encoding::Mtbuf => { + let (offen, idxen, tfe) = (bit(w0, 12), bit(w0, 13), bit(w1, 23)); + let mtbuf = self.encoding == Encoding::Mtbuf; + Fields::Buffer { + data: (!name.ends_with("_inv")) + .then(|| vector(w1 >> 8 & 0xFF, data_dwords(name) + u8::from(tfe))), + addr: vector(w1 & 0xFF, 1 + u8::from(offen && idxen)), + rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, 4), + soffset: source(w1 >> 24, 1, 0), + offset: (w0 & 0xFFF) as u16, + offen, + idxen, + format: mtbuf.then_some((w0 >> 19 & 0x7F) as u8), + lds: !mtbuf && bit(w0, 16), + tfe, + cache: cache(bit(w0, 14), bit(w1, 22), bit(w0, 15)), + } + } + Encoding::Mimg => { + let (dim, dmask, a16, d16) = ( + (w0 >> 3 & 7) as u8, + (w0 >> 8 & 0xF) as u8, + bit(w1, 30), + bit(w1, 31), + ); + let (r128, tfe, lwe) = (bit(w0, 15), bit(w0, 16), bit(w0, 17)); + let mut data = if name.starts_with("image_gather4") { + 4 + } else { + dmask.count_ones().max(1) as u8 + }; + if d16 { + data = data.div_ceil(2); + } + let count = image_addr_dwords(name, dim, a16); + let addr = if w0 >> 1 & 3 == 0 { + vec![vector(w1 & 0xFF, count)] + } else { + // NSA: one VGPR per address, the first in dword 1, the rest + // in the extra dwords. + (0..usize::from(count)) + .map(|i| match i { + 0 => vector(w1 & 0xFF, 1), + i => vector(w(2 + (i - 1) / 4) >> (8 * ((i - 1) % 4)) & 0xFF, 1), + }) + .collect() + }; + let sampled = ["image_sample", "image_gather4", "image_get_lod"] + .iter() + .any(|p| name.starts_with(p)); + Fields::Image { + data: vector(w1 >> 8 & 0xFF, data + u8::from(tfe || lwe)), + addr, + rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, if r128 { 4 } else { 8 }), + sampler: sampled.then(|| scalar(((w1 >> 21 & 0x1F) << 2) as u8, 4)), + dmask, + dim, + unorm: bit(w0, 12), + r128, + a16, + d16, + tfe, + lwe, + cache: cache(bit(w0, 13), bit(w0, 25), bit(w0, 7)), + } + } + Encoding::Flat | Encoding::Global | Encoding::Scratch => { + let saddr = (w1 >> 16 & 0x7F) as u8; + let glc = bit(w0, 16); + let n = data_dwords(name); + let (load, atomic) = (name.contains("_load_"), name.contains("_atomic_")); + let addr = match self.encoding { + Encoding::Flat => Some(vector(w1 & 0xFF, 2)), + Encoding::Global => Some(vector(w1 & 0xFF, 1 + u8::from(saddr == NULL))), + // With an SGPR base, scratch takes no VGPR. + _ => (saddr == NULL).then(|| vector(w1 & 0xFF, 1)), + }; + let ret = if atomic && name.contains("cmpswap") { + n / 2 + } else { + n + }; + Fields::Flat { + dst: (load || atomic && glc).then(|| vector(w1 >> 24, ret)), + addr, + data: (!load).then(|| vector(w1 >> 8 & 0xFF, n)), + saddr: (self.encoding != Encoding::Flat) + .then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))), + offset: match self.encoding { + Encoding::Flat => (w0 & 0x7FF) as i16, + _ => ((w0 << 4) as i16) >> 4, + }, + lds: bit(w0, 13), + cache: cache(glc, bit(w0, 17), bit(w0, 12)), + } + } + Encoding::Exp => { + let compr = bit(w0, 10); + Fields::Exp { + target: (w0 >> 4 & 0x3F) as u8, + src: std::array::from_fn(|i| { + let slot = if compr { i / 2 } else { i }; + bit(w0, i as u32).then(|| vector(w1 >> (8 * slot) & 0xFF, 1)) + }), + compr, + done: bit(w0, 11), + vm: bit(w0, 12), + } + } + } + } + + fn valu(&self, name: &str, lanes: u8) -> Valu { + // No operands; the console compiler stores a shader hash in their fields. + if matches!(name, "v_nop" | "v_pipeflush" | "v_clrexcp") { + return Valu::default(); + } + let w = |i: usize| self.words.get(i).copied().unwrap_or(0); + let w0 = w(0); + let (dst_n, src_n) = valu_dwords(name); + let compare = match self.encoding { + Encoding::Vopc => true, + Encoding::Vop3 => self.opcode < 0x100, + _ => false, + }; + let vop3b = VOP3B.contains(&name); + let carry_in = name.ends_with("_co_ci_u32") || name == "v_cndmask_b32"; + let mut v = Valu::default(); + match self.encoding { + Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc => { + let ext = w(1); + let mut src0 = w0 & 0x1FF; + let vsrc1 = 256 + (w0 >> 9 & 0xFF); + let mut src1 = vsrc1; + match src0 { + 0xF9 => { + let sdwa = Sdwa { + dst_sel: (ext >> 8 & 7) as u8, + dst_unused: (ext >> 11 & 3) as u8, + src_sel: [(ext >> 16 & 7) as u8, (ext >> 24 & 7) as u8], + sext: (ext >> 19 & 1 | ext >> 26 & 2) as u8, + }; + // The s0/s1 bits select an SGPR or constant instead of a VGPR. + src0 = (ext & 0xFF) | if ext >> 23 & 1 == 0 { 256 } else { 0 }; + if ext >> 31 == 1 { + src1 = vsrc1 - 256; + } + v.neg = (ext >> 20 & 1 | ext >> 27 & 2) as u8; + v.abs = (ext >> 21 & 1 | ext >> 28 & 2) as u8; + if compare { + if ext >> 15 & 1 == 1 { + v.dst = Some(scalar((ext >> 8 & 0x7F) as u8, lanes)); + } + v.sdwa = Some(Sdwa { + dst_sel: 6, + dst_unused: 0, + ..sdwa + }); + } else { + v.clamp = ext >> 13 & 1 == 1; + v.omod = (ext >> 14 & 3) as u8; + v.sdwa = Some(sdwa); + } + } + 0xFA => { + src0 = 256 + (ext & 0xFF); + v.neg = (ext >> 20 & 1 | ext >> 21 & 2) as u8; + v.abs = (ext >> 21 & 1 | ext >> 22 & 2) as u8; + v.dpp = Some(Dpp::Row { + ctrl: (ext >> 8 & 0x1FF) as u16, + row_mask: (ext >> 28) as u8, + bank_mask: (ext >> 24 & 0xF) as u8, + bound_ctrl: ext >> 19 & 1 == 1, + fi: ext >> 18 & 1 == 1, + }); + } + 0xE9 | 0xEA => { + v.dpp = Some(Dpp::Lanes { + sel: ext >> 8, + fi: src0 == 0xEA, + }); + src0 = 256 + (ext & 0xFF); + } + _ => {} + } + let op0 = source(src0, src_n[0], ext); + let op1 = source(src1, src_n[1], ext); + match self.encoding { + Encoding::Vopc => { + let mask = if name.starts_with("v_cmpx") { + EXEC + } else { + VCC + }; + v.dst = v.dst.or(Some(scalar(mask, lanes))); + v.src = vec![op0, op1]; + } + Encoding::Vop1 => { + v.dst = Some(valu_dst(name, w0 >> 17 & 0xFF, dst_n)); + v.src = vec![op0]; + } + _ => { + v.dst = Some(vector(w0 >> 17 & 0xFF, dst_n)); + v.src = match name { + n if n.ends_with("mk_f32") || n.ends_with("mk_f16") => { + vec![op0, Operand::Literal(ext), op1] + } + n if n.ends_with("ak_f32") || n.ends_with("ak_f16") => { + vec![op0, op1, Operand::Literal(ext)] + } + _ => vec![op0, op1], + }; + if carry_in { + v.src.push(scalar(VCC, lanes)); + } + if name.ends_with("_co_ci_u32") { + v.carry = Some(scalar(VCC, lanes)); + } + } + } + } + Encoding::Vop3 | Encoding::Vop3p => { + let w1 = w(1); + let field = |i: u32| w1 >> (9 * i) & 0x1FF; + let count = match self.opcode { + _ if self.encoding == Encoding::Vop3p => { + if name.starts_with("v_pk_") + && !name.contains("_fma_") + && !name.contains("_mad_") + { + 2 + } else { + 3 + } + } + 0x000..0x100 => 2, + 0x100..0x140 => 2 + usize::from(carry_in), + 0x180..0x200 => 1, + _ if VOP3_TWO_SOURCES.contains(&name) => 2, + _ => 3, + }; + v.src = (0..count) + .map(|i| { + let code = field(i as u32); + if i == 0 && name.starts_with("v_interp_") { + Operand::Attr { + index: (code & 0x3F) as u8, + chan: (code >> 6 & 3) as u8, + high: code >> 8 & 1 == 1, + } + } else if i == 2 && carry_in { + source(code, lanes, w(2)) + } else { + source(code, src_n[i], w(2)) + } + }) + .collect(); + v.clamp = w0 >> 15 & 1 == 1; + v.neg = (w1 >> 29) as u8; + if self.encoding == Encoding::Vop3p { + v.neg_hi = (w0 >> 8 & 7) as u8; + v.opsel = (w0 >> 11 & 7) as u8; + v.opsel_hi = (w1 >> 27 & 3 | w0 >> 12 & 4) as u8; + } else { + v.omod = (w1 >> 27 & 3) as u8; + if vop3b { + v.carry = Some(scalar((w0 >> 8 & 0x7F) as u8, lanes)); + } else { + v.abs = (w0 >> 8 & 7) as u8; + v.opsel = (w0 >> 11 & 0xF) as u8; + } + } + let vdst = w0 & 0xFF; + v.dst = Some(if compare { + scalar(vdst as u8, lanes) + } else { + valu_dst(name, vdst, dst_n) + }); + } + _ => unreachable!("not a VALU encoding"), + } + v + } +} + +/// VOP3-only opcodes that take two sources (the rest take three). +const VOP3_TWO_SOURCES: &[&str] = &[ + "v_add_f64", + "v_mul_f64", + "v_min_f64", + "v_max_f64", + "v_ldexp_f64", + "v_mul_lo_u32", + "v_mul_hi_u32", + "v_mul_lo_i32", + "v_mul_hi_i32", + "v_trig_preop_f64", + "v_lshlrev_b64", + "v_lshrrev_b64", + "v_ashrrev_i64", + "v_add_nc_u16", + "v_sub_nc_u16", + "v_mul_lo_u16", + "v_lshrrev_b16", + "v_ashrrev_i16", + "v_max_u16", + "v_max_i16", + "v_min_u16", + "v_min_i16", + "v_add_nc_i16", + "v_sub_nc_i16", + "v_add_co_u32", + "v_sub_co_u32", + "v_subrev_co_u32", + "v_pack_b32_f16", + "v_cvt_pknorm_i16_f16", + "v_cvt_pknorm_u16_f16", + "v_lshlrev_b16", + "v_interp_p1ll_f16", + "v_readlane_b32", + "v_writelane_b32", + "v_ldexp_f32", + "v_bfm_b32", + "v_bcnt_u32_b32", + "v_mbcnt_lo_u32_b32", + "v_mbcnt_hi_u32_b32", + "v_cvt_pknorm_i16_f32", + "v_cvt_pknorm_u16_f32", + "v_cvt_pk_u16_u32", + "v_cvt_pk_i16_i32", + "v_sub_nc_i32", + "v_add_nc_i32", +]; + +/// VOP3 opcodes whose bits 14:8 hold a scalar destination instead of `abs`/`opsel`. +const VOP3B: &[&str] = &[ + "v_add_co_u32", + "v_sub_co_u32", + "v_subrev_co_u32", + "v_add_co_ci_u32", + "v_sub_co_ci_u32", + "v_subrev_co_ci_u32", + "v_div_scale_f32", + "v_div_scale_f64", + "v_mad_u64_u32", + "v_mad_i64_i32", +]; + +fn scalar(code: u8, dwords: u8) -> Operand { + Operand::Scalar { code, dwords } +} + +fn vector(reg: u32, dwords: u8) -> Operand { + Operand::Vector { + reg: reg as u8, + dwords, + } +} + +/// A 9-bit source field (8-bit scalar fields are the same codes below 256). +fn source(code: u32, dwords: u8, literal: u32) -> Operand { + match code { + 0..=127 => scalar(code as u8, dwords), + 255 => Operand::Literal(literal), + 256.. => vector(code - 256, dwords), + _ => Operand::Const(code as u8), + } +} + +/// VALU destinations that are SGPRs. +fn valu_dst(name: &str, field: u32, dwords: u8) -> Operand { + match name { + "v_readlane_b32" | "v_readfirstlane_b32" => scalar(field as u8, 1), + _ => vector(field, dwords), + } +} + +/// LDS opcodes on two addresses (`ds_read2_b32`...), with `offset0`/`offset1`. +pub(super) fn ds_pair(name: &str) -> bool { + name.split('_').any(|t| { + ["read2", "write2", "wrxchg2"] + .iter() + .any(|p| t.starts_with(p)) + }) +} + +/// Dwords of a type suffix such as `b64` or `f32`. +fn type_dwords(token: &str) -> u8 { + match token { + "b64" | "u64" | "i64" | "f64" => 2, + _ => 1, + } +} + +/// (sdst, ssrc0, ssrc1) dwords of a scalar ALU opcode. +fn salu_dwords(name: &str) -> (u8, u8, u8) { + match name { + "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" | "s_bfe_u64" | "s_bfe_i64" + | "s_bitcmp0_b64" | "s_bitcmp1_b64" => (2, 2, 1), + "s_bfm_b64" | "s_bitset0_b64" | "s_bitset1_b64" | "s_bitreplicate_b64_b32" => (2, 1, 1), + "s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64" + | "s_flbit_i32_b64" | "s_flbit_i32_i64" => (1, 2, 2), + _ => { + let n = type_dwords(name.rsplit('_').next().unwrap_or("")); + (n, n, n) + } + } +} + +/// (vdst, [src0, src1, src2]) dwords of a VALU opcode. +fn valu_dwords(name: &str) -> (u8, [u8; 3]) { + let parts: Vec<&str> = name.split('_').collect(); + match name { + "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => (2, [1, 2, 2]), + "v_ldexp_f64" | "v_trig_preop_f64" | "v_cmp_class_f64" | "v_cmpx_class_f64" => { + (2, [2, 1, 2]) + } + "v_mad_u64_u32" | "v_mad_i64_i32" => (2, [1, 1, 2]), + "v_qsad_pk_u16_u8" | "v_mqsad_pk_u16_u8" => (2, [2, 1, 2]), + "v_mqsad_u32_u8" => (4, [2, 1, 4]), + "v_frexp_exp_i32_f64" => (1, [2; 3]), + _ if parts.len() == 4 && parts[1] == "cvt" => { + (type_dwords(parts[2]), [type_dwords(parts[3]); 3]) + } + _ => { + let n = type_dwords(parts.last().copied().unwrap_or("")); + (n, [n; 3]) + } + } +} + +/// Dwords of loaded, stored or atomic data, from the opcode name. +fn data_dwords(name: &str) -> u8 { + let mut n: u8 = 1; + for token in name.split('_') { + n = match token { + "dwordx2" | "x2" | "xy" | "b64" | "u64" | "i64" | "f64" => 2, + "dwordx3" | "xyz" | "b96" => 3, + "dwordx4" | "xyzw" | "b128" => 4, + "dwordx8" => 8, + "dwordx16" => 16, + _ => n, + }; + } + if name.contains("cmpswap") { + n *= 2; + } + if name.contains("format_d16") { + n = n.div_ceil(2); + } + n +} + +/// Address dwords of an image opcode: offset, bias, compare, derivatives, +/// 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. + const DIMS: [(u8, u8); 8] = [ + (1, 1), + (2, 2), + (3, 3), + (3, 2), + (2, 1), + (3, 2), + (3, 2), + (4, 2), + ]; + let (coords, grads) = DIMS[usize::from(dim & 7)]; + match name { + "image_bvh_intersect_ray" => return if a16 { 8 } else { 11 }, + "image_bvh64_intersect_ray" => return if a16 { 9 } else { 12 }, + "image_get_resinfo" => return 1, + _ => {} + } + let (mut whole, mut derivs, mut packed): (u8, u8, u8) = (0, 0, coords); + if let Some(rest) = name + .strip_prefix("image_sample") + .or_else(|| name.strip_prefix("image_gather4")) + { + for token in rest.split('_') { + match token { + "o" | "b" | "c" => whole += 1, + "d" | "cd" => derivs = grads, + "l" | "cl" => packed += 1, + _ => {} + } + } + } else if name.contains("_mip") { + packed += 1; + } + if a16 { + whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2) + } else { + whole + 2 * derivs + packed + } +} diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs new file mode 100644 index 000000000..f029ff405 --- /dev/null +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -0,0 +1,496 @@ +//! GFX10 machine code: instruction boundaries, encodings and opcodes. +//! +//! Instructions are found by following control flow from offset 0, not by a +//! linear sweep: compilers place data (constant tables) in the code region +//! after the end of the program. [`Instruction::fields`] decodes the operand +//! fields and [`Instruction::text`] prints them in AMD's SP3 syntax. +//! +//! Encodings by the top bits of the first dword: +//! +//! ```text +//! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC +//! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP +//! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH +//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP +//! ``` + +mod fields; +mod opcodes; +mod sp3; + +pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu}; + +use std::collections::BTreeMap; + +use crate::ShaderError; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Encoding { + Sop2, + Sopk, + Sop1, + Sopc, + Sopp, + Smem, + Vop2, + Vop1, + Vopc, + Vop3, + Vop3p, + Vintrp, + Ds, + Mubuf, + Mtbuf, + Mimg, + Exp, + Flat, + Global, + Scratch, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Instruction { + /// Byte offset in the program. + pub offset: usize, + pub encoding: Encoding, + pub opcode: u16, + /// Every dword of the instruction, including literals and extra dwords. + pub words: Vec<u32>, +} + +impl Instruction { + /// AMD's name for the opcode, if it is in our table. + pub fn name(&self) -> Option<&'static str> { + name(self.encoding, self.opcode) + } +} + +/// Decodes every instruction reachable from offset 0, sorted by offset. +pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> { + if !code.len().is_multiple_of(4) { + return Err(isa(code.len(), "code size is not a multiple of 4")); + } + let mut found = BTreeMap::new(); + let mut pending = vec![0usize]; + while let Some(mut offset) = pending.pop() { + while !found.contains_key(&offset) { + let inst = instruction(code, offset)?; + let next = offset + 4 * inst.words.len(); + let flow = control(&inst, code.len(), |at| { + found.range(..at).next_back().map(|(_, i)| i) + })?; + found.insert(offset, inst); + match flow { + Flow::Next => offset = next, + Flow::Stop => break, + Flow::Jump(target) => offset = target, + Flow::Branch(target) => { + pending.push(target); + offset = next; + } + } + } + } + let list: Vec<Instruction> = found.into_values().collect(); + if let Some(w) = list + .windows(2) + .find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset) + { + return Err(isa(w[1].offset, "a branch lands inside an instruction")); + } + Ok(list) +} + +/// Where execution goes after an instruction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Flow { + Next, + /// End of the program, or an indirect jump that is not a far jump. + Stop, + Jump(usize), + /// Conditional: to the target or the next instruction. + Branch(usize), +} + +/// Control flow after `inst`, resolving far jumps. `before(at)` returns the +/// decoded instruction with the highest offset below `at`, if any. +pub(crate) fn control<'a>( + inst: &Instruction, + len: usize, + before: impl Fn(usize) -> Option<&'a Instruction>, +) -> Result<Flow, ShaderError> { + Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? { + Flow::Stop if inst.name() == Some("s_setpc_b64") => { + far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump) + } + flow => flow, + }) +} + +fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> { + let target = || { + let delta = 4 * i64::from(inst.words[0] as u16 as i16); + usize::try_from(next as i64 + delta) + .ok() + .filter(|&t| t < len) + .ok_or(isa(inst.offset, "branch target outside the code")) + }; + Ok(match (inst.encoding, inst.name().unwrap_or("")) { + ( + Encoding::Sopp, + "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end", + ) => Flow::Stop, + (Encoding::Sopp, "s_branch") => Flow::Jump(target()?), + (Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?), + (Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?), + // Indirect jump; `decode` resolves the compiler's far-jump form. + (Encoding::Sop1, "s_setpc_b64") => Flow::Stop, + _ => Flow::Next, + }) +} + +/// Resolves the far jump compilers emit beyond the reach of a branch offset: +/// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry +/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line +/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next +/// merged stage through registers) gives `None`. +fn far_jump<'a>( + before: impl Fn(usize) -> Option<&'a Instruction>, + setpc: &Instruction, + len: usize, +) -> Result<Option<usize>, ShaderError> { + let n = setpc.words[0] & 0xFF; + let mut delta = None; + let mut at = setpc.offset; + for _ in 0..4 { + let Some(prev) = before(at) else { + break; + }; + if prev.offset + 4 * prev.words.len() != at { + break; + } + let w = prev.words[0]; + let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF); + match (prev.encoding, prev.name()) { + (Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32"))) + if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() => + { + // The low dword of a signed 64-bit offset: a backward jump + // adds a negative one (its high dword is -1). + let literal = i64::from(prev.words[1] as i32); + delta = Some(if op == "s_add_u32" { literal } else { -literal }); + } + (Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => { + let Some(delta) = delta else { break }; + // s_getpc_b64 yields the address of the instruction after it. + return usize::try_from(prev.offset as i64 + 4 + delta) + .ok() + .filter(|&t| t < len) + .map(Some) + .ok_or(isa(setpc.offset, "far jump target outside the code")); + } + _ => {} + } + at = prev.offset; + } + Ok(None) +} + +fn instruction(code: &[u8], offset: usize) -> Result<Instruction, ShaderError> { + let word = |i: usize| { + code.get(offset + 4 * i..offset + 4 * i + 4) + .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) + .ok_or(isa(offset, "instruction runs past the end of the code")) + }; + let w = word(0)?; + let (encoding, opcode, len) = if w >> 31 == 0 { + let src0 = w & 0x1FF; + // Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive. + let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA)); + match w >> 25 { + 0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra), + 0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra), + op => { + let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| { + matches!( + n, + "v_madmk_f32" + | "v_madak_f32" + | "v_fmamk_f32" + | "v_fmaak_f32" + | "v_madmk_f16" + | "v_madak_f16" + | "v_fmamk_f16" + | "v_fmaak_f16" + ) + }); + (Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak))) + } + } + } else if w >> 30 == 0b10 { + let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF)); + match w >> 23 { + 0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])), + 0x17E => ( + Encoding::Sopc, + (w >> 16) & 0x7F, + literal(&[w & 0xFF, (w >> 8) & 0xFF]), + ), + 0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1), + _ if w >> 28 == 0b1011 => { + let op = (w >> 23) & 0x1F; + let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32"); + (Encoding::Sopk, op, 1 + usize::from(imm32)) + } + _ => ( + Encoding::Sop2, + (w >> 23) & 0x7F, + literal(&[w & 0xFF, (w >> 8) & 0xFF]), + ), + } + } else { + let vop3 = + |w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF)); + match w >> 26 { + 0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1), + 0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)), + 0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)), + 0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2), + 0x37 => { + let encoding = match (w >> 14) & 3 { + 0 => Encoding::Flat, + 1 => Encoding::Scratch, + 2 => Encoding::Global, + _ => return Err(isa(offset, "reserved FLAT segment")), + }; + (encoding, (w >> 18) & 0x7F, 2) + } + 0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2), + 0x3A => ( + Encoding::Mtbuf, + (w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3, + 2, + ), + // Bits 2:1 count extra dwords of non-sequential address registers. + 0x3C => ( + Encoding::Mimg, + (w >> 18) & 0x7F | (w & 1) << 7, + 2 + (w as usize >> 1 & 3), + ), + 0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2), + 0x3E => (Encoding::Exp, 0, 2), + _ => return Err(isa(offset, "unknown encoding")), + } + }; + Ok(Instruction { + offset, + encoding, + opcode: opcode as u16, + words: (0..len).map(word).collect::<Result<_, _>>()?, + }) +} + +fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> { + use opcodes as t; + let (table, op) = match encoding { + Encoding::Sop2 => (t::SOP2, opcode), + Encoding::Sopk => (t::SOPK, opcode), + Encoding::Sop1 => (t::SOP1, opcode), + Encoding::Sopc => (t::SOPC, opcode), + Encoding::Sopp => (t::SOPP, opcode), + Encoding::Smem => (t::SMEM, opcode), + Encoding::Vop2 => (t::VOP2, opcode), + Encoding::Vop1 => (t::VOP1, opcode), + Encoding::Vopc => (t::VOPC, opcode), + // VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases. + Encoding::Vop3 => match opcode { + 0x000..0x100 => (t::VOPC, opcode), + 0x100..0x140 => (t::VOP2, opcode - 0x100), + 0x180..0x200 => (t::VOP1, opcode - 0x180), + _ => (t::VOP3, opcode), + }, + Encoding::Vop3p => (t::VOP3P, opcode), + Encoding::Vintrp => (t::VINTRP, opcode), + Encoding::Ds => (t::DS, opcode), + Encoding::Mubuf => (t::MUBUF, opcode), + Encoding::Mtbuf => (t::MTBUF, opcode), + Encoding::Mimg => (t::MIMG, opcode), + Encoding::Exp => return Some("exp"), + Encoding::Flat => (t::FLAT, opcode), + Encoding::Global => (t::GLOBAL, opcode), + Encoding::Scratch => (t::SCRATCH, opcode), + }; + table + .binary_search_by_key(&op, |&(o, _)| o) + .ok() + .map(|i| table[i].1) +} + +fn isa(offset: usize, reason: &'static str) -> ShaderError { + ShaderError::Isa { offset, reason } +} + +#[cfg(test)] +mod tests { + use super::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + /// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction. + const fn sopp(op: u32, simm16: i16) -> u32 { + 0xBF80_0000 | op << 16 | simm16 as u16 as u32 + } + + fn bytes(words: &[u32]) -> Vec<u8> { + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> { + decode(&bytes(code)) + .unwrap() + .iter() + .map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?"))) + .collect() + } + + #[test] + fn tables_are_sorted() { + for t in [ + opcodes::SOP2, + opcodes::SOPK, + opcodes::SOP1, + opcodes::SOPC, + opcodes::SOPP, + opcodes::SMEM, + opcodes::VOP2, + opcodes::VOP1, + opcodes::VOPC, + opcodes::VOP3, + opcodes::VOP3P, + opcodes::VINTRP, + opcodes::DS, + opcodes::MUBUF, + opcodes::MTBUF, + opcodes::MIMG, + opcodes::FLAT, + opcodes::GLOBAL, + opcodes::SCRATCH, + ] { + assert!(t.windows(2).all(|w| w[0].0 < w[1].0)); + } + } + + #[test] + fn lengths_and_names() { + let code = [ + 0xBE80_03FF, + 0x3F80_0000, // s_mov_b32 s0, literal + 0x0600_0000, // v_add_f32 v0, s0, v0 + 0xD54B_0000, + 0x03FE_0000, + 0x4000_0000, // v_fma_f32 with a literal src2 + 0xF080_0F0A, + 0, + 0, // image_sample (2D) with one extra address dword + 0xF800_080F, + 0, // exp + S_ENDPGM, + ]; + assert_eq!( + summary(&code), + [ + (0, 2, "s_mov_b32"), + (8, 1, "v_add_f32"), + (12, 3, "v_fma_f32"), + (24, 3, "image_sample"), + (36, 2, "exp"), + (44, 1, "s_endpgm"), + ] + ); + } + + #[test] + fn follows_branches_and_skips_data() { + let code = [ + sopp(0x04, 1), // s_cbranch_scc0 -> 8 + sopp(0x02, 1), // s_branch -> 12 + S_ENDPGM, + S_ENDPGM, + S_ENDPGM, // data follows the program end + 0xFFFF_FFFF, + ]; + let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect(); + assert_eq!(found, [0, 4, 8, 12]); + } + + #[test] + fn follows_far_jumps() { + let code = [ + 0xBE88_1F00, // s_getpc_b64 s[8:9] + 0x8008_FF08, + 20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24 + 0x8209_8009, // s_addc_u32 s9, s9, 0 + 0xBE80_2008, // s_setpc_b64 s[8:9] + 0xFFFF_FFFF, // not code + S_ENDPGM, + ]; + let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect(); + assert_eq!( + found, + [ + (0, "s_getpc_b64"), + (4, "s_add_u32"), + (12, "s_addc_u32"), + (16, "s_setpc_b64"), + (24, "s_endpgm"), + ] + ); + // Through other registers (a handover to another stage): the path ends. + assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1); + } + + #[test] + fn follows_far_jumps_backward() { + // The compiler's backward far jump adds a negative offset: the low + // dword as a 32-bit literal, the high dword as -1 with the carry. + let code = [ + sopp(0x02, 1), // s_branch -> 8, past the jump target + S_ENDPGM, // the far jump's target: only it reaches here + 0xBE88_1F00, // s_getpc_b64 s[8:9] + 0x8008_FF08, + 0xFFFF_FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4 + 0x8209_C109, // s_addc_u32 s9, s9, -1 + 0xBE80_2008, // s_setpc_b64 s[8:9] + ]; + let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect(); + assert_eq!( + found, + [ + (0, "s_branch"), + (4, "s_endpgm"), + (8, "s_getpc_b64"), + (12, "s_add_u32"), + (20, "s_addc_u32"), + (24, "s_setpc_b64"), + ] + ); + } + + #[test] + fn rejects_bad_code() { + assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4"); + assert!( + decode(&bytes(&[sopp(0x02, 100)])).is_err(), + "branch out of range" + ); + assert!( + decode(&bytes(&[0xBE80_03FF])).is_err(), + "literal past the end" + ); + assert!( + decode(&bytes(&[0xE400_0000, 0])).is_err(), + "unknown encoding" + ); + // s_cbranch_scc0 into the literal of the s_mov_b32 at 4. + assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err()); + } +} diff --git a/crates/victory-shader/src/gfx10/opcodes.rs b/crates/victory-shader/src/gfx10/opcodes.rs new file mode 100644 index 000000000..d1ba275aa --- /dev/null +++ b/crates/victory-shader/src/gfx10/opcodes.rs @@ -0,0 +1,1333 @@ +// GFX10 opcode names, generated from Mesa's src/amd/compiler/aco_opcodes.py +// (tag mesa-22.3.0, GFX10 column), which carries this notice: +// +// Copyright (c) 2018 Valve Corporation +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice (including the next +// paragraph) shall be included in all copies or substantial portions of the +// Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// +// Each table is sorted by opcode. VOP3 holds only VOP3-only opcodes; VOP3 +// encodings of VOPC/VOP2/VOP1 ops (0x000-0x13f, 0x180-0x1ff) use those tables. + +pub(super) const SOP2: &[(u16, &str)] = &[ + (0x000, "s_add_u32"), + (0x001, "s_sub_u32"), + (0x002, "s_add_i32"), + (0x003, "s_sub_i32"), + (0x004, "s_addc_u32"), + (0x005, "s_subb_u32"), + (0x006, "s_min_i32"), + (0x007, "s_min_u32"), + (0x008, "s_max_i32"), + (0x009, "s_max_u32"), + (0x00a, "s_cselect_b32"), + (0x00b, "s_cselect_b64"), + (0x00e, "s_and_b32"), + (0x00f, "s_and_b64"), + (0x010, "s_or_b32"), + (0x011, "s_or_b64"), + (0x012, "s_xor_b32"), + (0x013, "s_xor_b64"), + (0x014, "s_andn2_b32"), + (0x015, "s_andn2_b64"), + (0x016, "s_orn2_b32"), + (0x017, "s_orn2_b64"), + (0x018, "s_nand_b32"), + (0x019, "s_nand_b64"), + (0x01a, "s_nor_b32"), + (0x01b, "s_nor_b64"), + (0x01c, "s_xnor_b32"), + (0x01d, "s_xnor_b64"), + (0x01e, "s_lshl_b32"), + (0x01f, "s_lshl_b64"), + (0x020, "s_lshr_b32"), + (0x021, "s_lshr_b64"), + (0x022, "s_ashr_i32"), + (0x023, "s_ashr_i64"), + (0x024, "s_bfm_b32"), + (0x025, "s_bfm_b64"), + (0x026, "s_mul_i32"), + (0x027, "s_bfe_u32"), + (0x028, "s_bfe_i32"), + (0x029, "s_bfe_u64"), + (0x02a, "s_bfe_i64"), + (0x02c, "s_absdiff_i32"), + (0x02e, "s_lshl1_add_u32"), + (0x02f, "s_lshl2_add_u32"), + (0x030, "s_lshl3_add_u32"), + (0x031, "s_lshl4_add_u32"), + (0x032, "s_pack_ll_b32_b16"), + (0x033, "s_pack_lh_b32_b16"), + (0x034, "s_pack_hh_b32_b16"), + (0x035, "s_mul_hi_u32"), + (0x036, "s_mul_hi_i32"), +]; + +pub(super) const SOPK: &[(u16, &str)] = &[ + (0x000, "s_movk_i32"), + (0x001, "s_version"), + (0x002, "s_cmovk_i32"), + (0x003, "s_cmpk_eq_i32"), + (0x004, "s_cmpk_lg_i32"), + (0x005, "s_cmpk_gt_i32"), + (0x006, "s_cmpk_ge_i32"), + (0x007, "s_cmpk_lt_i32"), + (0x008, "s_cmpk_le_i32"), + (0x009, "s_cmpk_eq_u32"), + (0x00a, "s_cmpk_lg_u32"), + (0x00b, "s_cmpk_gt_u32"), + (0x00c, "s_cmpk_ge_u32"), + (0x00d, "s_cmpk_lt_u32"), + (0x00e, "s_cmpk_le_u32"), + (0x00f, "s_addk_i32"), + (0x010, "s_mulk_i32"), + (0x012, "s_getreg_b32"), + (0x013, "s_setreg_b32"), + (0x015, "s_setreg_imm32_b32"), + (0x016, "s_call_b64"), + (0x017, "s_waitcnt_vscnt"), + (0x018, "s_waitcnt_vmcnt"), + (0x019, "s_waitcnt_expcnt"), + (0x01a, "s_waitcnt_lgkmcnt"), + (0x01b, "s_subvector_loop_begin"), + (0x01c, "s_subvector_loop_end"), +]; + +pub(super) const SOP1: &[(u16, &str)] = &[ + (0x003, "s_mov_b32"), + (0x004, "s_mov_b64"), + (0x005, "s_cmov_b32"), + (0x006, "s_cmov_b64"), + (0x007, "s_not_b32"), + (0x008, "s_not_b64"), + (0x009, "s_wqm_b32"), + (0x00a, "s_wqm_b64"), + (0x00b, "s_brev_b32"), + (0x00c, "s_brev_b64"), + (0x00d, "s_bcnt0_i32_b32"), + (0x00e, "s_bcnt0_i32_b64"), + (0x00f, "s_bcnt1_i32_b32"), + (0x010, "s_bcnt1_i32_b64"), + (0x011, "s_ff0_i32_b32"), + (0x012, "s_ff0_i32_b64"), + (0x013, "s_ff1_i32_b32"), + (0x014, "s_ff1_i32_b64"), + (0x015, "s_flbit_i32_b32"), + (0x016, "s_flbit_i32_b64"), + (0x017, "s_flbit_i32"), + (0x018, "s_flbit_i32_i64"), + (0x019, "s_sext_i32_i8"), + (0x01a, "s_sext_i32_i16"), + (0x01b, "s_bitset0_b32"), + (0x01c, "s_bitset0_b64"), + (0x01d, "s_bitset1_b32"), + (0x01e, "s_bitset1_b64"), + (0x01f, "s_getpc_b64"), + (0x020, "s_setpc_b64"), + (0x021, "s_swappc_b64"), + (0x022, "s_rfe_b64"), + (0x024, "s_and_saveexec_b64"), + (0x025, "s_or_saveexec_b64"), + (0x026, "s_xor_saveexec_b64"), + (0x027, "s_andn2_saveexec_b64"), + (0x028, "s_orn2_saveexec_b64"), + (0x029, "s_nand_saveexec_b64"), + (0x02a, "s_nor_saveexec_b64"), + (0x02b, "s_xnor_saveexec_b64"), + (0x02c, "s_quadmask_b32"), + (0x02d, "s_quadmask_b64"), + (0x02e, "s_movrels_b32"), + (0x02f, "s_movrels_b64"), + (0x030, "s_movreld_b32"), + (0x031, "s_movreld_b64"), + (0x034, "s_abs_i32"), + (0x035, "s_mov_fed_b32"), + (0x037, "s_andn1_saveexec_b64"), + (0x038, "s_orn1_saveexec_b64"), + (0x039, "s_andn1_wrexec_b64"), + (0x03a, "s_andn2_wrexec_b64"), + (0x03b, "s_bitreplicate_b64_b32"), + (0x03c, "s_and_saveexec_b32"), + (0x03d, "s_or_saveexec_b32"), + (0x03e, "s_xor_saveexec_b32"), + (0x03f, "s_andn2_saveexec_b32"), + (0x040, "s_orn2_saveexec_b32"), + (0x041, "s_nand_saveexec_b32"), + (0x042, "s_nor_saveexec_b32"), + (0x043, "s_xnor_saveexec_b32"), + (0x044, "s_andn1_saveexec_b32"), + (0x045, "s_orn1_saveexec_b32"), + (0x046, "s_andn1_wrexec_b32"), + (0x047, "s_andn2_wrexec_b32"), + (0x049, "s_movrelsd_2_b32"), +]; + +pub(super) const SOPC: &[(u16, &str)] = &[ + (0x000, "s_cmp_eq_i32"), + (0x001, "s_cmp_lg_i32"), + (0x002, "s_cmp_gt_i32"), + (0x003, "s_cmp_ge_i32"), + (0x004, "s_cmp_lt_i32"), + (0x005, "s_cmp_le_i32"), + (0x006, "s_cmp_eq_u32"), + (0x007, "s_cmp_lg_u32"), + (0x008, "s_cmp_gt_u32"), + (0x009, "s_cmp_ge_u32"), + (0x00a, "s_cmp_lt_u32"), + (0x00b, "s_cmp_le_u32"), + (0x00c, "s_bitcmp0_b32"), + (0x00d, "s_bitcmp1_b32"), + (0x00e, "s_bitcmp0_b64"), + (0x00f, "s_bitcmp1_b64"), + (0x012, "s_cmp_eq_u64"), + (0x013, "s_cmp_lg_u64"), +]; + +pub(super) const SOPP: &[(u16, &str)] = &[ + (0x000, "s_nop"), + (0x001, "s_endpgm"), + (0x002, "s_branch"), + (0x003, "s_wakeup"), + (0x004, "s_cbranch_scc0"), + (0x005, "s_cbranch_scc1"), + (0x006, "s_cbranch_vccz"), + (0x007, "s_cbranch_vccnz"), + (0x008, "s_cbranch_execz"), + (0x009, "s_cbranch_execnz"), + (0x00a, "s_barrier"), + (0x00b, "s_setkill"), + (0x00c, "s_waitcnt"), + (0x00d, "s_sethalt"), + (0x00e, "s_sleep"), + (0x00f, "s_setprio"), + (0x010, "s_sendmsg"), + (0x011, "s_sendmsghalt"), + (0x012, "s_trap"), + (0x013, "s_icache_inv"), + (0x014, "s_incperflevel"), + (0x015, "s_decperflevel"), + (0x016, "s_ttracedata"), + (0x017, "s_cbranch_cdbgsys"), + (0x018, "s_cbranch_cdbguser"), + (0x019, "s_cbranch_cdbgsys_or_user"), + (0x01a, "s_cbranch_cdbgsys_and_user"), + (0x01b, "s_endpgm_saved"), + (0x01e, "s_endpgm_ordered_ps_done"), + (0x01f, "s_code_end"), + (0x020, "s_inst_prefetch"), + (0x021, "s_clause"), + (0x022, "s_wait_idle"), + (0x023, "s_waitcnt_depctr"), + (0x024, "s_round_mode"), + (0x025, "s_denorm_mode"), + (0x028, "s_ttracedata_imm"), +]; + +pub(super) const SMEM: &[(u16, &str)] = &[ + (0x000, "s_load_dword"), + (0x001, "s_load_dwordx2"), + (0x002, "s_load_dwordx4"), + (0x003, "s_load_dwordx8"), + (0x004, "s_load_dwordx16"), + (0x005, "s_scratch_load_dword"), + (0x006, "s_scratch_load_dwordx2"), + (0x007, "s_scratch_load_dwordx4"), + (0x008, "s_buffer_load_dword"), + (0x009, "s_buffer_load_dwordx2"), + (0x00a, "s_buffer_load_dwordx4"), + (0x00b, "s_buffer_load_dwordx8"), + (0x00c, "s_buffer_load_dwordx16"), + (0x010, "s_store_dword"), + (0x011, "s_store_dwordx2"), + (0x012, "s_store_dwordx4"), + (0x015, "s_scratch_store_dword"), + (0x016, "s_scratch_store_dwordx2"), + (0x017, "s_scratch_store_dwordx4"), + (0x018, "s_buffer_store_dword"), + (0x019, "s_buffer_store_dwordx2"), + (0x01a, "s_buffer_store_dwordx4"), + (0x01f, "s_gl1_inv"), + (0x020, "s_dcache_inv"), + (0x021, "s_dcache_wb"), + (0x024, "s_memtime"), + (0x025, "s_memrealtime"), + (0x026, "s_atc_probe"), + (0x027, "s_atc_probe_buffer"), + (0x028, "s_dcache_discard"), + (0x029, "s_dcache_discard_x2"), + (0x02a, "s_get_waveid_in_workgroup"), + (0x040, "s_buffer_atomic_swap"), + (0x041, "s_buffer_atomic_cmpswap"), + (0x042, "s_buffer_atomic_add"), + (0x043, "s_buffer_atomic_sub"), + (0x044, "s_buffer_atomic_smin"), + (0x045, "s_buffer_atomic_umin"), + (0x046, "s_buffer_atomic_smax"), + (0x047, "s_buffer_atomic_umax"), + (0x048, "s_buffer_atomic_and"), + (0x049, "s_buffer_atomic_or"), + (0x04a, "s_buffer_atomic_xor"), + (0x04b, "s_buffer_atomic_inc"), + (0x04c, "s_buffer_atomic_dec"), + (0x060, "s_buffer_atomic_swap_x2"), + (0x061, "s_buffer_atomic_cmpswap_x2"), + (0x062, "s_buffer_atomic_add_x2"), + (0x063, "s_buffer_atomic_sub_x2"), + (0x064, "s_buffer_atomic_smin_x2"), + (0x065, "s_buffer_atomic_umin_x2"), + (0x066, "s_buffer_atomic_smax_x2"), + (0x067, "s_buffer_atomic_umax_x2"), + (0x068, "s_buffer_atomic_and_x2"), + (0x069, "s_buffer_atomic_or_x2"), + (0x06a, "s_buffer_atomic_xor_x2"), + (0x06b, "s_buffer_atomic_inc_x2"), + (0x06c, "s_buffer_atomic_dec_x2"), + (0x080, "s_atomic_swap"), + (0x081, "s_atomic_cmpswap"), + (0x082, "s_atomic_add"), + (0x083, "s_atomic_sub"), + (0x084, "s_atomic_smin"), + (0x085, "s_atomic_umin"), + (0x086, "s_atomic_smax"), + (0x087, "s_atomic_umax"), + (0x088, "s_atomic_and"), + (0x089, "s_atomic_or"), + (0x08a, "s_atomic_xor"), + (0x08b, "s_atomic_inc"), + (0x08c, "s_atomic_dec"), + (0x0a0, "s_atomic_swap_x2"), + (0x0a1, "s_atomic_cmpswap_x2"), + (0x0a2, "s_atomic_add_x2"), + (0x0a3, "s_atomic_sub_x2"), + (0x0a4, "s_atomic_smin_x2"), + (0x0a5, "s_atomic_umin_x2"), + (0x0a6, "s_atomic_smax_x2"), + (0x0a7, "s_atomic_umax_x2"), + (0x0a8, "s_atomic_and_x2"), + (0x0a9, "s_atomic_or_x2"), + (0x0aa, "s_atomic_xor_x2"), + (0x0ab, "s_atomic_inc_x2"), + (0x0ac, "s_atomic_dec_x2"), +]; + +pub(super) const VOP2: &[(u16, &str)] = &[ + (0x001, "v_cndmask_b32"), + (0x002, "v_dot2c_f32_f16"), + (0x003, "v_add_f32"), + (0x004, "v_sub_f32"), + (0x005, "v_subrev_f32"), + (0x006, "v_mac_legacy_f32"), + (0x007, "v_mul_legacy_f32"), + (0x008, "v_mul_f32"), + (0x009, "v_mul_i32_i24"), + (0x00a, "v_mul_hi_i32_i24"), + (0x00b, "v_mul_u32_u24"), + (0x00c, "v_mul_hi_u32_u24"), + (0x00d, "v_dot4c_i32_i8"), + (0x00f, "v_min_f32"), + (0x010, "v_max_f32"), + (0x011, "v_min_i32"), + (0x012, "v_max_i32"), + (0x013, "v_min_u32"), + (0x014, "v_max_u32"), + (0x016, "v_lshrrev_b32"), + (0x018, "v_ashrrev_i32"), + (0x01a, "v_lshlrev_b32"), + (0x01b, "v_and_b32"), + (0x01c, "v_or_b32"), + (0x01d, "v_xor_b32"), + (0x01e, "v_xnor_b32"), + (0x01f, "v_mac_f32"), + (0x020, "v_madmk_f32"), + (0x021, "v_madak_f32"), + (0x025, "v_add_nc_u32"), + (0x026, "v_sub_nc_u32"), + (0x027, "v_subrev_nc_u32"), + (0x028, "v_add_co_ci_u32"), + (0x029, "v_sub_co_ci_u32"), + (0x02a, "v_subrev_co_ci_u32"), + (0x02b, "v_fmac_f32"), + (0x02c, "v_fmamk_f32"), + (0x02d, "v_fmaak_f32"), + (0x02f, "v_cvt_pkrtz_f16_f32"), + (0x032, "v_add_f16"), + (0x033, "v_sub_f16"), + (0x034, "v_subrev_f16"), + (0x035, "v_mul_f16"), + (0x036, "v_fmac_f16"), + (0x037, "v_fmamk_f16"), + (0x038, "v_fmaak_f16"), + (0x039, "v_max_f16"), + (0x03a, "v_min_f16"), + (0x03b, "v_ldexp_f16"), + (0x03c, "v_pk_fmac_f16"), +]; + +pub(super) const VOP1: &[(u16, &str)] = &[ + (0x000, "v_nop"), + (0x001, "v_mov_b32"), + (0x002, "v_readfirstlane_b32"), + (0x003, "v_cvt_i32_f64"), + (0x004, "v_cvt_f64_i32"), + (0x005, "v_cvt_f32_i32"), + (0x006, "v_cvt_f32_u32"), + (0x007, "v_cvt_u32_f32"), + (0x008, "v_cvt_i32_f32"), + (0x00a, "v_cvt_f16_f32"), + (0x00b, "v_cvt_f32_f16"), + (0x00c, "v_cvt_rpi_i32_f32"), + (0x00d, "v_cvt_flr_i32_f32"), + (0x00e, "v_cvt_off_f32_i4"), + (0x00f, "v_cvt_f32_f64"), + (0x010, "v_cvt_f64_f32"), + (0x011, "v_cvt_f32_ubyte0"), + (0x012, "v_cvt_f32_ubyte1"), + (0x013, "v_cvt_f32_ubyte2"), + (0x014, "v_cvt_f32_ubyte3"), + (0x015, "v_cvt_u32_f64"), + (0x016, "v_cvt_f64_u32"), + (0x017, "v_trunc_f64"), + (0x018, "v_ceil_f64"), + (0x019, "v_rndne_f64"), + (0x01a, "v_floor_f64"), + (0x01b, "v_pipeflush"), + (0x020, "v_fract_f32"), + (0x021, "v_trunc_f32"), + (0x022, "v_ceil_f32"), + (0x023, "v_rndne_f32"), + (0x024, "v_floor_f32"), + (0x025, "v_exp_f32"), + (0x027, "v_log_f32"), + (0x02a, "v_rcp_f32"), + (0x02b, "v_rcp_iflag_f32"), + (0x02e, "v_rsq_f32"), + (0x02f, "v_rcp_f64"), + (0x031, "v_rsq_f64"), + (0x033, "v_sqrt_f32"), + (0x034, "v_sqrt_f64"), + (0x035, "v_sin_f32"), + (0x036, "v_cos_f32"), + (0x037, "v_not_b32"), + (0x038, "v_bfrev_b32"), + (0x039, "v_ffbh_u32"), + (0x03a, "v_ffbl_b32"), + (0x03b, "v_ffbh_i32"), + (0x03c, "v_frexp_exp_i32_f64"), + (0x03d, "v_frexp_mant_f64"), + (0x03e, "v_fract_f64"), + (0x03f, "v_frexp_exp_i32_f32"), + (0x040, "v_frexp_mant_f32"), + (0x041, "v_clrexcp"), + (0x042, "v_movreld_b32"), + (0x043, "v_movrels_b32"), + (0x044, "v_movrelsd_b32"), + (0x048, "v_movrelsd_2_b32"), + (0x050, "v_cvt_f16_u16"), + (0x051, "v_cvt_f16_i16"), + (0x052, "v_cvt_u16_f16"), + (0x053, "v_cvt_i16_f16"), + (0x054, "v_rcp_f16"), + (0x055, "v_sqrt_f16"), + (0x056, "v_rsq_f16"), + (0x057, "v_log_f16"), + (0x058, "v_exp_f16"), + (0x059, "v_frexp_mant_f16"), + (0x05a, "v_frexp_exp_i16_f16"), + (0x05b, "v_floor_f16"), + (0x05c, "v_ceil_f16"), + (0x05d, "v_trunc_f16"), + (0x05e, "v_rndne_f16"), + (0x05f, "v_fract_f16"), + (0x060, "v_sin_f16"), + (0x061, "v_cos_f16"), + (0x062, "v_sat_pk_u8_i16"), + (0x063, "v_cvt_norm_i16_f16"), + (0x064, "v_cvt_norm_u16_f16"), + (0x065, "v_swap_b32"), + (0x068, "v_swaprel_b32"), +]; + +pub(super) const VOPC: &[(u16, &str)] = &[ + (0x000, "v_cmp_f_f32"), + (0x001, "v_cmp_lt_f32"), + (0x002, "v_cmp_eq_f32"), + (0x003, "v_cmp_le_f32"), + (0x004, "v_cmp_gt_f32"), + (0x005, "v_cmp_lg_f32"), + (0x006, "v_cmp_ge_f32"), + (0x007, "v_cmp_o_f32"), + (0x008, "v_cmp_u_f32"), + (0x009, "v_cmp_nge_f32"), + (0x00a, "v_cmp_nlg_f32"), + (0x00b, "v_cmp_ngt_f32"), + (0x00c, "v_cmp_nle_f32"), + (0x00d, "v_cmp_neq_f32"), + (0x00e, "v_cmp_nlt_f32"), + (0x00f, "v_cmp_tru_f32"), + (0x010, "v_cmpx_f_f32"), + (0x011, "v_cmpx_lt_f32"), + (0x012, "v_cmpx_eq_f32"), + (0x013, "v_cmpx_le_f32"), + (0x014, "v_cmpx_gt_f32"), + (0x015, "v_cmpx_lg_f32"), + (0x016, "v_cmpx_ge_f32"), + (0x017, "v_cmpx_o_f32"), + (0x018, "v_cmpx_u_f32"), + (0x019, "v_cmpx_nge_f32"), + (0x01a, "v_cmpx_nlg_f32"), + (0x01b, "v_cmpx_ngt_f32"), + (0x01c, "v_cmpx_nle_f32"), + (0x01d, "v_cmpx_neq_f32"), + (0x01e, "v_cmpx_nlt_f32"), + (0x01f, "v_cmpx_tru_f32"), + (0x020, "v_cmp_f_f64"), + (0x021, "v_cmp_lt_f64"), + (0x022, "v_cmp_eq_f64"), + (0x023, "v_cmp_le_f64"), + (0x024, "v_cmp_gt_f64"), + (0x025, "v_cmp_lg_f64"), + (0x026, "v_cmp_ge_f64"), + (0x027, "v_cmp_o_f64"), + (0x028, "v_cmp_u_f64"), + (0x029, "v_cmp_nge_f64"), + (0x02a, "v_cmp_nlg_f64"), + (0x02b, "v_cmp_ngt_f64"), + (0x02c, "v_cmp_nle_f64"), + (0x02d, "v_cmp_neq_f64"), + (0x02e, "v_cmp_nlt_f64"), + (0x02f, "v_cmp_tru_f64"), + (0x030, "v_cmpx_f_f64"), + (0x031, "v_cmpx_lt_f64"), + (0x032, "v_cmpx_eq_f64"), + (0x033, "v_cmpx_le_f64"), + (0x034, "v_cmpx_gt_f64"), + (0x035, "v_cmpx_lg_f64"), + (0x036, "v_cmpx_ge_f64"), + (0x037, "v_cmpx_o_f64"), + (0x038, "v_cmpx_u_f64"), + (0x039, "v_cmpx_nge_f64"), + (0x03a, "v_cmpx_nlg_f64"), + (0x03b, "v_cmpx_ngt_f64"), + (0x03c, "v_cmpx_nle_f64"), + (0x03d, "v_cmpx_neq_f64"), + (0x03e, "v_cmpx_nlt_f64"), + (0x03f, "v_cmpx_tru_f64"), + (0x080, "v_cmp_f_i32"), + (0x081, "v_cmp_lt_i32"), + (0x082, "v_cmp_eq_i32"), + (0x083, "v_cmp_le_i32"), + (0x084, "v_cmp_gt_i32"), + (0x085, "v_cmp_ne_i32"), + (0x086, "v_cmp_ge_i32"), + (0x087, "v_cmp_t_i32"), + (0x088, "v_cmp_class_f32"), + (0x089, "v_cmp_lt_i16"), + (0x08a, "v_cmp_eq_i16"), + (0x08b, "v_cmp_le_i16"), + (0x08c, "v_cmp_gt_i16"), + (0x08d, "v_cmp_ne_i16"), + (0x08e, "v_cmp_ge_i16"), + (0x08f, "v_cmp_class_f16"), + (0x090, "v_cmpx_f_i32"), + (0x091, "v_cmpx_lt_i32"), + (0x092, "v_cmpx_eq_i32"), + (0x093, "v_cmpx_le_i32"), + (0x094, "v_cmpx_gt_i32"), + (0x095, "v_cmpx_ne_i32"), + (0x096, "v_cmpx_ge_i32"), + (0x097, "v_cmpx_t_i32"), + (0x098, "v_cmpx_class_f32"), + (0x099, "v_cmpx_lt_i16"), + (0x09a, "v_cmpx_eq_i16"), + (0x09b, "v_cmpx_le_i16"), + (0x09c, "v_cmpx_gt_i16"), + (0x09d, "v_cmpx_ne_i16"), + (0x09e, "v_cmpx_ge_i16"), + (0x09f, "v_cmpx_class_f16"), + (0x0a0, "v_cmp_f_i64"), + (0x0a1, "v_cmp_lt_i64"), + (0x0a2, "v_cmp_eq_i64"), + (0x0a3, "v_cmp_le_i64"), + (0x0a4, "v_cmp_gt_i64"), + (0x0a5, "v_cmp_ne_i64"), + (0x0a6, "v_cmp_ge_i64"), + (0x0a7, "v_cmp_t_i64"), + (0x0a8, "v_cmp_class_f64"), + (0x0a9, "v_cmp_lt_u16"), + (0x0aa, "v_cmp_eq_u16"), + (0x0ab, "v_cmp_le_u16"), + (0x0ac, "v_cmp_gt_u16"), + (0x0ad, "v_cmp_ne_u16"), + (0x0ae, "v_cmp_ge_u16"), + (0x0b0, "v_cmpx_f_i64"), + (0x0b1, "v_cmpx_lt_i64"), + (0x0b2, "v_cmpx_eq_i64"), + (0x0b3, "v_cmpx_le_i64"), + (0x0b4, "v_cmpx_gt_i64"), + (0x0b5, "v_cmpx_ne_i64"), + (0x0b6, "v_cmpx_ge_i64"), + (0x0b7, "v_cmpx_t_i64"), + (0x0b8, "v_cmpx_class_f64"), + (0x0b9, "v_cmpx_lt_u16"), + (0x0ba, "v_cmpx_eq_u16"), + (0x0bb, "v_cmpx_le_u16"), + (0x0bc, "v_cmpx_gt_u16"), + (0x0bd, "v_cmpx_ne_u16"), + (0x0be, "v_cmpx_ge_u16"), + (0x0c0, "v_cmp_f_u32"), + (0x0c1, "v_cmp_lt_u32"), + (0x0c2, "v_cmp_eq_u32"), + (0x0c3, "v_cmp_le_u32"), + (0x0c4, "v_cmp_gt_u32"), + (0x0c5, "v_cmp_ne_u32"), + (0x0c6, "v_cmp_ge_u32"), + (0x0c7, "v_cmp_t_u32"), + (0x0c8, "v_cmp_f_f16"), + (0x0c9, "v_cmp_lt_f16"), + (0x0ca, "v_cmp_eq_f16"), + (0x0cb, "v_cmp_le_f16"), + (0x0cc, "v_cmp_gt_f16"), + (0x0cd, "v_cmp_lg_f16"), + (0x0ce, "v_cmp_ge_f16"), + (0x0cf, "v_cmp_o_f16"), + (0x0d0, "v_cmpx_f_u32"), + (0x0d1, "v_cmpx_lt_u32"), + (0x0d2, "v_cmpx_eq_u32"), + (0x0d3, "v_cmpx_le_u32"), + (0x0d4, "v_cmpx_gt_u32"), + (0x0d5, "v_cmpx_ne_u32"), + (0x0d6, "v_cmpx_ge_u32"), + (0x0d7, "v_cmpx_t_u32"), + (0x0d8, "v_cmpx_f_f16"), + (0x0d9, "v_cmpx_lt_f16"), + (0x0da, "v_cmpx_eq_f16"), + (0x0db, "v_cmpx_le_f16"), + (0x0dc, "v_cmpx_gt_f16"), + (0x0dd, "v_cmpx_lg_f16"), + (0x0de, "v_cmpx_ge_f16"), + (0x0df, "v_cmpx_o_f16"), + (0x0e0, "v_cmp_f_u64"), + (0x0e1, "v_cmp_lt_u64"), + (0x0e2, "v_cmp_eq_u64"), + (0x0e3, "v_cmp_le_u64"), + (0x0e4, "v_cmp_gt_u64"), + (0x0e5, "v_cmp_ne_u64"), + (0x0e6, "v_cmp_ge_u64"), + (0x0e7, "v_cmp_t_u64"), + (0x0e8, "v_cmp_u_f16"), + (0x0e9, "v_cmp_nge_f16"), + (0x0ea, "v_cmp_nlg_f16"), + (0x0eb, "v_cmp_ngt_f16"), + (0x0ec, "v_cmp_nle_f16"), + (0x0ed, "v_cmp_neq_f16"), + (0x0ee, "v_cmp_nlt_f16"), + (0x0ef, "v_cmp_tru_f16"), + (0x0f0, "v_cmpx_f_u64"), + (0x0f1, "v_cmpx_lt_u64"), + (0x0f2, "v_cmpx_eq_u64"), + (0x0f3, "v_cmpx_le_u64"), + (0x0f4, "v_cmpx_gt_u64"), + (0x0f5, "v_cmpx_ne_u64"), + (0x0f6, "v_cmpx_ge_u64"), + (0x0f7, "v_cmpx_t_u64"), + (0x0f8, "v_cmpx_u_f16"), + (0x0f9, "v_cmpx_nge_f16"), + (0x0fa, "v_cmpx_nlg_f16"), + (0x0fb, "v_cmpx_ngt_f16"), + (0x0fc, "v_cmpx_nle_f16"), + (0x0fd, "v_cmpx_neq_f16"), + (0x0fe, "v_cmpx_nlt_f16"), + (0x0ff, "v_cmpx_tru_f16"), +]; + +pub(super) const VOP3: &[(u16, &str)] = &[ + (0x140, "v_mad_legacy_f32"), + (0x141, "v_mad_f32"), + (0x142, "v_mad_i32_i24"), + (0x143, "v_mad_u32_u24"), + (0x144, "v_cubeid_f32"), + (0x145, "v_cubesc_f32"), + (0x146, "v_cubetc_f32"), + (0x147, "v_cubema_f32"), + (0x148, "v_bfe_u32"), + (0x149, "v_bfe_i32"), + (0x14a, "v_bfi_b32"), + (0x14b, "v_fma_f32"), + (0x14c, "v_fma_f64"), + (0x14d, "v_lerp_u8"), + (0x14e, "v_alignbit_b32"), + (0x14f, "v_alignbyte_b32"), + (0x150, "v_mullit_f32"), + (0x151, "v_min3_f32"), + (0x152, "v_min3_i32"), + (0x153, "v_min3_u32"), + (0x154, "v_max3_f32"), + (0x155, "v_max3_i32"), + (0x156, "v_max3_u32"), + (0x157, "v_med3_f32"), + (0x158, "v_med3_i32"), + (0x159, "v_med3_u32"), + (0x15a, "v_sad_u8"), + (0x15b, "v_sad_hi_u8"), + (0x15c, "v_sad_u16"), + (0x15d, "v_sad_u32"), + (0x15e, "v_cvt_pk_u8_f32"), + (0x15f, "v_div_fixup_f32"), + (0x160, "v_div_fixup_f64"), + (0x164, "v_add_f64"), + (0x165, "v_mul_f64"), + (0x166, "v_min_f64"), + (0x167, "v_max_f64"), + (0x168, "v_ldexp_f64"), + (0x169, "v_mul_lo_u32"), + (0x16a, "v_mul_hi_u32"), + (0x16b, "v_mul_lo_i32"), + (0x16c, "v_mul_hi_i32"), + (0x16d, "v_div_scale_f32"), + (0x16e, "v_div_scale_f64"), + (0x16f, "v_div_fmas_f32"), + (0x170, "v_div_fmas_f64"), + (0x171, "v_msad_u8"), + (0x172, "v_qsad_pk_u16_u8"), + (0x173, "v_mqsad_pk_u16_u8"), + (0x174, "v_trig_preop_f64"), + (0x175, "v_mqsad_u32_u8"), + (0x176, "v_mad_u64_u32"), + (0x177, "v_mad_i64_i32"), + (0x178, "v_xor3_b32"), + (0x2ff, "v_lshlrev_b64"), + (0x300, "v_lshrrev_b64"), + (0x301, "v_ashrrev_i64"), + (0x303, "v_add_nc_u16"), + (0x304, "v_sub_nc_u16"), + (0x305, "v_mul_lo_u16"), + (0x307, "v_lshrrev_b16"), + (0x308, "v_ashrrev_i16"), + (0x309, "v_max_u16"), + (0x30a, "v_max_i16"), + (0x30b, "v_min_u16"), + (0x30c, "v_min_i16"), + (0x30d, "v_add_nc_i16"), + (0x30e, "v_sub_nc_i16"), + (0x30f, "v_add_co_u32"), + (0x310, "v_sub_co_u32"), + (0x311, "v_pack_b32_f16"), + (0x312, "v_cvt_pknorm_i16_f16"), + (0x313, "v_cvt_pknorm_u16_f16"), + (0x314, "v_lshlrev_b16"), + (0x319, "v_subrev_co_u32"), + (0x340, "v_mad_u16"), + (0x342, "v_interp_p1ll_f16"), + (0x343, "v_interp_p1lv_f16"), + (0x344, "v_perm_b32"), + (0x345, "v_xad_u32"), + (0x346, "v_lshl_add_u32"), + (0x347, "v_add_lshl_u32"), + (0x34b, "v_fma_f16"), + (0x351, "v_min3_f16"), + (0x352, "v_min3_i16"), + (0x353, "v_min3_u16"), + (0x354, "v_max3_f16"), + (0x355, "v_max3_i16"), + (0x356, "v_max3_u16"), + (0x357, "v_med3_f16"), + (0x358, "v_med3_i16"), + (0x359, "v_med3_u16"), + (0x35a, "v_interp_p2_f16"), + (0x35e, "v_mad_i16"), + (0x35f, "v_div_fixup_f16"), + (0x360, "v_readlane_b32"), + (0x361, "v_writelane_b32"), + (0x362, "v_ldexp_f32"), + (0x363, "v_bfm_b32"), + (0x364, "v_bcnt_u32_b32"), + (0x365, "v_mbcnt_lo_u32_b32"), + (0x366, "v_mbcnt_hi_u32_b32"), + (0x368, "v_cvt_pknorm_i16_f32"), + (0x369, "v_cvt_pknorm_u16_f32"), + (0x36a, "v_cvt_pk_u16_u32"), + (0x36b, "v_cvt_pk_i16_i32"), + (0x36d, "v_add3_u32"), + (0x36f, "v_lshl_or_b32"), + (0x371, "v_and_or_b32"), + (0x372, "v_or3_b32"), + (0x373, "v_mad_u32_u16"), + (0x375, "v_mad_i32_i16"), + (0x376, "v_sub_nc_i32"), + (0x377, "v_permlane16_b32"), + (0x378, "v_permlanex16_b32"), + (0x37f, "v_add_nc_i32"), +]; + +pub(super) const VOP3P: &[(u16, &str)] = &[ + (0x000, "v_pk_mad_i16"), + (0x001, "v_pk_mul_lo_u16"), + (0x002, "v_pk_add_i16"), + (0x003, "v_pk_sub_i16"), + (0x004, "v_pk_lshlrev_b16"), + (0x005, "v_pk_lshrrev_b16"), + (0x006, "v_pk_ashrrev_i16"), + (0x007, "v_pk_max_i16"), + (0x008, "v_pk_min_i16"), + (0x009, "v_pk_mad_u16"), + (0x00a, "v_pk_add_u16"), + (0x00b, "v_pk_sub_u16"), + (0x00c, "v_pk_max_u16"), + (0x00d, "v_pk_min_u16"), + (0x00e, "v_pk_fma_f16"), + (0x00f, "v_pk_add_f16"), + (0x010, "v_pk_mul_f16"), + (0x011, "v_pk_min_f16"), + (0x012, "v_pk_max_f16"), + (0x013, "v_dot2_f32_f16"), + (0x014, "v_dot2_i32_i16"), + (0x015, "v_dot2_u32_u16"), + (0x016, "v_dot4_i32_i8"), + (0x017, "v_dot4_u32_u8"), + (0x019, "v_dot8_u32_u4"), + (0x020, "v_fma_mix_f32"), + (0x021, "v_fma_mixlo_f16"), + (0x022, "v_fma_mixhi_f16"), +]; + +pub(super) const VINTRP: &[(u16, &str)] = &[ + (0x000, "v_interp_p1_f32"), + (0x001, "v_interp_p2_f32"), + (0x002, "v_interp_mov_f32"), +]; + +pub(super) const DS: &[(u16, &str)] = &[ + (0x000, "ds_add_u32"), + (0x001, "ds_sub_u32"), + (0x002, "ds_rsub_u32"), + (0x003, "ds_inc_u32"), + (0x004, "ds_dec_u32"), + (0x005, "ds_min_i32"), + (0x006, "ds_max_i32"), + (0x007, "ds_min_u32"), + (0x008, "ds_max_u32"), + (0x009, "ds_and_b32"), + (0x00a, "ds_or_b32"), + (0x00b, "ds_xor_b32"), + (0x00c, "ds_mskor_b32"), + (0x00d, "ds_write_b32"), + (0x00e, "ds_write2_b32"), + (0x00f, "ds_write2st64_b32"), + (0x010, "ds_cmpst_b32"), + (0x011, "ds_cmpst_f32"), + (0x012, "ds_min_f32"), + (0x013, "ds_max_f32"), + (0x014, "ds_nop"), + (0x015, "ds_add_f32"), + (0x018, "ds_gws_sema_release_all"), + (0x019, "ds_gws_init"), + (0x01a, "ds_gws_sema_v"), + (0x01b, "ds_gws_sema_br"), + (0x01c, "ds_gws_sema_p"), + (0x01d, "ds_gws_barrier"), + (0x01e, "ds_write_b8"), + (0x01f, "ds_write_b16"), + (0x020, "ds_add_rtn_u32"), + (0x021, "ds_sub_rtn_u32"), + (0x022, "ds_rsub_rtn_u32"), + (0x023, "ds_inc_rtn_u32"), + (0x024, "ds_dec_rtn_u32"), + (0x025, "ds_min_rtn_i32"), + (0x026, "ds_max_rtn_i32"), + (0x027, "ds_min_rtn_u32"), + (0x028, "ds_max_rtn_u32"), + (0x029, "ds_and_rtn_b32"), + (0x02a, "ds_or_rtn_b32"), + (0x02b, "ds_xor_rtn_b32"), + (0x02c, "ds_mskor_rtn_b32"), + (0x02d, "ds_wrxchg_rtn_b32"), + (0x02e, "ds_wrxchg2_rtn_b32"), + (0x02f, "ds_wrxchg2st64_rtn_b32"), + (0x030, "ds_cmpst_rtn_b32"), + (0x031, "ds_cmpst_rtn_f32"), + (0x032, "ds_min_rtn_f32"), + (0x033, "ds_max_rtn_f32"), + (0x034, "ds_wrap_rtn_b32"), + (0x035, "ds_swizzle_b32"), + (0x036, "ds_read_b32"), + (0x037, "ds_read2_b32"), + (0x038, "ds_read2st64_b32"), + (0x039, "ds_read_i8"), + (0x03a, "ds_read_u8"), + (0x03b, "ds_read_i16"), + (0x03c, "ds_read_u16"), + (0x03d, "ds_consume"), + (0x03e, "ds_append"), + (0x03f, "ds_ordered_count"), + (0x040, "ds_add_u64"), + (0x041, "ds_sub_u64"), + (0x042, "ds_rsub_u64"), + (0x043, "ds_inc_u64"), + (0x044, "ds_dec_u64"), + (0x045, "ds_min_i64"), + (0x046, "ds_max_i64"), + (0x047, "ds_min_u64"), + (0x048, "ds_max_u64"), + (0x049, "ds_and_b64"), + (0x04a, "ds_or_b64"), + (0x04b, "ds_xor_b64"), + (0x04c, "ds_mskor_b64"), + (0x04d, "ds_write_b64"), + (0x04e, "ds_write2_b64"), + (0x04f, "ds_write2st64_b64"), + (0x050, "ds_cmpst_b64"), + (0x051, "ds_cmpst_f64"), + (0x052, "ds_min_f64"), + (0x053, "ds_max_f64"), + (0x055, "ds_add_rtn_f32"), + (0x060, "ds_add_rtn_u64"), + (0x061, "ds_sub_rtn_u64"), + (0x062, "ds_rsub_rtn_u64"), + (0x063, "ds_inc_rtn_u64"), + (0x064, "ds_dec_rtn_u64"), + (0x065, "ds_min_rtn_i64"), + (0x066, "ds_max_rtn_i64"), + (0x067, "ds_min_rtn_u64"), + (0x068, "ds_max_rtn_u64"), + (0x069, "ds_and_rtn_b64"), + (0x06a, "ds_or_rtn_b64"), + (0x06b, "ds_xor_rtn_b64"), + (0x06c, "ds_mskor_rtn_b64"), + (0x06d, "ds_wrxchg_rtn_b64"), + (0x06e, "ds_wrxchg2_rtn_b64"), + (0x06f, "ds_wrxchg2st64_rtn_b64"), + (0x070, "ds_cmpst_rtn_b64"), + (0x071, "ds_cmpst_rtn_f64"), + (0x072, "ds_min_rtn_f64"), + (0x073, "ds_max_rtn_f64"), + (0x076, "ds_read_b64"), + (0x077, "ds_read2_b64"), + (0x078, "ds_read2st64_b64"), + (0x07e, "ds_condxchg32_rtn_b64"), + (0x080, "ds_add_src2_u32"), + (0x081, "ds_sub_src2_u32"), + (0x082, "ds_rsub_src2_u32"), + (0x083, "ds_inc_src2_u32"), + (0x084, "ds_dec_src2_u32"), + (0x085, "ds_min_src2_i32"), + (0x086, "ds_max_src2_i32"), + (0x087, "ds_min_src2_u32"), + (0x088, "ds_max_src2_u32"), + (0x089, "ds_and_src2_b32"), + (0x08a, "ds_or_src2_b32"), + (0x08b, "ds_xor_src2_b32"), + (0x08d, "ds_write_src2_b32"), + (0x092, "ds_min_src2_f32"), + (0x093, "ds_max_src2_f32"), + (0x095, "ds_add_src2_f32"), + (0x0a0, "ds_write_b8_d16_hi"), + (0x0a1, "ds_write_b16_d16_hi"), + (0x0a2, "ds_read_u8_d16"), + (0x0a3, "ds_read_u8_d16_hi"), + (0x0a4, "ds_read_i8_d16"), + (0x0a5, "ds_read_i8_d16_hi"), + (0x0a6, "ds_read_u16_d16"), + (0x0a7, "ds_read_u16_d16_hi"), + (0x0b0, "ds_write_addtid_b32"), + (0x0b1, "ds_read_addtid_b32"), + (0x0b2, "ds_permute_b32"), + (0x0b3, "ds_bpermute_b32"), + (0x0c0, "ds_add_src2_u64"), + (0x0c1, "ds_sub_src2_u64"), + (0x0c2, "ds_rsub_src2_u64"), + (0x0c3, "ds_inc_src2_u64"), + (0x0c4, "ds_dec_src2_u64"), + (0x0c5, "ds_min_src2_i64"), + (0x0c6, "ds_max_src2_i64"), + (0x0c7, "ds_min_src2_u64"), + (0x0c8, "ds_max_src2_u64"), + (0x0c9, "ds_and_src2_b64"), + (0x0ca, "ds_or_src2_b64"), + (0x0cb, "ds_xor_src2_b64"), + (0x0cd, "ds_write_src2_b64"), + (0x0d2, "ds_min_src2_f64"), + (0x0d3, "ds_max_src2_f64"), + (0x0de, "ds_write_b96"), + (0x0df, "ds_write_b128"), + (0x0fe, "ds_read_b96"), + (0x0ff, "ds_read_b128"), +]; + +pub(super) const MUBUF: &[(u16, &str)] = &[ + (0x000, "buffer_load_format_x"), + (0x001, "buffer_load_format_xy"), + (0x002, "buffer_load_format_xyz"), + (0x003, "buffer_load_format_xyzw"), + (0x004, "buffer_store_format_x"), + (0x005, "buffer_store_format_xy"), + (0x006, "buffer_store_format_xyz"), + (0x007, "buffer_store_format_xyzw"), + (0x008, "buffer_load_ubyte"), + (0x009, "buffer_load_sbyte"), + (0x00a, "buffer_load_ushort"), + (0x00b, "buffer_load_sshort"), + (0x00c, "buffer_load_dword"), + (0x00d, "buffer_load_dwordx2"), + (0x00e, "buffer_load_dwordx4"), + (0x00f, "buffer_load_dwordx3"), + (0x018, "buffer_store_byte"), + (0x019, "buffer_store_byte_d16_hi"), + (0x01a, "buffer_store_short"), + (0x01b, "buffer_store_short_d16_hi"), + (0x01c, "buffer_store_dword"), + (0x01d, "buffer_store_dwordx2"), + (0x01e, "buffer_store_dwordx4"), + (0x01f, "buffer_store_dwordx3"), + (0x020, "buffer_load_ubyte_d16"), + (0x021, "buffer_load_ubyte_d16_hi"), + (0x022, "buffer_load_sbyte_d16"), + (0x023, "buffer_load_sbyte_d16_hi"), + (0x024, "buffer_load_short_d16"), + (0x025, "buffer_load_short_d16_hi"), + (0x026, "buffer_load_format_d16_hi_x"), + (0x027, "buffer_store_format_d16_hi_x"), + (0x030, "buffer_atomic_swap"), + (0x031, "buffer_atomic_cmpswap"), + (0x032, "buffer_atomic_add"), + (0x033, "buffer_atomic_sub"), + (0x034, "buffer_atomic_csub"), + (0x035, "buffer_atomic_smin"), + (0x036, "buffer_atomic_umin"), + (0x037, "buffer_atomic_smax"), + (0x038, "buffer_atomic_umax"), + (0x039, "buffer_atomic_and"), + (0x03a, "buffer_atomic_or"), + (0x03b, "buffer_atomic_xor"), + (0x03c, "buffer_atomic_inc"), + (0x03d, "buffer_atomic_dec"), + (0x03e, "buffer_atomic_fcmpswap"), + (0x03f, "buffer_atomic_fmin"), + (0x040, "buffer_atomic_fmax"), + (0x050, "buffer_atomic_swap_x2"), + (0x051, "buffer_atomic_cmpswap_x2"), + (0x052, "buffer_atomic_add_x2"), + (0x053, "buffer_atomic_sub_x2"), + (0x055, "buffer_atomic_smin_x2"), + (0x056, "buffer_atomic_umin_x2"), + (0x057, "buffer_atomic_smax_x2"), + (0x058, "buffer_atomic_umax_x2"), + (0x059, "buffer_atomic_and_x2"), + (0x05a, "buffer_atomic_or_x2"), + (0x05b, "buffer_atomic_xor_x2"), + (0x05c, "buffer_atomic_inc_x2"), + (0x05d, "buffer_atomic_dec_x2"), + (0x05e, "buffer_atomic_fcmpswap_x2"), + (0x05f, "buffer_atomic_fmin_x2"), + (0x060, "buffer_atomic_fmax_x2"), + (0x071, "buffer_gl0_inv"), + (0x072, "buffer_gl1_inv"), + (0x080, "buffer_load_format_d16_x"), + (0x081, "buffer_load_format_d16_xy"), + (0x082, "buffer_load_format_d16_xyz"), + (0x083, "buffer_load_format_d16_xyzw"), + (0x084, "buffer_store_format_d16_x"), + (0x085, "buffer_store_format_d16_xy"), + (0x086, "buffer_store_format_d16_xyz"), + (0x087, "buffer_store_format_d16_xyzw"), +]; + +pub(super) const MTBUF: &[(u16, &str)] = &[ + (0x000, "tbuffer_load_format_x"), + (0x001, "tbuffer_load_format_xy"), + (0x002, "tbuffer_load_format_xyz"), + (0x003, "tbuffer_load_format_xyzw"), + (0x004, "tbuffer_store_format_x"), + (0x005, "tbuffer_store_format_xy"), + (0x006, "tbuffer_store_format_xyz"), + (0x007, "tbuffer_store_format_xyzw"), + (0x008, "tbuffer_load_format_d16_x"), + (0x009, "tbuffer_load_format_d16_xy"), + (0x00a, "tbuffer_load_format_d16_xyz"), + (0x00b, "tbuffer_load_format_d16_xyzw"), + (0x00c, "tbuffer_store_format_d16_x"), + (0x00d, "tbuffer_store_format_d16_xy"), + (0x00e, "tbuffer_store_format_d16_xyz"), + (0x00f, "tbuffer_store_format_d16_xyzw"), +]; + +pub(super) const MIMG: &[(u16, &str)] = &[ + (0x000, "image_load"), + (0x001, "image_load_mip"), + (0x002, "image_load_pck"), + (0x003, "image_load_pck_sgn"), + (0x004, "image_load_mip_pck"), + (0x005, "image_load_mip_pck_sgn"), + (0x008, "image_store"), + (0x009, "image_store_mip"), + (0x00a, "image_store_pck"), + (0x00b, "image_store_mip_pck"), + (0x00e, "image_get_resinfo"), + (0x00f, "image_atomic_swap"), + (0x010, "image_atomic_cmpswap"), + (0x011, "image_atomic_add"), + (0x012, "image_atomic_sub"), + (0x014, "image_atomic_smin"), + (0x015, "image_atomic_umin"), + (0x016, "image_atomic_smax"), + (0x017, "image_atomic_umax"), + (0x018, "image_atomic_and"), + (0x019, "image_atomic_or"), + (0x01a, "image_atomic_xor"), + (0x01b, "image_atomic_inc"), + (0x01c, "image_atomic_dec"), + (0x01d, "image_atomic_fcmpswap"), + (0x01e, "image_atomic_fmin"), + (0x01f, "image_atomic_fmax"), + (0x020, "image_sample"), + (0x021, "image_sample_cl"), + (0x022, "image_sample_d"), + (0x023, "image_sample_d_cl"), + (0x024, "image_sample_l"), + (0x025, "image_sample_b"), + (0x026, "image_sample_b_cl"), + (0x027, "image_sample_lz"), + (0x028, "image_sample_c"), + (0x029, "image_sample_c_cl"), + (0x02a, "image_sample_c_d"), + (0x02b, "image_sample_c_d_cl"), + (0x02c, "image_sample_c_l"), + (0x02d, "image_sample_c_b"), + (0x02e, "image_sample_c_b_cl"), + (0x02f, "image_sample_c_lz"), + (0x030, "image_sample_o"), + (0x031, "image_sample_cl_o"), + (0x032, "image_sample_d_o"), + (0x033, "image_sample_d_cl_o"), + (0x034, "image_sample_l_o"), + (0x035, "image_sample_b_o"), + (0x036, "image_sample_b_cl_o"), + (0x037, "image_sample_lz_o"), + (0x038, "image_sample_c_o"), + (0x039, "image_sample_c_cl_o"), + (0x03a, "image_sample_c_d_o"), + (0x03b, "image_sample_c_d_cl_o"), + (0x03c, "image_sample_c_l_o"), + (0x03d, "image_sample_c_b_o"), + (0x03e, "image_sample_c_b_cl_o"), + (0x03f, "image_sample_c_lz_o"), + (0x040, "image_gather4"), + (0x041, "image_gather4_cl"), + (0x044, "image_gather4_l"), + (0x045, "image_gather4_b"), + (0x046, "image_gather4_b_cl"), + (0x047, "image_gather4_lz"), + (0x048, "image_gather4_c"), + (0x049, "image_gather4_c_cl"), + (0x04c, "image_gather4_c_l"), + (0x04d, "image_gather4_c_b"), + (0x04e, "image_gather4_c_b_cl"), + (0x04f, "image_gather4_c_lz"), + (0x050, "image_gather4_o"), + (0x051, "image_gather4_cl_o"), + (0x054, "image_gather4_l_o"), + (0x055, "image_gather4_b_o"), + (0x056, "image_gather4_b_cl_o"), + (0x057, "image_gather4_lz_o"), + (0x058, "image_gather4_c_o"), + (0x059, "image_gather4_c_cl_o"), + (0x05c, "image_gather4_c_l_o"), + (0x05d, "image_gather4_c_b_o"), + (0x05e, "image_gather4_c_b_cl_o"), + (0x05f, "image_gather4_c_lz_o"), + (0x060, "image_get_lod"), + (0x068, "image_sample_cd"), + (0x069, "image_sample_cd_cl"), + (0x06a, "image_sample_c_cd"), + (0x06b, "image_sample_c_cd_cl"), + (0x06c, "image_sample_cd_o"), + (0x06d, "image_sample_cd_cl_o"), + (0x06e, "image_sample_c_cd_o"), + (0x06f, "image_sample_c_cd_cl_o"), + (0x080, "image_msaa_load"), + (0x0a2, "image_sample_d_g16"), + (0x0a3, "image_sample_d_cl_g16"), + (0x0aa, "image_sample_c_d_g16"), + (0x0ab, "image_sample_c_d_cl_g16"), + (0x0b2, "image_sample_d_o_g16"), + (0x0b3, "image_sample_d_cl_o_g16"), + (0x0ba, "image_sample_c_d_o_g16"), + (0x0bb, "image_sample_c_d_cl_o_g16"), + (0x0e6, "image_bvh_intersect_ray"), + (0x0e7, "image_bvh64_intersect_ray"), +]; + +pub(super) const FLAT: &[(u16, &str)] = &[ + (0x008, "flat_load_ubyte"), + (0x009, "flat_load_sbyte"), + (0x00a, "flat_load_ushort"), + (0x00b, "flat_load_sshort"), + (0x00c, "flat_load_dword"), + (0x00d, "flat_load_dwordx2"), + (0x00e, "flat_load_dwordx4"), + (0x00f, "flat_load_dwordx3"), + (0x018, "flat_store_byte"), + (0x019, "flat_store_byte_d16_hi"), + (0x01a, "flat_store_short"), + (0x01b, "flat_store_short_d16_hi"), + (0x01c, "flat_store_dword"), + (0x01d, "flat_store_dwordx2"), + (0x01e, "flat_store_dwordx4"), + (0x01f, "flat_store_dwordx3"), + (0x020, "flat_load_ubyte_d16"), + (0x021, "flat_load_ubyte_d16_hi"), + (0x022, "flat_load_sbyte_d16"), + (0x023, "flat_load_sbyte_d16_hi"), + (0x024, "flat_load_short_d16"), + (0x025, "flat_load_short_d16_hi"), + (0x030, "flat_atomic_swap"), + (0x031, "flat_atomic_cmpswap"), + (0x032, "flat_atomic_add"), + (0x033, "flat_atomic_sub"), + (0x035, "flat_atomic_smin"), + (0x036, "flat_atomic_umin"), + (0x037, "flat_atomic_smax"), + (0x038, "flat_atomic_umax"), + (0x039, "flat_atomic_and"), + (0x03a, "flat_atomic_or"), + (0x03b, "flat_atomic_xor"), + (0x03c, "flat_atomic_inc"), + (0x03d, "flat_atomic_dec"), + (0x03e, "flat_atomic_fcmpswap"), + (0x03f, "flat_atomic_fmin"), + (0x040, "flat_atomic_fmax"), + (0x050, "flat_atomic_swap_x2"), + (0x051, "flat_atomic_cmpswap_x2"), + (0x052, "flat_atomic_add_x2"), + (0x053, "flat_atomic_sub_x2"), + (0x055, "flat_atomic_smin_x2"), + (0x056, "flat_atomic_umin_x2"), + (0x057, "flat_atomic_smax_x2"), + (0x058, "flat_atomic_umax_x2"), + (0x059, "flat_atomic_and_x2"), + (0x05a, "flat_atomic_or_x2"), + (0x05b, "flat_atomic_xor_x2"), + (0x05c, "flat_atomic_inc_x2"), + (0x05d, "flat_atomic_dec_x2"), + (0x05e, "flat_atomic_fcmpswap_x2"), + (0x05f, "flat_atomic_fmin_x2"), + (0x060, "flat_atomic_fmax_x2"), +]; + +pub(super) const GLOBAL: &[(u16, &str)] = &[ + (0x008, "global_load_ubyte"), + (0x009, "global_load_sbyte"), + (0x00a, "global_load_ushort"), + (0x00b, "global_load_sshort"), + (0x00c, "global_load_dword"), + (0x00d, "global_load_dwordx2"), + (0x00e, "global_load_dwordx4"), + (0x00f, "global_load_dwordx3"), + (0x016, "global_load_dword_addtid"), + (0x017, "global_store_dword_addtid"), + (0x018, "global_store_byte"), + (0x019, "global_store_byte_d16_hi"), + (0x01a, "global_store_short"), + (0x01b, "global_store_short_d16_hi"), + (0x01c, "global_store_dword"), + (0x01d, "global_store_dwordx2"), + (0x01e, "global_store_dwordx4"), + (0x01f, "global_store_dwordx3"), + (0x020, "global_load_ubyte_d16"), + (0x021, "global_load_ubyte_d16_hi"), + (0x022, "global_load_sbyte_d16"), + (0x023, "global_load_sbyte_d16_hi"), + (0x024, "global_load_short_d16"), + (0x025, "global_load_short_d16_hi"), + (0x030, "global_atomic_swap"), + (0x031, "global_atomic_cmpswap"), + (0x032, "global_atomic_add"), + (0x033, "global_atomic_sub"), + (0x034, "global_atomic_csub"), + (0x035, "global_atomic_smin"), + (0x036, "global_atomic_umin"), + (0x037, "global_atomic_smax"), + (0x038, "global_atomic_umax"), + (0x039, "global_atomic_and"), + (0x03a, "global_atomic_or"), + (0x03b, "global_atomic_xor"), + (0x03c, "global_atomic_inc"), + (0x03d, "global_atomic_dec"), + (0x03e, "global_atomic_fcmpswap"), + (0x03f, "global_atomic_fmin"), + (0x040, "global_atomic_fmax"), + (0x050, "global_atomic_swap_x2"), + (0x051, "global_atomic_cmpswap_x2"), + (0x052, "global_atomic_add_x2"), + (0x053, "global_atomic_sub_x2"), + (0x055, "global_atomic_smin_x2"), + (0x056, "global_atomic_umin_x2"), + (0x057, "global_atomic_smax_x2"), + (0x058, "global_atomic_umax_x2"), + (0x059, "global_atomic_and_x2"), + (0x05a, "global_atomic_or_x2"), + (0x05b, "global_atomic_xor_x2"), + (0x05c, "global_atomic_inc_x2"), + (0x05d, "global_atomic_dec_x2"), + (0x05e, "global_atomic_fcmpswap_x2"), + (0x05f, "global_atomic_fmin_x2"), + (0x060, "global_atomic_fmax_x2"), +]; + +pub(super) const SCRATCH: &[(u16, &str)] = &[ + (0x008, "scratch_load_ubyte"), + (0x009, "scratch_load_sbyte"), + (0x00a, "scratch_load_ushort"), + (0x00b, "scratch_load_sshort"), + (0x00c, "scratch_load_dword"), + (0x00d, "scratch_load_dwordx2"), + (0x00e, "scratch_load_dwordx4"), + (0x00f, "scratch_load_dwordx3"), + (0x018, "scratch_store_byte"), + (0x019, "scratch_store_byte_d16_hi"), + (0x01a, "scratch_store_short"), + (0x01b, "scratch_store_short_d16_hi"), + (0x01c, "scratch_store_dword"), + (0x01d, "scratch_store_dwordx2"), + (0x01e, "scratch_store_dwordx4"), + (0x01f, "scratch_store_dwordx3"), + (0x020, "scratch_load_ubyte_d16"), + (0x021, "scratch_load_ubyte_d16_hi"), + (0x022, "scratch_load_sbyte_d16"), + (0x023, "scratch_load_sbyte_d16_hi"), + (0x024, "scratch_load_short_d16"), + (0x025, "scratch_load_short_d16_hi"), +]; + +#[cfg(test)] +mod tests { + fn bytes(words: &[u32]) -> Vec<u8> { + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// `s_ttracedata_imm 0x1234` as LLVM's GFX10 disassembler tests have it + /// (`gfx10_sopp.txt`: `0x34,0x12,0xa8,0xbf`), SOPP opcode 0x28 as in + /// AMD's RDNA2 ISA. A thread-trace marker, which translation drops. + #[test] + fn s_ttracedata_imm_is_sopp_0x28() { + let code = bytes(&[0xBFA8_1234, 0xBF81_0000]); + let decoded = super::super::decode(&code).unwrap(); + assert_eq!(decoded[0].name(), Some("s_ttracedata_imm")); + assert!(crate::ir::build(&code, false, 1).is_ok()); + } +} diff --git a/crates/victory-shader/src/gfx10/sp3.rs b/crates/victory-shader/src/gfx10/sp3.rs new file mode 100644 index 000000000..0ca5ab414 --- /dev/null +++ b/crates/victory-shader/src/gfx10/sp3.rs @@ -0,0 +1,784 @@ +//! Instruction text in AMD's SP3 assembly syntax. + +use std::fmt::{self, Display, Write}; + +use super::fields::{Cache, Dpp, Fields, NULL, Operand, Valu}; +use super::{Encoding, Instruction}; + +impl Instruction { + /// The instruction in SP3 syntax, e.g. `v_add_f32 v1, 0.5, v8`. + /// Branch targets are written `label_<byte offset>`. + pub fn text(&self, wave64: bool) -> String { + let name = self.name().unwrap_or("?"); + let ops = operands(self, name, &self.fields(wave64)); + if ops.is_empty() { + name.to_owned() + } else { + format!("{name} {ops}") + } + } +} + +impl Display for Operand { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Operand::Scalar { code, dwords: 1 } => f.write_str(&scalar_name(code)), + Operand::Scalar { + code: 106, + dwords: 2, + } => f.write_str("vcc"), + Operand::Scalar { + code: 126, + dwords: 2, + } => f.write_str("exec"), + Operand::Scalar { code, dwords } if code < 106 => { + write!(f, "s[{code}:{}]", code + dwords - 1) + } + Operand::Scalar { code, dwords } if (108..124).contains(&code) => { + write!(f, "ttmp[{}:{}]", code - 108, code - 108 + dwords - 1) + } + Operand::Scalar { code, .. } => f.write_str(&scalar_name(code)), + Operand::Vector { reg, dwords: 1 } => write!(f, "v{reg}"), + Operand::Vector { reg, dwords } => { + write!(f, "v[{reg}:{}]", reg as u32 + dwords as u32 - 1) + } + Operand::Const(code) => f.write_str(&const_name(code)), + Operand::Literal(value) => write!(f, "lit(0x{value:08x})"), + Operand::Attr { index, chan, .. } => write!( + f, + "attr{index}.{}", + ['x', 'y', 'z', 'w'][usize::from(chan & 3)] + ), + } + } +} + +fn scalar_name(code: u8) -> String { + match code { + 0..=105 => format!("s{code}"), + 106 => "vcc_lo".into(), + 107 => "vcc_hi".into(), + 108..=123 => format!("ttmp{}", code - 108), + 124 => "m0".into(), + 125 => "null".into(), + 126 => "exec_lo".into(), + _ => "exec_hi".into(), + } +} + +fn const_name(code: u8) -> String { + match code { + 128..=192 => (i32::from(code) - 128).to_string(), + 193..=208 => (192 - i32::from(code)).to_string(), + 240 => "0.5".into(), + 241 => "-0.5".into(), + 242 => "1.0".into(), + 243 => "-1.0".into(), + 244 => "2.0".into(), + 245 => "-2.0".into(), + 246 => "4.0".into(), + 247 => "-4.0".into(), + 248 => "0.15915494".into(), + 235 => "src_shared_base".into(), + 236 => "src_shared_limit".into(), + 237 => "src_private_base".into(), + 238 => "src_private_limit".into(), + 239 => "src_pops_exiting_wave_id".into(), + 251 => "src_vccz".into(), + 252 => "src_execz".into(), + 253 => "src_scc".into(), + 254 => "src_lds_direct".into(), + _ => format!("<src {code}>"), + } +} + +fn join(ops: impl IntoIterator<Item = String>) -> String { + ops.into_iter().collect::<Vec<_>>().join(", ") +} + +fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String { + let mut out = String::new(); + match fields { + Fields::Sop { dst, src, imm } => { + let regs = join(dst.iter().chain(src).map(|o| o.to_string())); + out = match (name, imm) { + ("s_getreg_b32", Some(imm)) => format!("{regs}, {}", hwreg(*imm)), + ("s_setreg_b32" | "s_setreg_imm32_b32", Some(imm)) => { + format!("{}, {regs}", hwreg(*imm)) + } + ("s_call_b64", Some(imm)) => format!("{regs}, {}", label(inst, *imm)), + (_, Some(imm)) if regs.is_empty() => format!("0x{imm:04x}"), + (_, Some(imm)) => format!("{regs}, 0x{imm:04x}"), + (_, None) => regs, + }; + } + Fields::Sopp { imm } => { + out = match name { + "s_endpgm" + | "s_barrier" + | "s_code_end" + | "s_endpgm_saved" + | "s_endpgm_ordered_ps_done" + | "s_wakeup" + | "s_icache_inv" + | "s_ttracedata" => String::new(), + "s_branch" => label(inst, *imm), + n if n.starts_with("s_cbranch_") => label(inst, *imm), + "s_waitcnt" => waitcnt(*imm), + "s_sendmsg" | "s_sendmsghalt" => sendmsg(*imm), + _ => format!("0x{imm:04x}"), + }; + } + Fields::Smem { + data, + base, + offset, + soffset, + cache, + } => { + if let Some(data) = data { + let off = match (soffset, offset) { + (Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(), + (Operand::Scalar { code: NULL, .. }, _) => { + format!("0x{:06x}", offset & 0x1F_FFFF) + } + (_, 0) => soffset.to_string(), + _ => format!("{soffset} offset:0x{:06x}", offset & 0x1F_FFFF), + }; + out = format!("{data}, {base}, {off}"); + } + flags(&mut out, cache, false); + } + Fields::Valu(v) => out = valu(name, v, inst.encoding), + Fields::Vintrp { dst, src, attr } => { + let src = match (name, src) { + ("v_interp_mov_f32", Operand::Const(p)) => ["p10", "p20", "p0"] + .get(usize::from(*p)) + .map_or("p?".into(), |p| p.to_string()), + _ => src.to_string(), + }; + out = format!("{dst}, {src}, {attr}"); + } + Fields::Ds { + dst, + addr, + data, + offset0, + offset1, + gds, + } => { + out = join(dst.iter().chain(addr).chain(data).map(|o| o.to_string())); + if super::fields::ds_pair(name) { + if *offset0 != 0 { + let _ = write!(out, " offset0:{offset0}"); + } + if *offset1 != 0 { + let _ = write!(out, " offset1:{offset1}"); + } + } else { + let offset = u16::from(*offset1) << 8 | u16::from(*offset0); + if offset != 0 { + let _ = write!(out, " offset:{offset}"); + } + } + if *gds { + out.push_str(" gds"); + } + } + Fields::Buffer { + data, + addr, + rsrc, + soffset, + offset, + offen, + idxen, + format, + lds, + tfe, + cache, + } => { + if let Some(data) = data { + out = format!("{data}, {addr}, {rsrc}, {soffset}"); + if *idxen { + out.push_str(" idxen"); + } + if *offen { + out.push_str(" offen"); + } + if *offset != 0 { + let _ = write!(out, " offset:{offset}"); + } + if let Some(format) = format { + let _ = write!(out, " format:[{}]", buffer_format(*format)); + } + } + flags(&mut out, cache, false); + if *lds { + out.push_str(" lds"); + } + if *tfe { + out.push_str(" tfe"); + } + } + Fields::Image { + data, + addr, + rsrc, + sampler, + dmask, + dim, + unorm, + r128, + a16, + d16, + tfe, + lwe, + cache, + } => { + let addr = match addr.as_slice() { + [one] => one.to_string(), + many => format!( + "[{}]", + many.iter() + .map(|o| o.to_string()) + .collect::<Vec<_>>() + .join(",") + ), + }; + out = join( + [data.to_string(), addr, rsrc.to_string()] + .into_iter() + .chain(sampler.map(|s| s.to_string())), + ); + if *dmask != 1 { + let _ = write!(out, " dmask:0x{dmask:x}"); + } + let dims = [ + "1D", + "2D", + "3D", + "CUBE", + "1D_ARRAY", + "2D_ARRAY", + "2D_MSAA", + "2D_MSAA_ARRAY", + ]; + let _ = write!(out, " dim:SQ_RSRC_IMG_{}", dims[usize::from(*dim & 7)]); + for (on, text) in [(*r128, "r128"), (*unorm, "unorm")] { + if on { + out.push(' '); + out.push_str(text); + } + } + flags(&mut out, cache, true); + for (on, text) in [(*a16, "a16"), (*d16, "d16"), (*tfe, "tfe"), (*lwe, "lwe")] { + if on { + out.push(' '); + out.push_str(text); + } + } + } + Fields::Flat { + dst, + addr, + data, + saddr, + offset, + lds, + cache, + } => { + let addr = addr.map_or("off".into(), |a| a.to_string()); + out = join( + dst.iter() + .map(|o| o.to_string()) + .chain([addr]) + .chain(data.iter().chain(saddr).map(|o| o.to_string())), + ); + if *offset != 0 { + let _ = write!(out, " inst_offset:{offset}"); + } + flags(&mut out, cache, false); + if *lds { + out.push_str(" lds"); + } + } + Fields::Exp { + target, + src, + compr, + done, + vm, + } => { + let target = match *target { + 0..=7 => format!("mrt{target}"), + 8 => "mrtz".into(), + 9 => "null".into(), + 12..=15 => format!("pos{}", target - 12), + 20 => "prim".into(), + 32..=63 => format!("param{}", target - 32), + _ => format!("<target {target}>"), + }; + out = join( + [target].into_iter().chain( + src.iter() + .map(|s| s.map_or("off".into(), |o| o.to_string())), + ), + ); + for (on, text) in [(*done, " done"), (*compr, " compr"), (*vm, " vm")] { + if on { + out.push_str(text); + } + } + } + } + out +} + +/// Cache flags; images write `dlc` first. +fn flags(out: &mut String, cache: &Cache, dlc_first: bool) { + let dlc = (cache.dlc, " dlc"); + let (first, last) = if dlc_first { + (dlc, (false, "")) + } else { + ((false, ""), dlc) + }; + for (on, text) in [first, (cache.glc, " glc"), (cache.slc, " slc"), last] { + if on { + out.push_str(text); + } + } + if out.starts_with(' ') { + out.remove(0); + } +} + +fn label(inst: &Instruction, imm: u16) -> String { + let target = inst.offset as i64 + 4 * inst.words.len() as i64 + 4 * i64::from(imm as i16); + format!("label_{target:04X}") +} + +fn hwreg(imm: u16) -> String { + let (id, offset, size) = (imm & 0x3F, imm >> 6 & 0x1F, (imm >> 11 & 0x1F) + 1); + let name = match id { + 1 => "HW_REG_MODE".into(), + 20 => "HW_REG_SHADER_FLAT_SCRATCH_LO".into(), + 21 => "HW_REG_SHADER_FLAT_SCRATCH_HI".into(), + 25 => "HW_REG_POPS_PACKER".into(), + _ => id.to_string(), + }; + if offset == 0 && size == 32 { + format!("hwreg({name})") + } else { + format!("hwreg({name}, {offset}, {size})") + } +} + +fn waitcnt(imm: u16) -> String { + let vm = imm & 0xF | (imm >> 14) << 4; + let exp = imm >> 4 & 7; + let lgkm = imm >> 8 & 0x3F; + let mut parts = Vec::new(); + if vm != 0x3F { + parts.push(format!("vmcnt({vm})")); + } + if exp != 7 { + parts.push(format!("expcnt({exp})")); + } + if lgkm != 0x3F { + parts.push(format!("lgkmcnt({lgkm})")); + } + if matches!(parts.len(), 0 | 3) { + return format!("0x{imm:04x}"); + } + parts.join(" & ") +} + +fn sendmsg(imm: u16) -> String { + let (msg, op, stream) = (imm & 0xF, imm >> 4 & 7, imm >> 8 & 3); + let msg_name = match msg { + 2 => "MSG_GS".into(), + 3 => "MSG_GS_DONE".into(), + 7 => "MSG_ORDERED_PS_DONE".into(), + 9 => "MSG_GS_ALLOC_REQ".into(), + _ => msg.to_string(), + }; + let op_name = ["GS_OP_NOP", "GS_OP_CUT", "GS_OP_EMIT", "GS_OP_EMIT_CUT"] + .get(usize::from(op)) + .map_or(op.to_string(), |s| s.to_string()); + if msg == 3 && op == 0 { + format!("sendmsg({msg_name}, {op_name})") + } else { + format!("sendmsg({msg_name}, {op_name}, {stream})") + } +} + +fn buffer_format(format: u8) -> String { + const NAMES: [&str; 78] = [ + "INVALID", + "8_UNORM", + "8_SNORM", + "8_USCALED", + "8_SSCALED", + "8_UINT", + "8_SINT", + "16_UNORM", + "16_SNORM", + "16_USCALED", + "16_SSCALED", + "16_UINT", + "16_SINT", + "16_FLOAT", + "8_8_UNORM", + "8_8_SNORM", + "8_8_USCALED", + "8_8_SSCALED", + "8_8_UINT", + "8_8_SINT", + "32_UINT", + "32_SINT", + "32_FLOAT", + "16_16_UNORM", + "16_16_SNORM", + "16_16_USCALED", + "16_16_SSCALED", + "16_16_UINT", + "16_16_SINT", + "16_16_FLOAT", + "10_11_11_UNORM", + "10_11_11_SNORM", + "10_11_11_USCALED", + "10_11_11_SSCALED", + "10_11_11_UINT", + "10_11_11_SINT", + "10_11_11_FLOAT", + "11_11_10_UNORM", + "11_11_10_SNORM", + "11_11_10_USCALED", + "11_11_10_SSCALED", + "11_11_10_UINT", + "11_11_10_SINT", + "11_11_10_FLOAT", + "10_10_10_2_UNORM", + "10_10_10_2_SNORM", + "10_10_10_2_USCALED", + "10_10_10_2_SSCALED", + "10_10_10_2_UINT", + "10_10_10_2_SINT", + "2_10_10_10_UNORM", + "2_10_10_10_SNORM", + "2_10_10_10_USCALED", + "2_10_10_10_SSCALED", + "2_10_10_10_UINT", + "2_10_10_10_SINT", + "8_8_8_8_UNORM", + "8_8_8_8_SNORM", + "8_8_8_8_USCALED", + "8_8_8_8_SSCALED", + "8_8_8_8_UINT", + "8_8_8_8_SINT", + "32_32_UINT", + "32_32_SINT", + "32_32_FLOAT", + "16_16_16_16_UNORM", + "16_16_16_16_SNORM", + "16_16_16_16_USCALED", + "16_16_16_16_SSCALED", + "16_16_16_16_UINT", + "16_16_16_16_SINT", + "16_16_16_16_FLOAT", + "32_32_32_UINT", + "32_32_32_SINT", + "32_32_32_FLOAT", + "32_32_32_32_UINT", + "32_32_32_32_SINT", + "32_32_32_32_FLOAT", + ]; + NAMES + .get(usize::from(format)) + .map_or(format!("{format}"), |n| format!("BUF_FMT_{n}")) +} + +fn valu(name: &str, v: &Valu, encoding: Encoding) -> String { + let bit = |mask: u8, i: usize| mask >> i & 1 != 0; + let mix = name.starts_with("v_fma_mix"); + let src = |i: usize| { + let o = v.src[i]; + let mut s = o.to_string(); + if let Some(sdwa) = v.sdwa + && bit(sdwa.sext, i) + { + s = format!("sext({s})"); + } + if encoding == Encoding::Vop3p { + if mix { + if bit(v.opsel_hi, i) { + s = format!("{}({s})", if bit(v.opsel, i) { "sel_hi" } else { "sel_lo" }); + } + if bit(v.neg_hi, i) { + s = format!("abs({s})"); + } + if bit(v.neg, i) { + s = format!("-{s}"); + } + } else { + if bit(v.neg, i) && bit(v.neg_hi, i) { + s = format!("-{s}"); + } + match (bit(v.opsel, i), bit(v.opsel_hi, i)) { + (false, true) => {} + (false, false) => s = format!("sel_lo({s})"), + (true, true) => s = format!("sel_hi({s})"), + (true, false) => s = format!("sel_hi_lo({s})"), + } + } + } else { + if bit(v.abs, i) { + s = format!("abs({s})"); + } + if bit(v.neg, i) { + s = format!("-{s}"); + } + // v_permlane*: the opsel bits are fi and bound_ctrl. + if bit(v.opsel, i) && !name.starts_with("v_permlane") { + s = format!("sel_hi({s})"); + } + } + s + }; + let mut ops: Vec<String> = v + .dst + .iter() + .chain(&v.carry) + .map(|o| o.to_string()) + .collect(); + let mut order: Vec<usize> = (0..v.src.len()).collect(); + if name.starts_with("v_interp_") && order.len() > 1 { + // dst, i/j, attribute, then the p1 result for p2. + order.swap(0, 1); + } + ops.extend(order.into_iter().map(src)); + let mut out = ops.join(", "); + let mut suffix = |s: &str| { + out.push(' '); + out.push_str(s); + }; + if let Some(Operand::Attr { high: true, .. }) = v.src.first() { + suffix("high"); + } + let omod = ["", "mul:2", "mul:4", "div:2"][usize::from(v.omod & 3)]; + if name.starts_with("v_permlane") { + if v.opsel & 1 != 0 { + suffix("fi:1"); + } + if v.opsel & 2 != 0 { + suffix("bound_ctrl:1"); + } + } + if let Some(sdwa) = v.sdwa { + if v.clamp { + suffix("clamp"); + } + if !omod.is_empty() { + suffix(omod); + } + let sel = [ + "BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD", "?", + ]; + if sdwa.dst_sel != 6 { + suffix(&format!("dst_sel:{}", sel[usize::from(sdwa.dst_sel & 7)])); + } + if sdwa.dst_unused != 0 { + let unused = ["UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE", "?"]; + suffix(&format!( + "dst_unused:{}", + unused[usize::from(sdwa.dst_unused & 3)] + )); + } + for (i, s) in sdwa.src_sel.iter().enumerate() { + if *s != 6 { + suffix(&format!("src{i}_sel:{}", sel[usize::from(s & 7)])); + } + } + } else { + if !omod.is_empty() { + suffix(omod); + } + if v.clamp { + suffix("clamp"); + } + } + match v.dpp { + Some(Dpp::Row { + ctrl, + row_mask, + bank_mask, + bound_ctrl, + fi, + }) => { + suffix(&match ctrl { + 0x000..=0x0FF => format!( + "quad_perm:[{},{},{},{}]", + ctrl & 3, + ctrl >> 2 & 3, + ctrl >> 4 & 3, + ctrl >> 6 & 3 + ), + 0x101..=0x10F => format!("row_shl:{}", ctrl & 0xF), + 0x111..=0x11F => format!("row_shr:{}", ctrl & 0xF), + 0x121..=0x12F => format!("row_ror:{}", ctrl & 0xF), + 0x140 => "row_mirror".into(), + 0x141 => "row_half_mirror".into(), + 0x150..=0x15F => format!("row_share:{}", ctrl & 0xF), + 0x160..=0x16F => format!("row_xmask:{}", ctrl & 0xF), + _ => format!("dpp_ctrl:0x{ctrl:x}"), + }); + if row_mask != 0xF { + suffix(&format!("row_mask:0x{row_mask:x}")); + } + if bank_mask != 0xF { + suffix(&format!("bank_mask:0x{bank_mask:x}")); + } + if bound_ctrl { + suffix("bound_ctrl:1"); + } + if fi { + suffix("fi:1"); + } + } + Some(Dpp::Lanes { sel, fi }) => { + let lanes: Vec<String> = (0..8).map(|i| (sel >> (3 * i) & 7).to_string()).collect(); + suffix(&format!("dpp8:[{}]", lanes.join(","))); + if fi { + suffix("fi:1"); + } + } + None => {} + } + out +} + +#[cfg(test)] +mod tests { + use crate::gfx10::{Fields, Operand, decode}; + + /// Text of each instruction in `words` (a straight-line program). + fn texts(words: &[u32], wave64: bool) -> Vec<String> { + let mut code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + code.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm + let insts = decode(&code).unwrap(); + insts[..insts.len() - 1] + .iter() + .map(|i| i.text(wave64)) + .collect() + } + + fn one(words: &[u32], wave64: bool) -> String { + let t = texts(words, wave64); + assert_eq!(t.len(), 1, "{t:?}"); + t[0].clone() + } + + #[test] + fn scalar() { + assert_eq!( + texts(&[0xBF88_0001, 0xBF8C_0070, 0xBE80_03FF, 0x1234_5678], true), + [ + "s_cbranch_execz label_0008", + "s_waitcnt vmcnt(0) & lgkmcnt(0)", + "s_mov_b32 s0, lit(0x12345678)", + ] + ); + assert_eq!(one(&[0x8782_027E], true), "s_and_b64 s[2:3], exec, s[2:3]"); + assert_eq!( + one(&[0xF408_0501, 0xFA00_0040], true), + "s_load_dwordx4 s[20:23], s[2:3], 0x000040" + ); + assert_eq!( + one(&[0xF420_0144, 0x0400_0000], true), + "s_buffer_load_dword s5, s[8:11], s2" + ); + } + + #[test] + fn lane_masks_follow_the_wave_size() { + let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3 + assert_eq!(one(&cmp, false), "v_cmp_gt_f32 vcc_lo, 0.5, v3"); + assert_eq!(one(&cmp, true), "v_cmp_gt_f32 vcc, 0.5, v3"); + let vop3 = [0xD401_0106, 0x0001_E501]; // v_cmp_lt_f32 to s6, |v1| < 1.0 + assert_eq!(one(&vop3, false), "v_cmp_lt_f32 s6, abs(v1), 1.0"); + assert_eq!(one(&vop3, true), "v_cmp_lt_f32 s[6:7], abs(v1), 1.0"); + assert_eq!( + one(&[0x0202_0480], false), + "v_cndmask_b32 v1, 0, v2, vcc_lo" + ); + assert_eq!( + one(&[0x5006_0801], true), + "v_add_co_ci_u32 v3, vcc, s1, v4, vcc" + ); + } + + #[test] + fn vector_modifiers() { + assert_eq!( + one(&[0x1004_0AFF, 0x3F00_0001], true), + "v_mul_f32 v2, lit(0x3f000001), v5" + ); + assert_eq!( + one(&[0xD54B_8004, 0x2BC0_0501], true), + "v_fma_f32 v4, -v1, s2, 0.5 mul:2 clamp" + ); + assert_eq!( + one(&[0x7E02_16F9, 0x0605_0602], true), + "v_cvt_f32_f16 v1, v2 src0_sel:WORD_1" + ); + assert_eq!( + one(&[0x7E06_02E9, 0x0539_7701], true), + "v_mov_b32 v3, v1 dpp8:[7,6,5,4,3,2,1,0]" + ); + assert_eq!( + one(&[0x7E0A_02FA, 0xFF08_B106], true), + "v_mov_b32 v5, v6 quad_perm:[1,0,3,2] bound_ctrl:1" + ); + assert_eq!( + one(&[0xCC20_0C01, 0x2C10_0702], true), + "v_fma_mix_f32 v1, -sel_hi(v2), s3, abs(v4)" + ); + } + + #[test] + fn memory_and_export() { + assert_eq!( + one(&[0xE034_7010, 0x0102_0402], true), + "buffer_load_dwordx2 v[4:5], v[2:3], s[8:11], s1 idxen offen offset:16 glc" + ); + assert_eq!( + one(&[0xD8DC_0302, 0x0600_0001], true), + "ds_read2_b32 v[6:7], v1 offset0:2 offset1:3" + ); + assert_eq!( + one(&[0xF800_1C0F, 0x0000_0302], true), + "exp mrt0, v2, v2, v3, v3 done compr vm" + ); + } + + #[test] + fn image_d16_data_is_packed() { + // Three f16 channels occupy two VGPRs; NSA lists the addresses. + let words = [0xF09C_070A, 0x8024_0801, 0x0000_0005]; + assert_eq!( + one(&words, true), + "image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 dim:SQ_RSRC_IMG_2D d16" + ); + let code: Vec<u8> = words + .iter() + .chain(&[0xBF81_0000]) + .flat_map(|w| w.to_le_bytes()) + .collect(); + let Fields::Image { data, addr, .. } = decode(&code).unwrap()[0].fields(true) else { + panic!("not an image instruction"); + }; + assert_eq!(data, Operand::Vector { reg: 8, dwords: 2 }); + assert_eq!(addr.len(), 2); + } +} diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs new file mode 100644 index 000000000..e1fb439c5 --- /dev/null +++ b/crates/victory-shader/src/io.rs @@ -0,0 +1,833 @@ +//! I/O raising (decision 0003): what a program's input registers, its +//! interpolation and its exports mean. +//! +//! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed +//! order (barycentrics, then position, front face...). `v_interp_p1` and +//! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of +//! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit +//! export patch ([`NativeProgram::patched_code`]) exports carry plain +//! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and +//! sample mask, `null` nothing. A lane whose EXEC bit is clear at the +//! export that ends the program (`done`) is discarded: that export's guard +//! after structurisation. +//! +//! Vertex shaders that run as the hardware VS get the vertex id in v0, the +//! primitive id in v2 and the instance id in v3; the fetch shader loads +//! channel k of each attribute into its VGPR + k. `exp pos0` is the +//! position, `exp param<n>` the output with parameter n. +//! +//! Attributes and outputs are named by their row: a register of the +//! container's signature part. +//! +//! Compute programs get the thread id in the group in v0-v2 and the group +//! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them. +//! +//! Mesh programs run as one NGG stage. The program computes its thread +//! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and +//! its group id from v5 of the first lane (`v_readfirstlane`: the group +//! times the group size). Lane n exports vertex n (`exp pos`, `exp param`) +//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20, +//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One +//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | +//! primitives << 12). + +use crate::ShaderError; +use crate::gfx10::{Fields, Operand}; +use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads}; +use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage}; +use crate::resource::Site; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Input { + VertexId, + PrimitiveId, + InstanceId, + /// A vertex attribute the fetch shader loads. + Attribute { + row: u8, + channel: u8, + }, + /// `index` 0 is i, 1 is j (2 the pull model's w). + Barycentric { + kind: Barycentric, + index: u8, + }, + /// Pixel position channel (0-3: x, y, z, w). + Position(u8), + FrontFace, + /// Sample id and other bits. + Ancillary, + SampleCoverage, + FixedPosition, + LineStipple, + /// Compute: thread-group id component (an SGPR). + GroupId(u8), + /// Compute: thread id within the group, component (a VGPR). + ThreadIdInGroup(u8), + /// Compute: the thread-group info SGPR (wave index and count). + GroupInfo, + /// Mesh: v5, the group id times the group size (read as uniform). + MeshGroup, + /// Mesh: s3, the wave's index in the group in bits 24-27. + MergedWaveInfo, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Barycentric { + PerspectiveSample, + PerspectiveCenter, + PerspectiveCentroid, + PerspectivePullModel, + LinearSample, + LinearCenter, + LinearCentroid, +} + +/// The pixel input VGPRs in hardware order: one entry per +/// `SPI_PS_INPUT_ADDR` bit. +const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [ + (2, Some(Barycentric::PerspectiveSample)), + (2, Some(Barycentric::PerspectiveCenter)), + (2, Some(Barycentric::PerspectiveCentroid)), + (3, Some(Barycentric::PerspectivePullModel)), + (2, Some(Barycentric::LinearSample)), + (2, Some(Barycentric::LinearCenter)), + (2, Some(Barycentric::LinearCentroid)), + (1, None), // line stipple + (1, None), // position x + (1, None), // y + (1, None), // z + (1, None), // w + (1, None), // front face + (1, None), // ancillary + (1, None), // sample coverage + (1, None), // fixed-point position +]; + +fn ps_system(bit: usize) -> Input { + match bit { + 7 => Input::LineStipple, + 8..=11 => Input::Position(bit as u8 - 8), + 12 => Input::FrontFace, + 13 => Input::Ancillary, + 14 => Input::SampleCoverage, + _ => Input::FixedPosition, + } +} + +/// An attribute channel of the input signature. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Attribute { + pub usage: Usage, + pub row: u8, + pub channel: u8, + /// The upper f16 half of the channel (packed fp16 inputs). + pub high: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Interp { + /// This site's result (`v_interp_p2*`) is the attribute interpolated + /// with `barycentric`; `first` are the `v_interp_p1*` halves it + /// completes (one per path where the compiler shares a first half). + Interpolated { + attribute: Attribute, + barycentric: Barycentric, + first: Vec<Site>, + }, + /// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10, + /// 1 for P20, 2 for P0 (the provoking vertex). + Vertex { attribute: Attribute, vertex: u8 }, + /// A half of an interpolation whose i or j is computed rather than + /// loaded: each half evaluates as the hardware does, from the + /// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 = + /// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0). + Weighted { attribute: Attribute }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Target { + Color(u8), + /// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables). + Depth, + Null, + Position(u8), + Param { + usage: Usage, + row: u8, + }, + /// `param0` of a vertex shader without outputs: the hardware wants one + /// parameter export regardless. + Unread, + /// The primitive export of a merged or mesh stage. + Primitive, + /// A mesh program's per-primitive output (a row of `PSG1`). + PrimitiveParam { + usage: Usage, + row: u8, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Export { + pub site: Site, + pub target: Target, + /// Per channel, as the instruction enables them. + pub values: [Option<Value>; 4], + /// Two f16 values per dword. + pub compressed: bool, + /// The program's last export (for pixels: kills the lanes not in EXEC). + pub done: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Io { + /// Input values the hardware loads, with their meaning; other VGPRs + /// read before written hold undefined values. + pub inputs: Vec<(Value, Input)>, + pub interps: Vec<(Site, Interp)>, + pub exports: Vec<Export>, + /// Compute: how many SGPRs the hardware initializes + /// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)). + pub initialized_sgprs: Option<u8>, +} + +/// Raises the I/O of `p`, built from `native`'s patched code. Fails for +/// stages whose stage data is not read and on constructs not covered yet. +pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { + let unsupported = |offset, what| ShaderError::Unsupported { offset, what }; + let (loaded, ps_inputs, params) = match (&native.io, native.stage) { + ( + StageIo::Ps { + inputs, input_addr, .. + }, + HwStage::Ps, + ) => { + // A pixel shader exports no parameters; `[]` never reaches `Unread`. + let loaded = ps_vgprs(*input_addr) + .into_iter() + .map(|(r, i)| (Reg::V(r), i)) + .collect(); + (loaded, &inputs[..], &[][..]) + } + (StageIo::Vs { inputs, outputs }, HwStage::Vs) => { + let mut loaded = vec![ + (Reg::V(0), Input::VertexId), + (Reg::V(2), Input::PrimitiveId), + (Reg::V(3), Input::InstanceId), + ]; + for i in inputs { + for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) { + let input = Input::Attribute { + row: i.row, + channel, + }; + loaded.push((Reg::V(i.vgpr + channel), input)); + } + } + (loaded, &[][..], &outputs[..]) + } + // Compute: thread ids in v0-v2, group ids and the group info in the + // SGPRs after the user data. + (StageIo::Cs(cs), HwStage::Cs) => { + let (ids, info) = cs.system_sgprs(); + let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs()) + .map(|c| (Reg::V(c), Input::ThreadIdInGroup(c))) + .collect(); + for (c, s) in ids.into_iter().enumerate() { + if let Some(s) = s { + loaded.push((Reg::S(s), Input::GroupId(c as u8))); + } + } + loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo))); + (loaded, &[][..], &[][..]) + } + (StageIo::Ms(ms), HwStage::Ms) => { + // The group input, and the phis that may carry it past a join. + let mut group: Vec<Value> = p + .inputs + .iter() + .filter(|i| i.0 == Reg::V(5)) + .map(|i| i.1) + .collect(); + // No lane is active over the EXEC-zero edge of s_cbranch_execz or + // _execnz, the same case as a partial-EXEC write below. + let no_lanes = |q: usize, b: usize| match ( + p.blocks[q].insts.last().map(Inst::name), + p.blocks[q].exit, + ) { + (Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => { + taken == b && not_taken != b + } + (Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => { + not_taken == b && taken != b + } + _ => false, + }; + while let Some(v) = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f))) + .find_map(|(b, f)| { + let mut args = f.args.iter().zip(&p.blocks[b].preds); + let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b)); + (carried && !group.contains(&f.value)).then_some(f.value) + }) + { + group.push(v); + } + // The group input holds the same value in every lane only as the + // first lane reads it. A write to v5 reads its old value too, which + // only lanes outside EXEC keep. + // shortcut: writes that may keep the old v5 in active lanes + // (v_fmac_f32's accumulator, a 16-bit half or d16 load, + // v_writelane_b32, v_movreld_b32, DPP that skips lanes) and + // partial-EXEC writes pass; check those too if a mesh program + // writes v5 that way. + let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| { + i.read(Reg::V(5)).is_some_and(|v| group.contains(&v)) + && i.name() != "v_readfirstlane_b32" + && (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5))) + }); + if let Some(i) = per_lane { + return Err(unsupported( + i.machine.offset, + "the mesh group input read per lane", + )); + } + let loaded = vec![ + (Reg::V(5), Input::MeshGroup), + (Reg::S(3), Input::MergedWaveInfo), + ]; + (loaded, &[][..], &ms.outputs[..]) + } + _ => return Err(unsupported(0, "I/O of this stage")), + }; + let inputs: Vec<(Value, Input)> = p + .inputs + .iter() + .filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1))) + .collect(); + let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1); + let attribute = |inst: &Inst, attr: &Operand| match *attr { + Operand::Attr { index, chan, high } => ps_inputs + .iter() + .find(|i: &&PsInput| i.attr == index) + .map(|i| Attribute { + usage: i.usage, + row: i.row, + channel: chan, + high, + }) + .ok_or(unsupported( + inst.machine.offset, + "an interpolated attribute the stage data does not list", + )), + _ => Err(unsupported(inst.machine.offset, "an interpolation operand")), + }; + // A VGPR value's barycentric kind and index, if it is one as loaded. + let barycentric = |v: Option<Value>| match v.and_then(input_of) { + Some(Input::Barycentric { kind, index }) => Some((kind, index)), + _ => None, + }; + + let mut io = Io { + inputs: inputs.clone(), + initialized_sgprs: match &native.io { + StageIo::Cs(cs) => Some(cs.initialized_sgprs()), + _ => None, + }, + ..Io::default() + }; + let defs: std::collections::HashMap<Value, Site> = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .insts + .iter() + .enumerate() + .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i)))) + }) + .collect(); + let phis: std::collections::HashMap<Value, (usize, usize)> = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .phis + .iter() + .enumerate() + .map(move |(i, phi)| (phi.value, (b, i))) + }) + .collect(); + let halves = Halves { + p, + defs: &defs, + phis: &phis, + }; + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let site = (b, i); + let at = inst.machine.offset; + let name = inst.name(); + match &inst.fields { + Fields::Vintrp { dst, src, attr } => { + let attribute = attribute(inst, attr)?; + match (name, *src) { + ("v_interp_mov_f32", Operand::Const(vertex)) => { + io.interps + .push((site, Interp::Vertex { attribute, vertex })); + } + // The first half is P0 + i·P10. Recorded so a program + // that reads it, not only the finished p2, still runs. + ("v_interp_p1_f32", _) => { + io.interps.push((site, Interp::Weighted { attribute })); + } + ("v_interp_p2_f32", Operand::Vector { reg, .. }) => { + let Operand::Vector { reg: d, .. } = *dst else { + return Err(unsupported(at, "an interpolation operand")); + }; + // The first half's result is this one's old dst. + let interp = halves + .pair( + attr, + inst.read(Reg::V(d)), + inst.read(Reg::V(reg)), + &barycentric, + ) + .map_err(|what| unsupported(at, what))?; + push_pair(&mut io, site, interp, attribute); + } + _ => return Err(unsupported(at, "an interpolation form")), + } + } + Fields::Valu(v) if name.starts_with("v_interp_") => match name { + "v_interp_p1ll_f16" => { + let attribute = attribute(inst, &v.src[0])?; + io.interps.push((site, Interp::Weighted { attribute })); + } + "v_interp_p2_f16" => { + let attribute = attribute(inst, &v.src[0])?; + let read = |k: usize| match v.src.get(k) { + Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)), + _ => None, + }; + let interp = halves + .pair(&v.src[0], read(2), read(1), &barycentric) + .map_err(|what| unsupported(at, what))?; + push_pair(&mut io, site, interp, attribute); + } + _ => return Err(unsupported(at, "an interpolation form")), + }, + Fields::Exp { + target, + src, + compr, + done, + .. + } => { + let target = match *target { + t @ 0..=7 => Target::Color(t), + 8 => Target::Depth, + 9 => Target::Null, + t @ 12..=16 => Target::Position(t - 12), + 20 => Target::Primitive, + 32 if params.is_empty() => Target::Unread, + t @ 32..=63 => { + // Bit 7: a mesh program's per-primitive output. + let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or( + unsupported(at, "a parameter export the stage data does not list"), + )?; + let (usage, row) = (o.usage, o.row); + if o.param & 0x80 != 0 { + Target::PrimitiveParam { usage, row } + } else { + Target::Param { usage, row } + } + } + _ => return Err(unsupported(at, "an export target")), + }; + let values = src.map(|s| match s { + Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)), + _ => None, + }); + io.exports.push(Export { + site, + target, + values, + compressed: *compr, + done: *done, + }); + } + _ => {} + } + } + } + Ok(io) +} + +/// The pixel input VGPRs that `addr` enables, with their meaning. +fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> { + let mut out = Vec::new(); + let mut next = 0u8; + for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() { + if addr >> bit & 1 == 0 { + continue; + } + for index in 0..count { + let input = match kind { + Some(kind) => Input::Barycentric { kind, index }, + None => ps_system(bit), + }; + out.push((next + index, input)); + } + next += count; + } + out +} + +/// An interpolation before its attribute is known: `barycentric` none +/// when i or j is computed. +struct Pair { + barycentric: Option<Barycentric>, + first: Vec<Site>, +} + +impl Pair { + fn with(self, attribute: Attribute) -> Interp { + match self.barycentric { + Some(barycentric) => Interp::Interpolated { + attribute, + barycentric, + first: self.first, + }, + None => Interp::Weighted { attribute }, + } + } +} + +/// Records interpolation `pair` at `site`, and its first halves too when +/// they evaluate on their own (computed barycentrics). +fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) { + if pair.barycentric.is_none() { + for &f in &pair.first { + if !io.interps.iter().any(|(s, _)| *s == f) { + io.interps.push((f, Interp::Weighted { attribute })); + } + } + } + io.interps.push((site, pair.with(attribute))); +} + +/// Finds the first halves of interpolations. +struct Halves<'a> { + p: &'a Program, + defs: &'a std::collections::HashMap<Value, Site>, + phis: &'a std::collections::HashMap<Value, (usize, usize)>, +} + +impl Halves<'_> { + /// The interpolation whose second half reads the first half's result + /// `acc`, the barycentric `j`, and attribute `attr`: every first half + /// must read the same attribute channel. With j and every first half's + /// i loaded as one kind's, the pair interpolates with that kind; + /// otherwise each half evaluates on its own (`Interp::Weighted`). + fn pair( + &self, + attr: &Operand, + acc: Option<Value>, + j: Option<Value>, + barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>, + ) -> Result<Pair, &'static str> { + let mut first = Vec::new(); + self.sites( + acc.ok_or("an interpolation without its first half")?, + &mut Vec::new(), + &mut first, + )?; + let mut kind = match barycentric(j) { + Some((kind, 1)) => Some(kind), + _ => None, + }; + for &(b, i) in &first { + let inst = &self.p.blocks[b].insts[i]; + let (a, i) = match &inst.fields { + Fields::Vintrp { + src: Operand::Vector { reg, .. }, + attr, + .. + } if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))), + Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) { + Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))), + _ => return Err("an interpolation without its first half"), + }, + _ => return Err("an interpolation without its first half"), + }; + if a != *attr { + return Err("interpolation halves of different attributes"); + } + if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) { + kind = None; + } + } + Ok(Pair { + barycentric: kind, + first, + }) + } + + /// The instructions `v` comes from, through phis (`seen`: phis on the + /// way; a loop back to one adds nothing). + fn sites( + &self, + v: Value, + seen: &mut Vec<Value>, + out: &mut Vec<Site>, + ) -> Result<(), &'static str> { + if let Some(&site) = self.defs.get(&v) { + if !out.contains(&site) { + out.push(site); + } + return Ok(()); + } + let &(b, i) = self + .phis + .get(&v) + .ok_or("an interpolation without its first half")?; + if !seen.contains(&v) { + seen.push(v); + for &a in &self.p.blocks[b].phis[i].args { + self.sites(a, seen, out)?; + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::native::ExportPatch; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn program(words: &[u32]) -> Program { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + crate::ir::build(&code, false, 256).unwrap() + } + + fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram { + NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs, + input_addr, + db_shader_control: 0, + patches: Vec::<ExportPatch>::new(), + }, + code: vec![], + } + } + + const TEXCOORD: PsInput = PsInput { + usage: Usage::Generic, + row: 1, + mask: 3, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 1, + }; + + #[test] + fn interpolation_pairs_and_color_exports() { + // Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j + // in v0/v1, then exported unconverted to MRT0. + let p = program(&[ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800_180F, + 0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm + S_ENDPGM, + ]); + let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap(); + let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1; + let center = |index| Input::Barycentric { + kind: Barycentric::PerspectiveCenter, + index, + }; + assert!(io.inputs.contains(&(input(0), center(0)))); + assert!(io.inputs.contains(&(input(1), center(1)))); + // v2 and v3 are read before written but hold nothing. + assert!(!io.inputs.iter().any(|i| i.0 == input(3))); + assert_eq!( + io.interps, + [( + (0, 1), + Interp::Interpolated { + attribute: Attribute { + usage: Usage::Generic, + row: 1, + channel: 0, + high: false + }, + barycentric: Barycentric::PerspectiveCenter, + first: vec![(0, 0)], + } + )] + ); + let [e] = &io.exports[..] else { + panic!("{:?}", io.exports) + }; + assert_eq!( + (e.target, e.done, e.compressed), + (Target::Color(0), true, false) + ); + assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2))); + } + + #[test] + fn unpaired_or_unknown_interpolation_fails() { + // p2 alone: its old dst is no p1's result. + let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x + assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err()); + // attr1 is not in the stage data. + let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x + assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err()); + } + + #[test] + fn computed_barycentrics_evaluate_each_half() { + // i scaled before the first half: both halves stand on their own. + let p = program(&[ + 0x1006_00F0, // v_mul_f32 v3, 0.5, v0 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + S_ENDPGM, + ]); + let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap(); + let attribute = Attribute { + usage: Usage::Generic, + row: 1, + channel: 0, + high: false, + }; + let mut interps = io.interps.clone(); + interps.sort_by_key(|i| i.0); + assert_eq!( + interps, + [ + ((0, 1), Interp::Weighted { attribute }), + ((0, 2), Interp::Weighted { attribute }), + ] + ); + } + + #[test] + fn mesh_inputs_and_primitive_export() { + let mesh = |words: &[u32]| { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 256).unwrap(); + let native = NativeProgram { + stage: HwStage::Ms, + wave64: true, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 128, + max_vertices: 128, + max_primitives: 128, + topology: 2, + lds_bytes: 0, + }), + code, + }; + raise(&p, &native) + }; + let io = mesh(&[ + 0x7E04_0505, // v_readfirstlane_b32 s2, v5 + 0xF800_0941, + 0x0000_0009, // exp prim, v9, off, off, off done + S_ENDPGM, + ]) + .unwrap(); + assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup)); + assert_eq!(io.exports[0].target, Target::Primitive); + // The group input is uniform only as the first lane reads it. + assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5 + // Also as an operand of a write to v5, or after a join. + let per_lane: [&[u32]; 5] = [ + &[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1 + &[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5 + &[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1] + &[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1 + &[ + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0001, // s_cbranch_scc1 -> 0xc + 0x7E0A_0280, // v_mov_b32 v5, 0 + 0x7E02_0305, // 0xc: v_mov_b32 v1, v5 + S_ENDPGM, + ], + ]; + let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect(); + assert!(accepted.is_empty(), "accepted: {accepted:08X?}"); + // Overwriting v5 reads the group input only for lanes outside EXEC: + // v_mov_b32 v5, 0; v_mov_b32 v1, v5. + assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok()); + // Skipping that write with s_cbranch_execz is the same case: under the + // same mask, the read sees only the 0. + let reuse = [ + 0x7E04_0505, // v_readfirstlane_b32 s2, v5 + 0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0 + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0001, // s_cbranch_execz -> 0x14 + 0x7E0A_0280, // v_mov_b32 v5, 0 + 0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7] + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0001, // s_cbranch_execz -> 0x24 + 0x7E02_0305, // v_mov_b32 v1, v5 + 0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7] + S_ENDPGM, + ]; + assert_eq!(mesh(&reuse).map(|_| ()), Ok(())); + } + + #[test] + fn pixel_vgprs_follow_the_input_address() { + // Linear center (bit 5), then position x and y (bits 8, 9). + let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9); + assert_eq!( + v, + [ + ( + 0, + Input::Barycentric { + kind: Barycentric::LinearCenter, + index: 0 + } + ), + ( + 1, + Input::Barycentric { + kind: Barycentric::LinearCenter, + index: 1 + } + ), + (2, Input::Position(0)), + (3, Input::Position(1)), + ] + ); + } +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs new file mode 100644 index 000000000..0b8fd9c6d --- /dev/null +++ b/crates/victory-shader/src/ir.rs @@ -0,0 +1,1791 @@ +//! One-to-one SSA form of a native program (decision 0003, step 1). +//! +//! Every machine instruction becomes one [`Inst`], except scheduling-only +//! ones (`s_nop`, `s_waitcnt*`, `s_inst_prefetch`...), which are dropped. +//! Each register dword is a variable: a read names the [`Value`] it sees, a +//! write defines a new one, and [`Phi`]s merge values where control flow +//! joins. Nothing is raised: an instruction keeps its opcode and decoded +//! fields, so its exact semantics stay with it. +//! +//! Implicit operands are explicit: SCC, M0, and EXEC, which every vector +//! instruction reads. A write to a VGPR also reads the register's old value, +//! because lanes disabled in EXEC keep it. +//! +//! M0-relative VGPR access (`v_movrels/d/sd_b32`, `v_swaprel_b32`) names its +//! operand's whole possible range: from the encoded register up to the +//! program's VGPR count, all read (and all written, for a destination). + +use crate::ShaderError; +use crate::gfx10::{self, Fields, Flow, Instruction, Operand}; + +/// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs, +/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from +/// [`PARKED`] up are scalars the compiler parked in VGPR lanes (`unspill`): +/// no machine instruction names them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Reg { + S(u8), + Scc, + V(u8), +} + +pub const VCC: u8 = 106; +pub const M0: u8 = 124; +pub const EXEC: u8 = 126; +/// The first scalar code past the machine's (0-127): see [`Reg`]. +pub const PARKED: u8 = 128; + +/// An SSA value: the content of one register dword (SCC: one bit). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Value(pub u32); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Program { + pub wave64: bool, + /// VGPRs v0 up to this exist; bounds M0-relative access. + pub vgprs: u16, + /// In code order, then copies made to give every loop one entry; block 0 + /// is the entry. + pub blocks: Vec<Block>, + /// Registers read before any write, with their value on entry: what the + /// hardware or a called fetch routine set up (user SGPRs, system values, + /// vertex inputs). + pub inputs: Vec<(Reg, Value)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Block { + /// Byte offset of the block's first machine instruction (shared by a + /// block and its copies). + pub offset: usize, + pub preds: Vec<usize>, + pub phis: Vec<Phi>, + pub insts: Vec<Inst>, + pub exit: Exit, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Exit { + Jump(usize), + /// `s_cbranch_*`, the block's last instruction. + Branch { + taken: usize, + not_taken: usize, + }, + /// `s_endpgm` and its variants. + End, + /// `s_setpc_b64` to an address held in registers, e.g. the handover to + /// the next half of a merged hardware stage. + Indirect, +} + +impl Exit { + pub fn successors(&self) -> Vec<usize> { + match *self { + Exit::Jump(b) => vec![b], + Exit::Branch { taken, not_taken } => vec![taken, not_taken], + Exit::End | Exit::Indirect => vec![], + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Phi { + pub reg: Reg, + pub value: Value, + /// One per predecessor, in [`Block::preds`] order. + pub args: Vec<Value>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Inst { + pub machine: Instruction, + pub fields: Fields, + /// Every register dword read, with the value it holds. + pub reads: Vec<(Reg, Value)>, + /// Every register dword written, with the value it receives. + pub writes: Vec<(Reg, Value)>, +} + +impl Inst { + pub fn name(&self) -> &'static str { + self.machine.name().unwrap_or("") + } + + /// The value `reg` holds when this instruction reads it. + pub fn read(&self, reg: Reg) -> Option<Value> { + self.reads.iter().find(|r| r.0 == reg).map(|r| r.1) + } + + /// The value this instruction writes to `reg`. + pub fn write(&self, reg: Reg) -> Option<Value> { + self.writes.iter().find(|w| w.0 == reg).map(|w| w.1) + } +} + +/// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR +/// count. Fails on instructions the IR cannot express yet +/// ([`ShaderError::Unsupported`]). +pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderError> { + let mut list = gfx10::decode(code)?; + let lanes = 1 + u8::from(wave64); + let isa = |offset, reason| ShaderError::Isa { offset, reason }; + + let mut flows = Vec::with_capacity(list.len()); + let mut leaders = vec![0]; + for (i, inst) in list.iter().enumerate() { + let flow = gfx10::control(inst, code.len(), |at| { + list[..list.partition_point(|i| i.offset < at)].last() + })?; + if let Flow::Jump(t) | Flow::Branch(t) = flow { + leaders.push(t); + } + if flow != Flow::Next + && let Some(next) = list.get(i + 1) + { + leaders.push(next.offset); + } + flows.push(flow); + } + leaders.sort_unstable(); + leaders.dedup(); + let parked = unspill(&mut list, &leaders, wave64, lanes, vgprs); + let block_at = |offset: usize| { + leaders + .binary_search(&offset) + .map_err(|_| isa(offset, "jump into a block")) + }; + + let mut blocks: Vec<Block> = leaders + .iter() + .map(|&offset| Block { + offset, + preds: Vec::new(), + phis: Vec::new(), + insts: Vec::new(), + exit: Exit::End, + }) + .collect(); + let next_offsets: Vec<Option<usize>> = (0..list.len()) + .map(|i| list.get(i + 1).map(|n| n.offset)) + .collect(); + for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() { + let b = leaders.partition_point(|&l| l <= machine.offset) - 1; + let name = machine.name().ok_or(ShaderError::Unsupported { + offset: machine.offset, + what: "unknown opcode", + })?; + let mut fields = machine.fields(wave64); + // A move to or from a scalar parked in a VGPR lane (`unspill`): its register + // codes may be ones the machine word cannot hold. + if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0) + && let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields + && let Some(Operand::Scalar { code: from, .. }) = src.first_mut() + { + (*to, *from) = (parked[k].1, parked[k].2); + } + let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?); + let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok()); + if ends { + blocks[b].exit = match flow { + Flow::Next => Exit::Jump(fallthrough()?), + Flow::Jump(t) => Exit::Jump(block_at(t)?), + Flow::Branch(t) => Exit::Branch { + taken: block_at(t)?, + not_taken: fallthrough()?, + }, + Flow::Stop if name == "s_setpc_b64" => Exit::Indirect, + Flow::Stop => Exit::End, + }; + } + if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { + // Lanes disabled in EXEC keep the old value. + for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) { + if !reads.contains(w) { + reads.push(*w); + } + } + let unset = |regs: Vec<Reg>| regs.into_iter().map(|r| (r, NONE)).collect(); + blocks[b].insts.push(Inst { + machine, + fields, + reads: unset(reads), + writes: unset(writes), + }); + } + } + link(&mut blocks); + if !blocks[0].preds.is_empty() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a branch to the program entry", + }); + } + split_irreducible(&mut blocks)?; + + Ok(rename(blocks, wave64, vgprs)) +} + +/// Scalar registers the compiler parked in lanes of a VGPR, as scalar moves. +/// +/// When it runs out of SGPRs the console compiler saves one in a lane of a +/// spare VGPR (`v_writelane_b32 vN, sX, K`) and takes it back later +/// (`v_readlane_b32 sX, vN, K`). A VGPR whose every use in the program is one +/// of those two forms with a constant lane is such a store: lane K of it is a +/// scalar register by another name. Each (VGPR, lane) gets a register code +/// the program does not use (the trap temporaries first, then SGPRs it never +/// names, then codes from [`PARKED`] up, which no machine word can hold), and +/// the save and the restore become `s_mov_b32` to and from it. Returns those +/// moves (index in `list`, destination code, source code) in order, for +/// `build` to put the codes into the decoded fields. They are then copies for +/// every later stage: a parked descriptor is traced to its load, and nothing +/// is left of a cross-lane operation, which a console wave run as two host +/// waves could not do where not every lane runs (the lane may be in the other +/// wave, or not running). +/// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit +/// address) moves as a pair (`s_mov_b64`) when every save and every restore +/// of the two lanes come together, so a parked lane mask comes back as the +/// mask it is; otherwise its halves come back as two scalars. +fn unspill( + list: &mut [gfx10::Instruction], + leaders: &[usize], + wave64: bool, + lanes: u8, + vgprs: u16, +) -> Vec<(usize, u8, u8)> { + /// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K). + fn parked(inst: &gfx10::Instruction, fields: &Fields) -> 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() { + return None; + } + let lane = |op: &Operand| match *op { + Operand::Const(c @ 128..=191) => Some(u32::from(c) - 128), + _ => None, + }; + match (inst.name()?, v.dst?, v.src.as_slice()) { + ("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 => { + Some((false, *reg, code, lane(k)?)) + } + _ => None, + } + } + // VGPRs used by parking alone, the scalar codes the program uses, and + // per instruction the scalar codes it writes. + let mut stores = [false; 256]; + let mut other = [false; 256]; + let mut used = [false; 128]; + let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len()); + let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len()); + let mut read: Vec<Vec<u8>> = Vec::with_capacity(list.len()); + for inst in list.iter() { + 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 ® in &writes { + if let Reg::S(c) = reg { + codes.push(c); + } + } + 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, + Reg::V(r) => other[usize::from(r)] = true, + Reg::Scc => {} + } + } + } + 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)]) { + *park = None; + } + let _ = i; + } + if parks.iter().all(Option::is_none) { + return Vec::new(); + } + let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); + // Lane pairs (register, lower lane) that always move together: each + // save of the lower lane is followed, in the same block and before its + // register changes, by the save of the next register into the next + // lane; each restore of the lower lane is followed at once by the + // restore of the next lane into the next register. + // The second save may come any number of instructions after the first (the + // compiler puts loads and constants between the two: five instructions later + // in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask + // is one dword, and a pair move of it with its neighbour would hide it. + let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect(); + slots.sort_unstable(); + slots.dedup(); + // instruction -> the instruction that completes its pair + let partner = |i: usize| -> Option<usize> { + let (save, reg, code, lane) = parks[i]?; + if save { + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((true, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None + } else { + // 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)) { + continue; + } + let lower: Vec<usize> = (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<Option<usize>> = lower.iter().map(|&i| partner(i)).collect(); + let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect(); + distinct.sort_unstable(); + distinct.dedup(); + if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { + pairs.push((reg, lane)); + } + } + // Codes for the parked scalars: the trap temporaries (108..=123), then + // user SGPRs the program never names, from the top, then the codes past + // the machine's (`PARKED`..=254; 255 stays unused so that the code after a + // parked one always exists). A material resolve program parks up to 63 + // scalars and leaves about 20 machine codes unused. + let past = usize::from(PARKED); + let mut free = [false; 256]; + for c in (0..105).chain(108..=123) { + free[c] = !used[c]; + } + 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]); + // 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); + codes.push(((reg, lane), c as u8)); + codes.push(((reg, lane + 1), c as u8 + 1)); + } + for &slot in &slots { + 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 { + return Vec::new(); + }; + free[c] = false; + codes.push((slot, c as u8)); + } + let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1); + let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { + list[i] = gfx10::Instruction { + offset: list[i].offset, + encoding, + opcode, + words: vec![word], + }; + }; + // `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); + 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() }; + if pairs.contains(&(reg, lane)) { + 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) }; + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((at, Some((true, dst, src)))); + edits.push((gone, None)); + } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + // the upper half of a pair: moved with the lower + } else { + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((i, Some((false, dst, src)))); + } + } + let mut moves = Vec::new(); + 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)); + moves.push((i, dst, src)); + } + None => put(list, i, gfx10::Encoding::Sopp, 0, NOP), + } + } + moves.sort_unstable(); + moves +} + +/// Rename register reads and writes after changing edges in a reducible graph. +fn rename(mut blocks: Vec<Block>, wave64: bool, vgprs: u16) -> Program { + let order = reverse_postorder(&blocks); + let (live_in, live_out) = liveness(&blocks, &order); + let mut values = 0u32; + let mut new_value = || { + values += 1; + Value(values - 1) + }; + let mut inputs = Vec::new(); + let mut outs: Vec<Vec<(Reg, Value)>> = vec![Vec::new(); blocks.len()]; + let mut current = [NONE; REGS]; + for &b in &order { + current.fill(NONE); + let block = &mut blocks[b]; + for reg in members(&live_in[b]) { + current[index(reg)] = match block.preds[..] { + [] => { + let v = new_value(); + inputs.push((reg, v)); + v + } + // A single predecessor comes earlier in reverse postorder. + [p] => lookup(&outs[p], reg), + _ => { + let value = new_value(); + block.phis.push(Phi { + reg, + value, + args: Vec::new(), + }); + value + } + }; + } + for inst in &mut block.insts { + for (reg, v) in &mut inst.reads { + *v = current[index(*reg)]; + debug_assert_ne!(*v, NONE, "{reg:?} read at {:#x}", inst.machine.offset); + } + for (reg, v) in &mut inst.writes { + *v = new_value(); + current[index(*reg)] = *v; + } + } + outs[b] = members(&live_out[b]) + .map(|reg| (reg, current[index(reg)])) + .collect(); + } + for block in &mut blocks { + for phi in &mut block.phis { + phi.args = block + .preds + .iter() + .map(|&p| lookup(&outs[p], phi.reg)) + .collect(); + debug_assert!(!phi.args.contains(&NONE), "{phi:?}"); + } + } + remove_trivial_phis(&mut blocks, values); + Program { + wave64, + vgprs, + blocks, + inputs, + } +} + +/// Duplicate a join for each proven (predecessor, join, destination) edge. +/// The instructions still execute on that path and define fresh SSA values. +pub(crate) fn thread_edges( + p: &Program, + edges: &[(usize, usize, usize)], +) -> Result<Program, ShaderError> { + let mut blocks = p.blocks.clone(); + for block in &mut blocks { + block.phis.clear(); + } + for &(pred, join, dest) in edges { + let mut copy = blocks[join].clone(); + copy.exit = Exit::Jump(dest); + let target = blocks.len(); + match &mut blocks[pred].exit { + Exit::Jump(t) => *t = target, + Exit::Branch { taken, not_taken } => { + if *taken == join { + *taken = target; + } + if *not_taken == join { + *not_taken = target; + } + } + _ => unreachable!("threading an incoming edge"), + } + blocks.push(copy); + } + link(&mut blocks); + split_irreducible(&mut blocks)?; + Ok(rename(blocks, p.wave64, p.vgprs)) +} + +/// The program without its early-outs: an `s_cbranch_execz` to a block that +/// only ends the program (`if (!inBounds) return;`, the outermost branch of +/// most compute programs) is left out, so the lanes that would have left +/// walk the body with EXEC clear. Vector instructions and every effect are +/// masked by EXEC already, as on the console, where the branch is taken +/// only when no lane of the wave is left; scalar code has no effects. The +/// body is then code every lane runs, which a console wave run as two host +/// waves needs for the barriers of its exchanges and LDS accesses. +/// `None` if the program has no such branch. +pub(crate) fn without_early_outs(p: &Program) -> Option<Program> { + let ends = |b: usize| { + p.blocks[b].exit == Exit::End + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + }; + let mut blocks = p.blocks.clone(); + let mut any = false; + for block in &mut blocks { + 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") { + block.insts.pop(); + block.exit = Exit::Jump(not_taken); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// As [`without_early_outs`], and also without the branches that only skip a +/// region when no lane is left for it: an `s_cbranch_execz` whose target is +/// where the skipped code ends up anyway (`if (c) { ... }` with nothing +/// else leaving the region). Every lane then walks the region with EXEC +/// clear for those that would have skipped it, and LDS accesses and +/// exchanges inside it are in code every lane runs. +/// The console takes such a branch only when no lane of the wave is left, +/// and then its scalar code does not run: a branch is kept if the code +/// after it could see that (a scalar register or SCC that the region +/// changes and the join merges with the value from before; EXEC aside, +/// which is empty either way). `None` if nothing changes. +/// +/// `deep` looks closer at what the code after the branch can see. A scalar the region moves +/// away and back (the compiler parks scalars in VGPR lanes around a branch and takes them +/// back before the join, `unspill`) is the value it copies; a join nothing reads shows no +/// one the difference (a restore of EXEC that the next one overwrites reads nothing); and +/// 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. +pub(crate) fn without_skips(p: &Program, deep: bool) -> Option<Program> { + 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 { .. })) + }; + // 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. + let mut copy: std::collections::HashMap<Value, Value> = Default::default(); + // Values something reads, directly or through joins. A scalar operation none of whose + // results is read reads nothing either (the compiler restores EXEC from a saved mask + // and overwrites it at once where two branches end together). + let mut live: std::collections::HashSet<Value> = Default::default(); + let idle = |inst: &Inst, live: &std::collections::HashSet<Value>| { + let name = inst.name(); + matches!(inst.fields, crate::gfx10::Fields::Sop { .. }) + && !(name.starts_with("s_setpc") + || name.starts_with("s_swappc") + || name.starts_with("s_call") + || name.starts_with("s_rfe") + || name.starts_with("s_movrel") + || name.starts_with("s_subvector")) + && inst.writes.iter().all(|w| !live.contains(&w.1)) + }; + for block in &p.blocks { + 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(_))) + { + copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1))); + } + } + } + let mut changed = true; + while changed { + changed = false; + for block in &p.blocks { + for inst in &block.insts { + if !idle(inst, &live) { + for r in &inst.reads { + changed |= live.insert(r.1); + } + } + } + for phi in &block.phis { + if live.contains(&phi.value) { + for &a in &phi.args { + changed |= live.insert(a); + } + } + } + } + } + let root = |mut v: Value| { + while deep && let Some(&c) = copy.get(&v) { + v = c; + } + v + }; + // The region a skip of `b` to `target` leaves out, if it is a pure skip. + let skipped = |b: usize, target: usize, first: usize| -> Option<Vec<bool>> { + let mut inside = vec![false; n]; + let mut stack = vec![first]; + while let Some(x) = stack.pop() { + if x == target || inside[x] { + continue; + } + if x == b { + return None; // a loop back to the branch + } + inside[x] = true; + match p.blocks[x].exit { + Exit::End | Exit::Indirect => return None, + exit => stack.extend(exit.successors()), + } + } + // entered only through the branch + for x in (0..n).filter(|&x| inside[x]) { + if p.blocks[x].preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + } + // the join sees no scalar the region changed + let join = &p.blocks[target]; + for phi in &join.phis { + let scalar = match phi.reg { + Reg::S(c) => c != 126 && c != 127, + Reg::Scc => true, + Reg::V(_) => false, + }; + // (a join nothing reads shows no one the difference) + if !scalar || deep && !live.contains(&phi.value) { + continue; + } + let before: Vec<Value> = + 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; + } + } + // Other ways into the join than the branch and the region (an inner branch that ends + // together with an outer one) change nothing in that: the lanes that would have + // skipped arrive from the region instead, with the same scalars. + if !deep && join.preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + Some(inside) + }; + let mut blocks = p.blocks.clone(); + let mut any = false; + for b in 0..n { + 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") { + continue; + } + if ends(taken) || skipped(b, taken, not_taken).is_some() { + blocks[b].insts.pop(); + blocks[b].exit = Exit::Jump(not_taken); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// Placeholder before renaming. +const NONE: Value = Value(u32::MAX); +/// Scalar codes 0-255 (from [`PARKED`] up: parked scalars), SCC, VGPRs 0-255. +const REGS: usize = 256 + 1 + 256; +type RegSet = [u64; REGS.div_ceil(64)]; + +fn index(reg: Reg) -> usize { + match reg { + Reg::S(c) => usize::from(c), + Reg::Scc => 256, + Reg::V(r) => 257 + usize::from(r), + } +} + +fn reg_at(i: usize) -> Reg { + match i { + 0..256 => Reg::S(i as u8), + 256 => Reg::Scc, + _ => Reg::V((i - 257) as u8), + } +} + +fn insert(set: &mut RegSet, reg: Reg) { + let i = index(reg); + set[i / 64] |= 1 << (i % 64); +} + +fn contains(set: &RegSet, reg: Reg) -> bool { + let i = index(reg); + set[i / 64] >> (i % 64) & 1 != 0 +} + +/// In [`Reg`] order, which is also index order. +fn members(set: &RegSet) -> impl Iterator<Item = Reg> + '_ { + (0..REGS) + .filter(|&i| set[i / 64] >> (i % 64) & 1 != 0) + .map(reg_at) +} + +/// `outs` is sorted by register, and holds every register live out. +fn lookup(outs: &[(Reg, Value)], reg: Reg) -> Value { + outs.binary_search_by_key(®, |&(r, _)| r) + .map_or(NONE, |i| outs[i].1) +} + +pub(crate) fn reverse_postorder(blocks: &[Block]) -> Vec<usize> { + let mut seen = vec![false; blocks.len()]; + let mut post = Vec::with_capacity(blocks.len()); + let mut stack = vec![(0, 0)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, i) = *top; + top.1 += 1; + match blocks[b].exit.successors().get(i) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + post +} + +/// Recomputes every block's predecessors from the exits. +fn link(blocks: &mut [Block]) { + for block in blocks.iter_mut() { + block.preds.clear(); + } + for b in 0..blocks.len() { + for s in blocks[b].exit.successors() { + blocks[s].preds.push(b); + } + } +} + +/// An edge to an earlier block in reverse postorder whose target does not +/// dominate its source, if any: there the control flow is irreducible. +/// `index` is each block's position in `order`. +pub(crate) fn irreducible_edge( + blocks: &[Block], + order: &[usize], + index: &[usize], +) -> Option<(usize, usize)> { + let &entry = order.first()?; + let idom = idoms(blocks, order, index); + for &b in order { + for s in blocks[b].exit.successors() { + if index[s] > index[b] { + continue; + } + let mut d = b; + while d != s && d != entry { + d = idom[d]; + } + if d != s { + return Some((b, s)); + } + } + } + None +} + +/// Each block's immediate dominator (the entry's is itself, unreachable +/// blocks' `usize::MAX`); `order` is reverse postorder, `index` each +/// block's position in it. +pub(crate) fn idoms(blocks: &[Block], order: &[usize], index: &[usize]) -> Vec<usize> { + let mut idom = vec![usize::MAX; blocks.len()]; + let Some(&entry) = order.first() else { + return idom; + }; + idom[entry] = entry; + let intersect = |idom: &[usize], mut a: usize, mut b: usize| { + while a != b { + while index[a] > index[b] { + a = idom[a]; + } + while index[b] > index[a] { + b = idom[b]; + } + } + a + }; + let mut changed = true; + while changed { + changed = false; + for &b in &order[1..] { + let mut new = usize::MAX; + for &q in blocks[b].preds.iter().filter(|&&q| idom[q] != usize::MAX) { + new = if new == usize::MAX { + q + } else { + intersect(&idom, q, new) + }; + } + if idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + idom +} + +/// Node splitting, before SSA. While a loop is entered at several blocks +/// (a compiler-rotated loop whose peeled first test jumps into its body), +/// the entry first in reverse postorder stays the header, and another +/// entry's outside predecessors move to a copy of everything that entry +/// reaches in the loop before the header. The copies run the same +/// instructions, so behaviour is unchanged. +fn split_irreducible(blocks: &mut Vec<Block>) -> Result<(), ShaderError> { + let limit = 4 * blocks.len() + 64; + loop { + let order = reverse_postorder(blocks); + let mut index = vec![usize::MAX; blocks.len()]; + for (i, &b) in order.iter().enumerate() { + index[b] = i; + } + let Some((from, _)) = irreducible_edge(blocks, &order, &index) else { + return Ok(()); + }; + let found = multi_entry_loop(blocks, &vec![true; blocks.len()]); + let Some((region, mut entries)) = found.filter(|_| blocks.len() < limit) else { + return Err(ShaderError::Unsupported { + offset: blocks[from].offset, + what: "irreducible control flow", + }); + }; + entries.sort_by_key(|&e| index[e]); + let (header, entry) = (entries[0], entries[1]); + + // What `entry` reaches in the loop before the header, and its copies. + let mut copy = vec![usize::MAX; blocks.len()]; + let mut copied = Vec::new(); + let mut stack = vec![entry]; + while let Some(b) = stack.pop() { + if copy[b] != usize::MAX { + continue; + } + copy[b] = blocks.len() + copied.len(); + copied.push(b); + for s in blocks[b].exit.successors() { + if region[s] && s != header { + stack.push(s); + } + } + } + let retarget = |exit: &mut Exit, to: &dyn Fn(usize) -> usize| match exit { + Exit::Jump(s) => *s = to(*s), + Exit::Branch { taken, not_taken } => { + *taken = to(*taken); + *not_taken = to(*not_taken); + } + Exit::End | Exit::Indirect => {} + }; + for &b in &copied { + let mut block = blocks[b].clone(); + retarget(&mut block.exit, &|s| { + if copy[s] == usize::MAX { s } else { copy[s] } + }); + blocks.push(block); + } + let outside: Vec<usize> = blocks[entry] + .preds + .iter() + .copied() + .filter(|&p| !region[p]) + .collect(); + for p in outside { + retarget(&mut blocks[p].exit, &|s| { + if s == entry { copy[entry] } else { s } + }); + } + link(blocks); + } +} + +/// A loop among the `inside` blocks entered at more than one block, with +/// its entries. Loops nested in a single-entry loop are searched with its +/// header removed, so one is found whenever the control flow is irreducible. +fn multi_entry_loop(blocks: &[Block], inside: &[bool]) -> Option<(Vec<bool>, Vec<usize>)> { + let reach = |from: usize, forward: bool| { + let mut seen = vec![false; blocks.len()]; + let mut stack = vec![from]; + while let Some(b) = stack.pop() { + let next = if forward { + blocks[b].exit.successors() + } else { + blocks[b].preds.clone() + }; + for n in next { + if inside[n] && !seen[n] { + seen[n] = true; + stack.push(n); + } + } + } + seen + }; + let mut done = vec![false; blocks.len()]; + for v in (0..blocks.len()).filter(|&v| inside[v]) { + if done[v] { + continue; + } + // Blocks on a cycle through `v`; `v` itself only if there is one. + let (ahead, behind) = (reach(v, true), reach(v, false)); + let region: Vec<bool> = ahead.iter().zip(&behind).map(|(a, b)| a & b).collect(); + if !region[v] { + continue; + } + let members = (0..blocks.len()).filter(|&b| region[b]); + for b in members.clone() { + done[b] = true; + } + let entries: Vec<usize> = members + .filter(|&b| blocks[b].preds.iter().any(|&p| !region[p])) + .collect(); + match entries[..] { + [] => {} + [header] => { + let mut nested = region; + nested[header] = false; + if let Some(found) = multi_entry_loop(blocks, &nested) { + return Some(found); + } + } + _ => return Some((region, entries)), + } + } + None +} + +/// Registers live into and out of each block. +fn liveness(blocks: &[Block], order: &[usize]) -> (Vec<RegSet>, Vec<RegSet>) { + let empty = [0; REGS.div_ceil(64)]; + let mut uses = vec![empty; blocks.len()]; + let mut defs = vec![empty; blocks.len()]; + for (b, block) in blocks.iter().enumerate() { + for inst in &block.insts { + for &(reg, _) in &inst.reads { + if !contains(&defs[b], reg) { + insert(&mut uses[b], reg); + } + } + for &(reg, _) in &inst.writes { + insert(&mut defs[b], reg); + } + } + } + let mut live_in = vec![empty; blocks.len()]; + let mut live_out = vec![empty; blocks.len()]; + let mut changed = true; + while changed { + changed = false; + for &b in order.iter().rev() { + let mut out = empty; + for s in blocks[b].exit.successors() { + for (o, i) in out.iter_mut().zip(&live_in[s]) { + *o |= i; + } + } + let mut inn = empty; + for w in 0..inn.len() { + inn[w] = uses[b][w] | out[w] & !defs[b][w]; + } + if inn != live_in[b] || out != live_out[b] { + (live_in[b], live_out[b]) = (inn, out); + changed = true; + } + } + } + (live_in, live_out) +} + +/// Phis are placed for every live register at every join; those whose +/// arguments are all one value (or the phi itself) are replaced by it. +fn remove_trivial_phis(blocks: &mut [Block], values: u32) { + let mut replaced: Vec<Value> = (0..values).map(Value).collect(); + let find = |replaced: &[Value], mut v: Value| { + while replaced[v.0 as usize] != v { + v = replaced[v.0 as usize]; + } + v + }; + let mut changed = true; + while changed { + changed = false; + for block in blocks.iter_mut() { + block.phis.retain(|phi| { + let mut only = None; + for &a in &phi.args { + let a = find(&replaced, a); + if a == phi.value || Some(a) == only { + continue; + } + if only.is_some() { + return true; + } + only = Some(a); + } + let Some(v) = only else { return true }; + replaced[phi.value.0 as usize] = v; + changed = true; + false + }); + } + } + for block in blocks { + for phi in &mut block.phis { + for a in &mut phi.args { + *a = find(&replaced, *a); + } + } + for inst in &mut block.insts { + for (_, v) in &mut inst.reads { + *v = find(&replaced, *v); + } + } + } +} + +/// Scheduling hints, performance counters and tracing: no effect on results. +const DROPPED: &[&str] = &[ + "s_nop", + "s_waitcnt", + "s_waitcnt_vscnt", + "s_waitcnt_vmcnt", + "s_waitcnt_expcnt", + "s_waitcnt_lgkmcnt", + "s_waitcnt_depctr", + "s_wait_idle", + "s_inst_prefetch", + "s_clause", + "s_setprio", + "s_sleep", + "s_ttracedata", + "s_ttracedata_imm", + "s_incperflevel", + "s_decperflevel", + "v_nop", + "v_pipeflush", + "v_clrexcp", +]; + +/// Registers read, registers written. +type Effects = (Vec<Reg>, Vec<Reg>); + +/// The registers `inst` of `p` reads as operands: its reads without the old +/// value of a VGPR it only writes. +pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec<Reg> { + let lanes = 1 + u8::from(p.wave64); + effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs) + .ok() + .flatten() + .map_or_else(Vec::new, |e| e.0) +} + +/// Registers an instruction reads and writes, one per dword, or `None` if +/// the IR drops it. +fn effects( + inst: &Instruction, + fields: &Fields, + name: &'static str, + lanes: u8, + vgprs: u16, +) -> Result<Option<Effects>, ShaderError> { + if DROPPED.contains(&name) { + return Ok(None); + } + let unsupported = || ShaderError::Unsupported { + offset: inst.offset, + what: name, + }; + 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>| { + add_regs(op, lanes, out).map_err(|_| ShaderError::Isa { + offset: inst.offset, + reason: "register range out of bounds", + }) + }; + let vector = !matches!( + fields, + Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. } + ); + match fields { + Fields::Sop { dst, src, .. } => { + if name.starts_with("s_movrel") + || name.starts_with("s_subvector_loop") + || matches!(name, "s_call_b64" | "s_rfe_b64") + { + return Err(unsupported()); + } + for s in src { + regs(s, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + // These change (or may keep) the destination's old value. + if name.starts_with("s_bitset") + || name.starts_with("s_cmov") + || matches!(name, "s_addk_i32" | "s_mulk_i32") + { + regs(d, &mut r)?; + } + } + if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32") + || name.starts_with("s_cselect_") + || name.starts_with("s_cmov_") + { + 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); + } + } + Fields::Sopp { .. } => match name { + "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)), + "s_endpgm" + | "s_endpgm_saved" + | "s_endpgm_ordered_ps_done" + | "s_code_end" + | "s_branch" + | "s_barrier" + | "s_icache_inv" + | "s_wakeup" + | "s_round_mode" + | "s_denorm_mode" => {} + _ => return Err(unsupported()), + }, + Fields::Smem { + data, + base, + soffset, + .. + } => match name { + "s_memtime" | "s_memrealtime" | "s_get_waveid_in_workgroup" => { + regs(data.as_ref().ok_or_else(unsupported)?, &mut w)?; + } + "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => {} + _ if name.contains("_load_") || name.contains("_store_") => { + regs(base, &mut r)?; + regs(soffset, &mut r)?; + let data = data.as_ref().ok_or_else(unsupported)?; + regs( + data, + if name.contains("_load_") { + &mut w + } else { + &mut r + }, + )?; + } + _ => return Err(unsupported()), + }, + Fields::Valu(v) => { + let (src_indexed, dst_indexed) = match name { + "v_movrels_b32" => (true, false), + "v_movreld_b32" => (false, true), + "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" => (true, true), + _ => (false, false), + }; + // v[reg + M0] for any M0 that stays inside the program's VGPRs. + let indexed = |op: &Operand, out: &mut Vec<Reg>| match *op { + Operand::Vector { reg, .. } if u16::from(reg) < vgprs => { + out.extend((u16::from(reg)..vgprs).map(|r| Reg::V(r as u8))); + Ok(()) + } + _ => Err(ShaderError::Isa { + offset: inst.offset, + reason: "relative VGPR base outside the program's VGPRs", + }), + }; + for (i, s) in v.src.iter().enumerate() { + if i == 0 && src_indexed { + indexed(s, &mut r)?; + } else { + regs(s, &mut r)?; + } + } + // GFX10 compares into EXEC write nothing else. + if name.starts_with("v_cmpx") { + w.extend(mask(EXEC)); + } else if let Some(d) = &v.dst { + if dst_indexed { + indexed(d, &mut w)?; + } else { + regs(d, &mut w)?; + } + } + if let Some(c) = &v.carry { + regs(c, &mut w)?; + } + match name { + "v_swap_b32" => { + regs(&v.src[0], &mut w)?; + if let Some(d) = &v.dst { + regs(d, &mut r)?; + } + } + "v_swaprel_b32" => { + indexed(&v.src[0], &mut w)?; + if let Some(d) = &v.dst { + indexed(d, &mut r)?; + } + } + "v_div_fmas_f32" | "v_div_fmas_f64" => r.extend(mask(VCC)), + _ => {} + } + if name.starts_with("v_interp_") || src_indexed || dst_indexed { + r.push(Reg::S(M0)); + } + } + Fields::Vintrp { dst, src, .. } => { + regs(src, &mut r)?; + r.push(Reg::S(M0)); + regs(dst, &mut w)?; + } + Fields::Ds { + dst, + addr, + data, + gds, + .. + } => { + for o in addr.iter().chain(data) { + regs(o, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + } + if *gds + || name.starts_with("ds_gws") + || name.contains("addtid") + || matches!(name, "ds_ordered_count" | "ds_append" | "ds_consume") + { + r.push(Reg::S(M0)); + } + } + Fields::Buffer { + data, + addr, + rsrc, + soffset, + offen, + idxen, + lds, + cache, + .. + } => { + if *offen || *idxen { + regs(addr, &mut r)?; + } + regs(rsrc, &mut r)?; + regs(soffset, &mut r)?; + if *lds { + r.push(Reg::S(M0)); + } + if let Some(d) = data { + if name.contains("_load_") { + if !lds { + regs(d, &mut w)?; + } + } else if name.contains("_store_") { + regs(d, &mut r)?; + } else if name.contains("_atomic_") { + regs(d, &mut r)?; + if cache.glc { + regs(&atomic_result(d, name), &mut w)?; + } + } else { + return Err(unsupported()); + } + } + } + Fields::Image { + data, + addr, + rsrc, + sampler, + cache, + .. + } => { + for a in addr.iter().chain([rsrc]).chain(sampler) { + regs(a, &mut r)?; + } + if name.contains("_store") { + regs(data, &mut r)?; + } else if name.contains("_atomic_") { + regs(data, &mut r)?; + if cache.glc { + regs(&atomic_result(data, name), &mut w)?; + } + } else { + regs(data, &mut w)?; + } + } + Fields::Flat { + dst, + addr, + data, + saddr, + .. + } => { + for o in [addr, data, saddr].into_iter().flatten() { + regs(o, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + } + } + Fields::Exp { src, .. } => { + for s in src.iter().flatten() { + regs(s, &mut r)?; + } + } + } + if vector { + r.extend(mask(EXEC)); + } + let mut seen = Vec::with_capacity(r.len()); + r.retain(|reg| { + let new = !seen.contains(reg); + seen.push(*reg); + new + }); + Ok(Some((r, w))) +} + +/// Scalar ALU opcodes that set SCC (carry, overflow, comparison, or "result +/// is not zero"). +fn writes_scc(encoding: gfx10::Encoding, name: &str) -> bool { + use gfx10::Encoding::*; + match encoding { + Sopc => true, + Sopk => name.starts_with("s_cmpk_") || name == "s_addk_i32", + _ => { + let stem = name.split('_').nth(1).unwrap_or(""); + name.contains("saveexec") + || name.contains("wrexec") + || matches!( + stem, + "add" + | "sub" + | "addc" + | "subb" + | "min" + | "max" + | "and" + | "or" + | "xor" + | "andn2" + | "orn2" + | "nand" + | "nor" + | "xnor" + | "lshl" + | "lshr" + | "ashr" + | "bfe" + | "absdiff" + | "lshl1" + | "lshl2" + | "lshl3" + | "lshl4" + | "not" + | "wqm" + | "bcnt0" + | "bcnt1" + | "quadmask" + | "abs" + ) + } + } +} + +/// What an atomic with `glc` returns: the old value (for compare-and-swap, +/// half the data operand). +fn atomic_result(data: &Operand, name: &str) -> Operand { + match *data { + Operand::Vector { reg, dwords } if name.contains("cmpswap") => Operand::Vector { + reg, + dwords: dwords / 2, + }, + op => op, + } +} + +/// 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>) -> Result<(), ()> { + match *op { + Operand::Scalar { code, .. } if code == gfx10::NULL => {} + Operand::Scalar { code, dwords } => { + let end = u16::from(code) + u16::from(dwords); + // A machine operand ends within the machine's codes, a parked + // scalar (`unspill`) within those past them. + let limit = if code < PARKED { 128 } else { 256 }; + if end > limit { + return Err(()); + } + 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))); + } + 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(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn build_words(words: &[u32], wave64: bool) -> Program { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + build(&code, wave64, 256).unwrap() + } + + fn input(p: &Program, reg: Reg) -> Value { + p.inputs.iter().find(|i| i.0 == reg).expect("input").1 + } + + /// `if (v0 < s0) { ... }` whose body changes s6: `body` are its words, `after` what + /// follows the join. + fn skip(body: &[u32], after: &[u32]) -> Program { + let mut w = vec![ + 0xBE94_0306, // s_mov_b32 s20, s6 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0000 | body.len() as u32, // s_cbranch_execz past the body + ]; + w.extend_from_slice(body); + w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13] + w.extend_from_slice(after); + w.push(S_ENDPGM); + build_words(&w, true) + } + + fn skips(p: &Program) -> usize { + p.blocks + .iter() + .filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .count() + } + + #[test] + fn a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read() { + const SET: u32 = 0xBE86_0385; // s_mov_b32 s6, 5 + const USE: u32 = 0x7E02_0206; // v_mov_b32 v1, s6 + const BACK: u32 = 0xBE86_0314; // s_mov_b32 s6, s20 + const READ: u32 = 0x7E04_0206; // v_mov_b32 v2, s6 + // s6 is changed in the body and read after the join: the branch stays + let kept = skip(&[SET, USE], &[READ]); + assert_eq!(skips(&kept), 1); + assert!(without_skips(&kept, false).is_none()); + assert!(without_skips(&kept, true).is_none()); + // ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes + // back): every lane may walk the body + let back = skip(&[SET, USE, BACK], &[READ]); + assert!(without_skips(&back, false).is_none()); + assert_eq!(skips(&without_skips(&back, true).expect("left out")), 0); + // ... or not read after the join at all + let unread = skip(&[SET, USE], &[]); + assert_eq!(skips(&without_skips(&unread, false).expect("left out")), 0); + assert_eq!(skips(&without_skips(&unread, true).expect("left out")), 0); + // ... or read only by a restore of EXEC that nothing uses before the next one + // (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0) + let idle = skip(&[SET, USE], &[0xBEFE_0406, 0xBEFE_040C, 0x7E04_0200]); + assert!(without_skips(&idle, false).is_none()); + assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0); + } + + #[test] + fn joins_get_phis_only_where_values_differ() { + let code = [ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12 + 0xBE82_0380, // s_mov_b32 s2, 0 + 0x7E00_0202, // 12: v_mov_b32 v0, s2 + 0x7E02_0200, // v_mov_b32 v1, s0 + S_ENDPGM, + ]; + for wave64 in [false, true] { + let p = build_words(&code, wave64); + let [b0, b1, b2] = &p.blocks[..] else { + panic!("{:?}", p.blocks) + }; + assert_eq!( + b0.exit, + Exit::Branch { + taken: 2, + not_taken: 1 + } + ); + assert_eq!(b1.exit, Exit::Jump(2)); + assert_eq!(b2.preds, [0, 1]); + assert_eq!(b0.insts[1].read(Reg::Scc), b0.insts[0].write(Reg::Scc)); + + // s2 differs per path; s0, EXEC, v0 and v1 do not. + let [phi] = &b2.phis[..] else { + panic!("{:?}", b2.phis) + }; + assert_eq!(phi.reg, Reg::S(2)); + assert_eq!( + phi.args, + [input(&p, Reg::S(2)), b1.insts[0].write(Reg::S(2)).unwrap()] + ); + let [mov0, mov1, end] = &b2.insts[..] else { + panic!() + }; + assert_eq!(mov0.read(Reg::S(2)), Some(phi.value)); + assert_eq!(mov1.read(Reg::S(0)), Some(input(&p, Reg::S(0)))); + // The old v1 is read: lanes outside EXEC keep it. + assert_eq!(mov1.read(Reg::V(1)), Some(input(&p, Reg::V(1)))); + assert_eq!(mov1.read(Reg::S(EXEC)), Some(input(&p, Reg::S(EXEC)))); + assert_eq!(mov1.read(Reg::S(EXEC + 1)).is_some(), wave64); + assert_eq!((end.name(), b2.exit), ("s_endpgm", Exit::End)); + } + } + + #[test] + fn in_place_scalar_ops_read_their_destination() { + let p = build_words( + &[ + 0xBE8D_1D94, // s_bitset1_b32 s13, 20 + 0xB78E_0010, // s_addk_i32 s14, 0x10 + 0xBE8F_0380, // s_mov_b32 s15, 0 + S_ENDPGM, + ], + false, + ); + let [bitset, addk, mov, _] = &p.blocks[0].insts[..] else { + panic!("{:?}", p.blocks[0].insts) + }; + assert_eq!(bitset.read(Reg::S(13)), Some(input(&p, Reg::S(13)))); + assert_eq!(addk.read(Reg::S(14)), Some(input(&p, Reg::S(14)))); + assert_eq!(mov.read(Reg::S(15)), None); + } + + #[test] + fn loops_carry_values_through_phis() { + let p = build_words( + &[ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0x8000_8100, // 4: s_add_u32 s0, s0, 1 + 0xBF07_8400, // s_cmp_lg_u32 s0, 4 + 0xBF85_FFFD, // s_cbranch_scc1 -> 4 + S_ENDPGM, + ], + true, + ); + assert!(p.inputs.is_empty(), "{:?}", p.inputs); + let [b0, b1, b2] = &p.blocks[..] else { + panic!() + }; + assert_eq!(b1.preds, [0, 1]); + assert_eq!( + b1.exit, + Exit::Branch { + taken: 1, + not_taken: 2 + } + ); + let [phi] = &b1.phis[..] else { + panic!("{:?}", b1.phis) + }; + let add = &b1.insts[0]; + assert_eq!(phi.reg, Reg::S(0)); + assert_eq!( + phi.args, + [ + b0.insts[0].write(Reg::S(0)).unwrap(), + add.write(Reg::S(0)).unwrap() + ] + ); + assert_eq!(add.read(Reg::S(0)), Some(phi.value)); + assert_eq!(b1.insts[1].read(Reg::S(0)), add.write(Reg::S(0))); + assert_eq!(b2.insts[0].name(), "s_endpgm"); + } + + #[test] + fn drops_scheduling_and_follows_far_jumps() { + let p = build_words( + &[ + 0xBF80_0000, // s_nop 0 + 0xBE88_1F00, // s_getpc_b64 s[8:9] + 0x8008_FF08, + 20, // s_add_u32 s8, s8, 20 -> 8 + 20 = 28 + 0x8209_8009, // s_addc_u32 s9, s9, 0 + 0xBE80_2008, // s_setpc_b64 s[8:9] + 0xFFFF_FFFF, // not code + S_ENDPGM, + ], + false, + ); + let names: Vec<_> = p.blocks[0].insts.iter().map(Inst::name).collect(); + assert_eq!( + names, + ["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"] + ); + assert_eq!(p.blocks[0].exit, Exit::Jump(1)); + assert_eq!(p.blocks[1].offset, 28); + // s_addc_u32 reads the carry s_add_u32 left in SCC. + let i = &p.blocks[0].insts; + assert_eq!(i[2].read(Reg::Scc), i[1].write(Reg::Scc)); + } + + #[test] + fn reports_what_it_cannot_express() { + let code: Vec<u8> = [0xBE80_2E01_u32, S_ENDPGM] // s_movrels_b32 s0, s1 + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + assert_eq!( + build(&code, false, 256), + Err(ShaderError::Unsupported { + offset: 0, + what: "s_movrels_b32" + }) + ); + } + + #[test] + fn relative_vgpr_access_spans_up_to_the_vgpr_count() { + let code: Vec<u8> = [ + 0x7E04_8501_u32, // v_movreld_b32 v2, v1: v[2 + m0] = v1 + 0x7E00_8704, // v_movrels_b32 v0, v4: v0 = v[4 + m0] + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = build(&code, false, 6).unwrap(); + let [movreld, movrels, _] = &p.blocks[0].insts[..] else { + panic!() + }; + let vgprs = |regs: &[(Reg, Value)]| -> Vec<u8> { + regs.iter() + .filter_map(|r| match r.0 { + Reg::V(v) => Some(v), + _ => None, + }) + .collect() + }; + assert_eq!(vgprs(&movreld.writes), [2, 3, 4, 5]); + // v1 is the source; v2-v5 are read for the lanes and indices not written. + assert_eq!(vgprs(&movreld.reads), [1, 2, 3, 4, 5]); + assert!(movreld.read(Reg::S(M0)).is_some()); + assert_eq!(vgprs(&movrels.writes), [0]); + assert_eq!(vgprs(&movrels.reads), [4, 5, 0]); + assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4))); + assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs"); + } +} diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs new file mode 100644 index 000000000..30b195262 --- /dev/null +++ b/crates/victory-shader/src/lib.rs @@ -0,0 +1,38 @@ +//! Xbox Series shaders to host shaders. +//! +//! An Xbox Series shader is a standard DXBC container ([`dxbc`]). Its `DXIL` +//! part ([`dxil`]) may carry Xbox additions around the LLVM bitcode: an +//! `XDAT` table before it indexing blobs after it, among them `xbop` +//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use +//! console-only intrinsics, so the GFX10 code is translated in general. + +pub mod bvh; +pub mod dxbc; +pub mod dxil; +pub mod emit; +pub mod gfx10; +pub mod io; +pub mod ir; +pub mod native; +pub mod resource; +pub mod spill; +pub mod structure; + +pub use dxbc::{Container, FourCC, Part}; +pub use dxil::{DxilProgram, ShaderKind, XboxExtras}; +pub use native::{ + HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, native_programs, +}; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum ShaderError { + #[error("not a DXBC container")] + NotDxbc, + #[error("malformed shader: {0}")] + Malformed(&'static str), + #[error("GFX10 code at {offset:#x}: {reason}")] + Isa { offset: usize, reason: &'static str }, + /// Valid code the translator cannot handle yet: an opcode name or a construct. + #[error("GFX10 code at {offset:#x}: {what} is not supported")] + Unsupported { offset: usize, what: &'static str }, +} diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs new file mode 100644 index 000000000..4bdd39be6 --- /dev/null +++ b/crates/victory-shader/src/native.rs @@ -0,0 +1,1023 @@ +//! Native GFX10 programs that the console compiler stores in a `DXIL` part. +//! +//! An `XDAT` index after the program header lists blobs stored around the +//! bitcode; one or more of them hold native programs, zlib-packed (a vertex +//! shader can carry two: compiled for use with and without a geometry +//! shader). Layout as observed in shipped titles (index offsets are relative +//! to the part data): +//! +//! ```text +//! +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry: +//! u32 kind, u32 offset, u32 size +//! kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size, +//! zlib stream +//! unpacked "FSSM" u32 version (0x101), u64 payload size, payload +//! payload +0x00 u64 graphics slot count (6) +//! +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30), +//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF +//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative), +//! +0x14 u32 flags: bit 5 wave32 (else wave64) +//! +0x28 u64 root layout table, +0x30 u64 used-resource table +//! (payload-relative), +0x38 u32 and +0x3c u32 their counts +//! +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used +//! layout 20 B: u32 root type, u32 table offset (dwords), u32 user SGPRs, +//! u32 base register, u8 first user-data dword, u8 root slot, +//! u16 0 +//! used 20 B: u8 resource type, u8 root type, u16 0, u32 table offset +//! (dwords), u32 lower bound, u32 stride, u8 descriptor +//! dwords, u8 first user-data dword, u8 root slot, u8 0 +//! ``` +//! +//! Stage data follows the record; offsets from its end (E = record + 0x54): +//! +//! ```text +//! PS E+0x24 32 inputs of 8 B: u8 usage, u8 signature row, u8 channel +//! 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+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 +//! for each color format in 10 slots of 10 dwords (ZERO, 32_R, +//! 32_GR, 32_AR, FP16, UNORM16, SNORM16, UINT16, SINT16, 32_ABGR) +//! VS E+0x24 32 inputs of 5 B: u8 usage, u8 row, u8 channel mask, u8 VGPR +//! of channel 0 (channel k in VGPR + k), u8 highest channel; +//! E+0xc4 u32 count +//! E+0xc8 32 outputs of 6 B: u8 usage, u8 row, u8 parameter (`exp +//! param<n>`), u8 row again, u8 slot, u8 flags (bit 0 fp16, +//! bit 1 two fp16 values per dword); E+0x188 u32 count +//! CS E+0x24 u32 COMPUTE_PGM_RSRC2, E+0x28 u32 x3 thread-group size +//! MS E+0xc8 outputs as VS, E+0x188 count; the param byte's bit 7 marks a +//! per-primitive output (`PSG1` row); the 3 bytes more are the +//! second row of a packed pair, a slot, flags (bit 0 fp16, bit 1 +//! two fp16 elements packed) +//! E+0x18c u32 SPI_VS_OUT_CONFIG, SPI_SHADER_POS_FORMAT, +//! PA_CL_VS_OUT_CNTL, VGT_STRMOUT_CONFIG, SPI_SHADER_PGM_RSRC2_GS, +//! VGT_GS_OUT_PRIM_TYPE, VGT_GS_INSTANCE_CNT, SPI_SHADER_IDX_FORMAT +//! E+0x448 u16 thread-group size in lanes, u16 maximum vertices, +//! u16 maximum primitives, u8 user SGPRs, u8 output topology +//! (2 triangles); code follows at E+0x45c +//! record +0x4c u32 LDS bytes (`lds_byte_size`; mesh programs read it here) +//! ``` +//! +//! Rows are registers of the container's signature parts (`ISG1`, `OSG1`). +//! Merged stages keep their stage data in another layout (not read). +//! +//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped), +//! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and +//! 0x12 16-byte blobs (0x10 is the shader hash). +//! Unknown versions are rejected so a format change shows up as an error. + +use crate::ShaderError::{self, Malformed}; +use crate::dxbc::{u32_at, u64_at}; + +const XDAT_OFFSET: usize = 0x18; +const MAX_XDAT_ENTRIES: usize = 64; +const KIND_NATIVE: u32 = 0x0d; +const XBCH_VERSION: u32 = 3; +const XBCH_HEADER: usize = 0x18; +const FSSM_VERSION: u32 = 0x101; +const FSSM_HEADER: usize = 0x10; +const GRAPHICS_SLOT_COUNT: u64 = 6; +/// Where each stage's record offset sits in the FSSM payload. +const SLOTS: [(HwStage, usize); 8] = [ + (HwStage::Ls, 0x08), + (HwStage::Hs, 0x10), + (HwStage::Es, 0x18), + (HwStage::Gs, 0x20), + (HwStage::Vs, 0x28), + (HwStage::Ps, 0x30), + (HwStage::Ms, 0x48), + (HwStage::Cs, 0x60), +]; +const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF; +const RECORD_SIZE: u64 = 0x54; +const RECORD_FLAGS: usize = 0x14; +const FLAG_WAVE32: u32 = 1 << 5; +const RECORD_REGS: usize = 0x50; +const RECORD_LAYOUT: usize = 0x28; +const RECORD_USED: usize = 0x30; +const RECORD_COUNTS: usize = 0x38; +const ENTRY_SIZE: u64 = 20; +const MAX_SEMANTICS: u32 = 32; +const PS_INPUTS: usize = 0x24; +const PS_INPUT_COUNT: usize = 0x124; +const PS_INPUT_ADDR: usize = 0x134; +const PS_DB_SHADER_CONTROL: usize = 0x138; +const PS_PATCH_SIZE: usize = 0x148; +const PS_PATCHES: usize = 0x14c; +const PATCH_SLOT_DWORDS: usize = 10; +/// The variant that exports every channel as a raw 32-bit value. +const PATCH_FULL: usize = 9; +const PATCH_BYTES: usize = 4 + 10 * PATCH_SLOT_DWORDS * 4; +const MRTS: usize = 8; +const VS_INPUTS: usize = 0x24; +const VS_INPUT_COUNT: usize = 0xc4; +const VS_OUTPUTS: usize = 0xc8; +const VS_OUTPUT_COUNT: usize = 0x188; +const CS_RSRC2: usize = 0x24; +const CS_THREADS: usize = 0x28; +const RECORD_LDS: usize = 0x4c; +const MS_CLIP_CNTL: usize = 0x194; +const MS_INFO: usize = 0x448; +/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. +const MAX_UNPACKED: u64 = 16 << 20; + +/// Hardware shader stage a native program runs as. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum HwStage { + Ls, + Hs, + Es, + Gs, + Vs, + Ps, + /// Mesh shader. + Ms, + Cs, +} + +impl HwStage { + /// The SGPR holding user-data dword `index`: merged stages (and mesh + /// shaders, which run as one) have 8 system SGPRs first. + pub fn user_sgpr(self, index: u8) -> u8 { + match self { + HwStage::Ls | HwStage::Hs | HwStage::Es | HwStage::Gs | HwStage::Ms => index + 8, + HwStage::Vs | HwStage::Ps | HwStage::Cs => index, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeProgram { + pub stage: HwStage, + /// Runs as 64 lanes per wave (else 32); sizes lane masks. + pub wave64: bool, + /// VGPRs the program uses (v0 up to this), the bound of indexed access. + pub vgprs: u16, + /// Where the root signature's parameters arrive (user SGPRs). + pub layout: Vec<RootParam>, + /// The descriptors the program reads, by root parameter. + pub used: Vec<UsedResource>, + pub io: StageIo, + /// GFX10 machine code, as stored. + pub code: Vec<u8>, +} + +impl NativeProgram { + /// The code with each render target's export patched for its full + /// 32-bit format, so exports carry the shader's values unconverted (as + /// the console does at pipeline creation for that format). + pub fn patched_code(&self) -> Vec<u8> { + let mut code = self.code.clone(); + if let StageIo::Ps { patches, .. } = &self.io { + for p in patches { + let at = p.offset as usize * 4; + for (i, word) in p.code.iter().enumerate() { + code[at + 4 * i..at + 4 * i + 4].copy_from_slice(&word.to_le_bytes()); + } + } + } + code + } +} + +/// What a semantic is, as the stage data names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Usage { + Generic, + ClipDistance, + Other(u8), +} + +impl Usage { + fn from_raw(raw: u8) -> Self { + match raw { + 6 => Usage::Generic, + 7 => Usage::ClipDistance, + n => Usage::Other(n), + } + } +} + +/// A pixel shader input: what `v_interp` of attribute `attr` reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PsInput { + pub usage: Usage, + /// Register in the input signature. + pub row: u8, + pub mask: u8, + pub attr: u8, + pub flat: bool, + pub fp16: bool, + /// Two 16-bit values per dword ([`VsOutput::pack2`]); `row2` is the + /// second element's register. + pub pack2: bool, + pub row2: u8, +} + +/// A vertex attribute the fetch shader loads: channel k into VGPR `vgpr + k`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VsInput { + pub usage: Usage, + pub row: u8, + pub mask: u8, + pub vgpr: u8, +} + +/// What `exp param<param>` of a vertex shader writes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VsOutput { + pub usage: Usage, + /// Register in the output signature. + pub row: u8, + pub param: u8, + /// 16-bit values, one per dword (low half) unless `pack2`: then two per + /// dword, channel c of this row in dword c / 2 (odd channels in the + /// high half), then a second 16-bit row from the next whole dword (the + /// next 16-bit row of the signature no entry names). + pub fp16: bool, + pub pack2: bool, +} + +/// The export code of one render target for its full 32-bit format. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExportPatch { + pub mrt: u8, + /// Where it goes in the code, in dwords. + pub offset: u32, + pub code: Vec<u32>, +} + +/// Inputs and outputs, for the stages whose stage data is read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum StageIo { + #[default] + None, + Vs { + inputs: Vec<VsInput>, + outputs: Vec<VsOutput>, + }, + Ps { + inputs: Vec<PsInput>, + /// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs. + input_addr: u32, + /// `DB_SHADER_CONTROL`: depth export, kill. + db_shader_control: u32, + patches: Vec<ExportPatch>, + }, + Cs(ComputeIo), + Ms(MeshIo), +} + +/// 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`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshIo { + /// `exp param<n>` targets; `param` bit 7 set: a per-primitive output, + /// `row` then a row of the primitive signature (`PSG1`). + pub outputs: Vec<VsOutput>, + /// `PA_CL_VS_OUT_CNTL`: which clip and cull distances `pos1+` carry. + pub clip_cntl: u32, + /// Thread-group size in lanes (the HLSL group rounded up to waves). + pub threads: u32, + pub max_vertices: u32, + pub max_primitives: u32, + /// 1 lines, 2 triangles. + pub topology: u8, + pub lds_bytes: u32, +} + +/// A compute program's dispatch settings. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ComputeIo { + /// `COMPUTE_PGM_RSRC2`: user SGPRs, which system SGPRs and VGPRs + /// follow them, LDS size. + pub rsrc2: u32, + /// Thread-group size (`numthreads`). + pub threads: [u32; 3], +} + +impl ComputeIo { + /// User SGPRs before the system ones. + pub fn user_sgprs(&self) -> u8 { + (self.rsrc2 >> 1 & 0x1F) as u8 + } + + /// The SGPR of each enabled thread-group id component, in order after + /// the user SGPRs, then the thread-group info SGPR if enabled. + pub fn system_sgprs(&self) -> ([Option<u8>; 3], Option<u8>) { + let mut next = self.user_sgprs(); + let mut take = |bit: u32| { + (self.rsrc2 >> bit & 1 != 0).then(|| { + next += 1; + next - 1 + }) + }; + let ids = [take(7), take(8), take(9)]; + (ids, take(10)) + } + + /// SGPRs the hardware initializes: the user SGPRs, the enabled system + /// ones, then the scratch wave offset when scratch is enabled (bit 0). + /// The ones above hold whatever the previous wave left. + pub fn initialized_sgprs(&self) -> u8 { + let (ids, info) = self.system_sgprs(); + let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max(); + end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8 + } + + /// Thread id components in v0, v1, v2 (1 to 3). + pub fn thread_id_vgprs(&self) -> u8 { + (self.rsrc2 >> 11 & 3) as u8 + 1 + } + + /// LDS bytes per thread group (512-byte granules). + pub fn lds_bytes(&self) -> u32 { + (self.rsrc2 >> 15 & 0x1FF) * 512 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum RootType { + Constants, + /// A 64-bit buffer address. + Descriptor, + /// The 32-bit heap address of a descriptor table range. + Table, + /// A sampler the root signature fixes. + ImmediateSampler, + /// The 32-bit address of the CBV/SRV/UAV heap (SM 6.6 dynamic resources). + ResourceHeap, + /// The 32-bit address of the sampler heap. + SamplerHeap, + Other(u32), +} + +impl RootType { + fn from_raw(raw: u32) -> Self { + match raw { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 3 => RootType::Table, + 4 => RootType::ImmediateSampler, + 5 => RootType::ResourceHeap, + 6 => RootType::SamplerHeap, + n => RootType::Other(n), + } + } +} + +/// One root parameter (or table range) and the user SGPRs holding it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RootParam { + pub root: RootType, + /// Of the range within its table. + pub table_offset_dwords: u32, + /// User SGPRs from `user_data` on. + pub sgprs: u32, + /// Shader register of the first descriptor (`b`/`t`/`u`/`s` number). + pub base_register: u32, + /// First user-data dword ([`HwStage::user_sgpr`]). + pub user_data: u8, + /// Index of the parameter in the root signature. + pub slot: u8, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ResourceType { + Srv, + Sampler, + Cbv, + Uav, + Other(u8), +} + +/// A descriptor range the program reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UsedResource { + pub kind: ResourceType, + pub root: RootType, + pub table_offset_dwords: u32, + /// Shader register of the first descriptor read. + pub lower_bound: u32, + pub stride: u32, + /// Size of the descriptor (4 or 8). + pub dwords: u8, + pub user_data: u8, + pub slot: u8, +} + +/// The native programs in a `DXIL` part's data; empty for the PC layout. +pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { + if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") { + return Ok(Vec::new()); + } + let count = u32_at(part, XDAT_OFFSET + 4)? as usize; + if count > MAX_XDAT_ENTRIES { + return Err(Malformed("implausible XDAT entry count")); + } + let mut out = Vec::new(); + for i in 0..count { + let at = XDAT_OFFSET + 12 + 12 * i; + if u32_at(part, at)? != KIND_NATIVE { + continue; + } + let offset = u32_at(part, at + 4)?.into(); + let size = u32_at(part, at + 8)?.into(); + let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?; + out.extend(programs(&unpack(blob)?)?); + } + Ok(out) +} + +fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> { + if blob.get(0..4) != Some(b"XBCH") { + return Err(Malformed("native blob lacks XBCH magic")); + } + if u32_at(blob, 4)? != XBCH_VERSION { + return Err(Malformed("unknown XBCH version")); + } + let packed = u64_at(blob, 8)?; + let unpacked = u64_at(blob, 16)?; + if unpacked > MAX_UNPACKED { + return Err(Malformed("implausible XBCH unpacked size")); + } + 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")); + } + Ok(out) +} + +fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { + if fssm.get(0..4) != Some(b"FSSM") { + return Err(Malformed("native blob lacks FSSM magic")); + } + if u32_at(fssm, 4)? != FSSM_VERSION { + return Err(Malformed("unknown FSSM version")); + } + let payload = &fssm[FSSM_HEADER.min(fssm.len())..]; + if u64_at(fssm, 8)? != payload.len() as u64 { + return Err(Malformed("FSSM payload size disagrees")); + } + if u64_at(payload, 0)? != GRAPHICS_SLOT_COUNT { + return Err(Malformed("unexpected FSSM slot count")); + } + let mut out = Vec::new(); + for (stage, at) in SLOTS { + let start = u64_at(payload, at)?; + if start == ABSENT { + continue; + } + let record = + bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?; + let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?) + .ok_or(Malformed("native code out of bounds"))?; + let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16; + if vgprs > 256 { + return Err(Malformed("implausible VGPR count")); + } + let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> { + let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?); + if len == 0 { + return Ok(&[]); + } + bytes(payload, u64_at(record, at)?, len) + .ok_or(Malformed("FSSM root table out of bounds")) + }; + let layout = table(RECORD_LAYOUT, RECORD_COUNTS)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| RootParam { + root: RootType::from_raw(le32(e, 0)), + table_offset_dwords: le32(e, 4), + sgprs: le32(e, 8), + base_register: le32(e, 12), + user_data: e[16], + slot: e[17], + }) + .collect(); + let used = table(RECORD_USED, RECORD_COUNTS + 4)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| UsedResource { + kind: match e[0] { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n), + }, + root: RootType::from_raw(e[1].into()), + table_offset_dwords: le32(e, 4), + lower_bound: le32(e, 8), + stride: le32(e, 12), + dwords: e[16], + user_data: e[17], + slot: e[18], + }) + .collect(); + // The record is in bounds, so its end is too. + let stage_data = &payload[(start + RECORD_SIZE) as usize..]; + let io = match stage { + HwStage::Ps => ps_io(stage_data, code.len())?, + HwStage::Vs => vs_io(stage_data)?, + HwStage::Cs => StageIo::Cs(ComputeIo { + rsrc2: u32_at(stage_data, CS_RSRC2)?, + threads: [ + u32_at(stage_data, CS_THREADS)?, + u32_at(stage_data, CS_THREADS + 4)?, + u32_at(stage_data, CS_THREADS + 8)?, + ], + }), + HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?, + _ => StageIo::None, + }; + out.push(NativeProgram { + stage, + wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0, + vgprs, + layout, + used, + io, + code: code.to_vec(), + }); + } + Ok(out) +} + +/// The entries of `size` bytes from `at`, with their count at `count_at`. +fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> { + let count = u32_at(data, count_at)?; + if count > MAX_SEMANTICS { + return Err(Malformed("implausible semantic count")); + } + data.get(at..at + size * count as usize) + .ok_or(Malformed("stage data out of bounds")) +} + +fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> { + let inputs = semantics(data, PS_INPUTS, 8, PS_INPUT_COUNT)? + .as_chunks::<8>() + .0 + .iter() + .map(|e| PsInput { + usage: Usage::from_raw(e[0]), + row: e[1], + mask: e[2] & 0xf, + attr: e[3], + flat: e[7] & 1 != 0, + fp16: e[7] & 8 != 0, + pack2: e[7] & 0x10 != 0, + row2: e[5], + }) + .collect(); + let size = u32_at(data, PS_PATCH_SIZE)? as usize; + if size > PATCH_SLOT_DWORDS { + return Err(Malformed("implausible export patch size")); + } + let mut patches = Vec::new(); + for mrt in 0..MRTS { + let at = PS_PATCHES + mrt * PATCH_BYTES; + let offset = u32_at(data, at)?; + if offset == u32::MAX { + continue; + } + if (offset as usize + size) * 4 > code_len { + return Err(Malformed("export patch outside the code")); + } + let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + let code = (0..size) + .map(|i| u32_at(data, full + 4 * i)) + .collect::<Result<_, _>>()?; + patches.push(ExportPatch { + mrt: mrt as u8, + offset, + code, + }); + } + Ok(StageIo::Ps { + inputs, + input_addr: u32_at(data, PS_INPUT_ADDR)?, + db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?, + patches, + }) +} + +fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> { + let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)? + .as_chunks::<5>() + .0 + .iter() + .map(|e| VsInput { + usage: Usage::from_raw(e[0]), + row: e[1], + mask: e[2] & 0xf, + vgpr: e[3], + }) + .collect(); + let outputs = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)? + .as_chunks::<6>() + .0 + .iter() + .map(|e| VsOutput { + usage: Usage::from_raw(e[0]), + row: e[1], + param: e[2], + fp16: e[5] & 1 != 0, + pack2: e[5] & 2 != 0, + }) + .collect(); + Ok(StageIo::Vs { inputs, outputs }) +} + +fn ms_io(data: &[u8], lds_bytes: u32) -> Result<StageIo, ShaderError> { + let StageIo::Vs { outputs, .. } = vs_io(data)? else { + unreachable!() + }; + let info = data + .get(MS_INFO..MS_INFO + 8) + .ok_or(Malformed("stage data out of bounds"))?; + let half = |at: usize| u32::from(u16::from_le_bytes([info[at], info[at + 1]])); + Ok(StageIo::Ms(MeshIo { + outputs, + clip_cntl: u32_at(data, MS_CLIP_CNTL)?, + threads: half(0), + max_vertices: half(2), + max_primitives: half(4), + topology: info[7], + lds_bytes, + })) +} + +/// For entries already sized by `as_chunks`. +fn le32(entry: &[u8], at: usize) -> u32 { + u32::from_le_bytes(entry[at..at + 4].try_into().unwrap()) +} + +/// `data[offset..offset + len]` with untrusted 64-bit bounds. +fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> { + let start = usize::try_from(offset).ok()?; + data.get(start..start.checked_add(usize::try_from(len).ok()?)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; + const PS_CODE: [u8; 4] = [9, 10, 11, 12]; + const VGPRS: u32 = 28; + + fn slot(stage: HwStage) -> usize { + SLOTS.iter().find(|s| s.0 == stage).unwrap().1 + } + + /// Stage data: no semantics, and every export patch absent. + const STAGE_DATA: usize = PS_PATCHES + MRTS * PATCH_BYTES; + + fn empty_stage_data() -> Vec<u8> { + let mut data = vec![0; STAGE_DATA]; + for mrt in 0..MRTS { + let at = PS_PATCHES + mrt * PATCH_BYTES; + data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + } + data + } + + /// Where a one-program blob's stage data starts. + fn stage_data_at(blob: &[u8], stage: HwStage) -> usize { + FSSM_HEADER + + u64_at(blob, FSSM_HEADER + slot(stage)).unwrap() as usize + + RECORD_SIZE as usize + } + + /// FSSM blob with `programs` as (stage, code) pairs. + fn fssm(programs: &[(HwStage, &[u8])]) -> Vec<u8> { + let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec(); + payload.resize(slot(HwStage::Cs) + 8, 0); + for (_, at) in SLOTS { + payload[at..at + 8].copy_from_slice(&ABSENT.to_le_bytes()); + } + for &(stage, code) in programs { + let slot = slot(stage); + let record = payload.len() as u64; + payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes()); + let code_at = record + RECORD_SIZE + STAGE_DATA as u64; + payload.extend_from_slice(&code_at.to_le_bytes()); + payload.extend_from_slice(&(code.len() as u64).to_le_bytes()); + let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 }; + payload.extend_from_slice(&[0; 4]); + payload.extend_from_slice(&flags.to_le_bytes()); + payload.resize(record as usize + RECORD_REGS, 0); + payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes()); + payload.extend_from_slice(&empty_stage_data()); + payload.extend_from_slice(code); + } + let mut out = b"FSSM".to_vec(); + out.extend_from_slice(&FSSM_VERSION.to_le_bytes()); + out.extend_from_slice(&(payload.len() as u64).to_le_bytes()); + out.extend_from_slice(&payload); + out + } + + fn xbch(unpacked: &[u8]) -> Vec<u8> { + let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6); + 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 + } + + /// `DXIL` part data: program header, XDAT index, then the blobs. + fn part(blobs: &[(u32, &[u8])]) -> Vec<u8> { + let mut out = vec![0u8; XDAT_OFFSET]; + out.extend_from_slice(b"XDAT"); + out.extend_from_slice(&(blobs.len() as u32).to_le_bytes()); + out.extend_from_slice(&0x24u32.to_le_bytes()); + let mut offset = out.len() + 12 * blobs.len(); + for (kind, blob) in blobs { + for v in [*kind, offset as u32, blob.len() as u32] { + out.extend_from_slice(&v.to_le_bytes()); + } + offset += blob.len(); + } + for (_, blob) in blobs { + out.extend_from_slice(blob); + } + out + } + + #[test] + fn finds_graphics_programs() { + let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)])); + let data = part(&[(0x0a, b"xbop"), (KIND_NATIVE, &native)]); + let found = native_programs(&data).unwrap(); + assert_eq!( + found, + [ + NativeProgram { + stage: HwStage::Vs, + wave64: true, + vgprs: 28, + layout: vec![], + used: vec![], + io: StageIo::Vs { + inputs: vec![], + outputs: vec![], + }, + code: VS_CODE.to_vec() + }, + NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 28, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: PS_CODE.to_vec() + }, + ] + ); + } + + #[test] + fn reads_root_tables() { + let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]); + let record = FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize; + let tables = (blob.len() - FSSM_HEADER) as u64; + // A table range in s9 (root slot 1), and an SRV read from it. + for v in [3u32, 2, 1, 5] { + blob.extend_from_slice(&v.to_le_bytes()); + } + blob.extend_from_slice(&[9, 1, 0, 0, 0, 3, 0, 0]); + for v in [2u32, 5, 4] { + blob.extend_from_slice(&v.to_le_bytes()); + } + blob.extend_from_slice(&[8, 9, 1, 0]); + let payload = (blob.len() - FSSM_HEADER) as u64; + blob[8..16].copy_from_slice(&payload.to_le_bytes()); + blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&tables.to_le_bytes()); + blob[record + RECORD_USED..][..8].copy_from_slice(&(tables + ENTRY_SIZE).to_le_bytes()); + blob[record + RECORD_COUNTS..][..8].copy_from_slice(&[1, 0, 0, 0, 1, 0, 0, 0]); + + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + assert_eq!( + p.layout, + [RootParam { + root: RootType::Table, + table_offset_dwords: 2, + sgprs: 1, + base_register: 5, + user_data: 9, + slot: 1 + }] + ); + assert_eq!( + p.used, + [UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 2, + lower_bound: 5, + stride: 4, + dwords: 8, + user_data: 9, + slot: 1 + }] + ); + + blob[record + RECORD_COUNTS] = 9; + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err()); + } + + #[test] + fn reads_pixel_io_and_applies_the_full_export_patch() { + let code = [0xBF80_0000u32; 4]; // s_nop + let bytes: Vec<u8> = code.iter().flat_map(|w| w.to_le_bytes()).collect(); + let mut blob = fssm(&[(HwStage::Ps, &bytes)]); + let e = stage_data_at(&blob, HwStage::Ps); + // 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_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`. + let patch = e + PS_PATCHES + PATCH_BYTES; + blob[patch..][..4].copy_from_slice(&1u32.to_le_bytes()); + let full = patch + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + blob[full..][..8].copy_from_slice(&[0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]); + + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + let StageIo::Ps { + inputs, + input_addr, + patches, + .. + } = &p.io + else { + panic!("{:?}", p.io) + }; + let input = PsInput { + usage: Usage::Generic, + row: 1, + mask: 3, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }; + 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(); + assert_eq!(patched[..4], p.code[..4]); + assert_eq!(patched[4..12], [0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]); + assert_eq!(patched[12..], p.code[12..]); + + blob[patch..][..4].copy_from_slice(&3u32.to_le_bytes()); + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err()); + } + + #[test] + fn finds_mesh_and_compute_programs() { + for stage in [HwStage::Ms, HwStage::Cs] { + let data = part(&[(KIND_NATIVE, &xbch(&fssm(&[(stage, &VS_CODE)])))]); + let found = native_programs(&data).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].stage, stage); + } + } + + #[test] + fn reads_mesh_outputs_and_limits() { + let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]); + let e = stage_data_at(&blob, HwStage::Ms); + // param0 is row 1 per vertex, param2 row 0 of the primitive signature. + blob[e + VS_OUTPUTS..][..12].copy_from_slice(&[6, 1, 0, 0, 0, 0, 6, 0, 0x82, 0, 0, 0]); + blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); + blob[e + MS_CLIP_CNTL..][..4].copy_from_slice(&0x0040_000Fu32.to_le_bytes()); + // 128 lanes, 128 vertices, 64 primitives, 13 user SGPRs, triangles. + blob[e + MS_INFO..][..8].copy_from_slice(&[0x80, 0, 0x80, 0, 0x40, 0, 13, 2]); + let record = e - RECORD_SIZE as usize; + blob[record + RECORD_LDS..][..4].copy_from_slice(&16u32.to_le_bytes()); + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + let out = |row, param| VsOutput { + usage: Usage::Generic, + row, + param, + fp16: false, + pack2: false, + }; + assert_eq!( + p.io, + StageIo::Ms(MeshIo { + outputs: vec![out(1, 0), out(0, 0x82)], + clip_cntl: 0x0040_000F, + threads: 128, + max_vertices: 128, + max_primitives: 64, + topology: 2, + lds_bytes: 16, + }) + ); + } + + #[test] + fn compute_dispatch_settings() { + // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.user_sgprs(), 5); + assert_eq!(cs.system_sgprs(), ([Some(5), Some(6), None], None)); + assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (2, 1024)); + // 6 user SGPRs, all three group ids, v0-v2, no LDS. + let cs = ComputeIo { + rsrc2: 0x138C, + threads: [8, 8, 1], + }; + assert_eq!(cs.system_sgprs(), ([Some(6), Some(7), Some(8)], None)); + assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0)); + } + + #[test] + fn initialized_sgprs_covers_user_system_and_scratch() { + // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.initialized_sgprs(), 7); + // All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9. + let cs = ComputeIo { + rsrc2: 0x78C, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 10); + // The same with scratch enabled adds the wave offset: s0..=s10. + let cs = ComputeIo { + rsrc2: 0x78D, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 11); + } + + #[test] + fn reads_every_native_blob() { + let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); + let vs = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)])); + let data = part(&[(0x12, &[0; 16]), (KIND_NATIVE, &es), (KIND_NATIVE, &vs)]); + let stages: Vec<_> = native_programs(&data) + .unwrap() + .iter() + .map(|p| p.stage) + .collect(); + assert_eq!(stages, [HwStage::Es, HwStage::Vs]); + } + + #[test] + fn pc_layout_has_none() { + assert!(native_programs(&[0u8; 64]).unwrap().is_empty()); + assert!( + native_programs(&part(&[(0x0a, b"xbop")])) + .unwrap() + .is_empty() + ); + } + + #[test] + fn rejects_corrupt_blobs() { + let good = xbch(&fssm(&[(HwStage::Ls, &VS_CODE)])); + let corrupt = |at: usize, byte: u8| { + let mut blob = good.clone(); + blob[at] = byte; + native_programs(&part(&[(KIND_NATIVE, &blob)])) + }; + assert!(corrupt(4, 9).is_err(), "unknown version"); + assert!(corrupt(16, 0xFF).is_err(), "stated size"); + assert!(corrupt(XBCH_HEADER + 2, 0xFF).is_err(), "zlib stream"); + assert!(native_programs(&part(&[(KIND_NATIVE, &good[..20])])).is_err()); + + let mut bad_record = fssm(&[(HwStage::Ls, &VS_CODE)]); + let at = FSSM_HEADER + slot(HwStage::Ls); + bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err()); + } +} diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs new file mode 100644 index 000000000..813a9b556 --- /dev/null +++ b/crates/victory-shader/src/resource.rs @@ -0,0 +1,3848 @@ +//! Resource tracking (decision 0003): where each descriptor a program uses +//! comes from, in terms of the root signature. +//! +//! Root parameters arrive in user SGPRs ([`RootParam`]): a descriptor table +//! as the 32-bit heap address of its range (the code sets the high half to +//! 0), a root descriptor as a 64-bit buffer address, root constants as +//! themselves. A root signature with dynamic resources (SM 6.6) adds the +//! 32-bit base addresses of both heaps; a descriptor is then loaded from +//! one of them at an index the code computes (from a root constant, say). The code loads table descriptors from heap memory with +//! `s_load_dword*`, and builds a buffer descriptor around a root +//! descriptor's address itself. Each descriptor operand and each scalar +//! memory address is traced through the SSA values back to those +//! parameters, by data flow: copies, phis that agree, and additions. + +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::{Bool, LaneExit, Meets, Structured}; + +/// An instruction: block and index in [`crate::ir::Block::insts`]. +pub type Site = (usize, usize); + +/// A byte address: a root parameter's, plus a constant and at most one +/// value the program computes (an index times a stride, say). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Address { + /// Index into the layout, or [`CODE`]. + pub param: usize, + /// Added modulo 2^32 (with carry into the high half of a root + /// descriptor's address). + pub offset: u32, + pub dynamic: Option<Value>, +} + +/// [`Address::param`] of the program's own code: a constant table the +/// compiler appends after the code and reads through `s_getpc_b64`; the +/// offset is then the byte offset in the code. +pub const CODE: usize = usize::MAX; + +/// [`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 - 1; + +/// The reasons an address traces to no root parameter for which the +/// address is then taken as it stands ([`MEMORY`]). +const RAW: [&str; 5] = [ + "an address not from a root parameter", + "an address from a root parameter that is no address", + "an address in an SGPR that is no root parameter", + "an address loaded from memory", + "an address from a phi", +]; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Source { + /// Dwords `first..` of what the scalar load at `load` reads (see + /// [`Resources::scalar`] for its address). + Loaded { load: Site, first: u8 }, + /// A buffer descriptor built around an address: `bits` OR-ed into + /// dword 1 (stride, swizzle), dwords 2 and 3 as given. + Built { + address: Address, + bits: u32, + words: [u32; 2], + }, + /// Fixed in the code (an immediate sampler, say). + Constant(Vec<u32>), + /// Chosen by control flow: one source per predecessor of `block`, in + /// [`crate::ir::Block::preds`] order. + Phi { block: usize, args: Vec<Source> }, + /// Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each + /// dword reads): the source when it is set, then when it is clear. + Select { scc: Value, args: Vec<Source> }, + /// Dwords `first..` of what the vector load at `load` (`global_load_*`) + /// reads, each lane at its own address (see [`Resources::scalar`]); the + /// dwords past that load come from loads of the bytes that follow. A + /// descriptor that differs between lanes. + Fetched { load: Site, first: u8 }, + /// Picked per lane by `v_cndmask_b32` reading the lane mask whose low + /// dword is `mask`: the source where the lane's bit is set, then where it + /// is clear. + Lanes { mask: Value, args: Vec<Source> }, + /// Per-lane dwords chosen by control flow (VGPRs joined where lanes + /// that took different paths meet): one source per predecessor of + /// `block`, in [`crate::ir::Block::preds`] order, `None` on an edge no + /// lane that accesses the descriptor takes. A descriptor that differs + /// between lanes. + LanePhi { + block: usize, + args: Vec<Option<Source>>, + }, +} + +impl Source { + /// The sources this one picks from (itself unless a phi). + pub fn leaves(&self) -> Vec<&Source> { + match self { + Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } => { + args.iter().flat_map(Source::leaves).collect() + } + Source::LanePhi { args, .. } => { + args.iter().flatten().flat_map(Source::leaves).collect() + } + s => vec![s], + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + /// Image, buffer or `s_buffer_load` resource. + Resource, + Sampler, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Descriptor { + pub site: Site, + pub role: Role, + pub source: Source, +} + +/// A view-heap descriptor whose byte address can be evaluated when binding +/// the draw, using a table base and a root constant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RootIndexedView { + pub table_slot: u8, + pub constant_slot: u8, + pub constant_dword: u32, + pub byte_offset: u32, + pub shift: u8, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Resources { + /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and + /// every global memory access (`global_*`, the dynamic term per lane). + pub scalar: Vec<(Site, Address)>, + pub descriptors: Vec<Descriptor>, + /// Direct descriptor sources with a draw-evaluable index. + pub root_indexed_views: Vec<RootIndexedView>, + /// User SGPRs holding root parameters: value on entry, layout index, + /// dword within the parameter. + pub params: Vec<(Value, usize, u32)>, + /// Scalar loads of one descriptor the code keeps per lane in VGPRs + /// ([`Tracer::lane_copies`]): they read one address, so their dwords + /// stand in for each other. + pub lane_copied: Vec<Site>, + pub waterfall: Waterfall, + /// Every `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`: where + /// its nodes are. + pub bvh: Vec<(Site, BvhNodes)>, +} + +/// Where a ray-tracing node test ([`crate::bvh`]) reads its nodes. Its +/// descriptor operand names a range of memory, not a texture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +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. + Resource, + /// Title memory by address: the code makes the descriptor from numbers + /// (the title: the whole address space, or one structure's address in + /// dword 0). Dwords 1 and 3, which hold its flags. + Memory { word1: u32, word3: u32 }, +} + +/// Waterfall loops over descriptors that differ between lanes: each pass +/// reads the first active lane's descriptor with `v_readfirstlane_b32`, +/// compares it with every lane's own (`v_cmp_eq`), and runs the access with +/// the lanes that match. Their accesses take each lane's own descriptor +/// ([`Source::Fetched`], [`Source::Lanes`]), so the first lane's dwords are +/// each lane's own too: the compares hold in every lane and one pass serves +/// all lanes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Waterfall { + /// The compares, true in every lane. + pub compares: Vec<Site>, + /// The `v_readfirstlane_b32` results they compare, each the lane's own + /// source dword. + pub reads: Vec<Value>, + /// Descriptor loads at a table offset among `reads` (the console + /// compiler's form): each lane loads its own entry. + pub loads: Vec<Site>, +} + +/// Traces every descriptor and scalar address of `p`, which runs as +/// `stage`, to the root parameters in `layout`. Fails on the first one it +/// cannot trace. `lanes`, `p` as one lane runs it, tells which paths the +/// lanes that access a per-lane descriptor took and which writes they ran; +/// without it, per-lane descriptors chosen by control flow are refused and +/// per-lane writes are taken to run in every lane. +pub fn track( + p: &Program, + layout: &[RootParam], + stage: HwStage, + lanes: Option<&Structured>, +) -> Result<Resources, ShaderError> { + let t = Tracer::new(p, layout, stage, lanes)?; + let mut out = Resources { + params: p + .inputs + .iter() + .filter_map(|&(reg, v)| { + let (param, dword) = t.param_of(reg)?; + Some((v, param, dword)) + }) + .collect(), + ..Resources::default() + }; + // Group accesses in the same loop so a shared mask can select several + // descriptors together. + let mut first_lane_at = std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>)>::new(); + // The console compiler's waterfall reads the first lane's table offset + // and loads that entry: accesses, offset reads and loads by block. + let mut offset_at = + std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new(); + for (b, block) in p.blocks.iter().enumerate() { + t.at.set(Some(b)); + for (i, inst) in block.insts.iter().enumerate() { + let site = (b, i); + let fail = |what| ShaderError::Unsupported { + offset: inst.machine.offset, + what, + }; + let mut first_lane = Vec::new(); + 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`]) + // is the same in every lane: its loop is lowered as it stands + // and needs no proof. + if !t.kept_per_lane(inst, op) { + first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + } + if let Source::Loaded { load, .. } = source + && out.scalar.iter().any(|s| s.0 == load) + && let Some(v) = t.first_lane_offset(load) + { + offset.push((v, load)); + } + out.descriptors.push(Descriptor { site, role, source }); + Ok(()) + }; + match &inst.fields { + Fields::Image { rsrc, .. } if inst.name().starts_with("image_bvh") => { + // The ray and node test names no texture. A descriptor + // whose flag dwords the code sets as numbers and whose + // type is a ray-tracing structure is a range of title + // memory (the title: all of it, or from one structure's + // address on), and the node's address is among the + // operands; any other descriptor must be a resource of + // the host. + let word = |k: u8| match *rsrc { + Operand::Scalar { code, dwords } if k < dwords => { + inst.read(Reg::S(code + k)).map(|v| t.origin(v)) + } + _ => None, + }; + match (word(1), word(3)) { + (Some(Term::Const(word1)), Some(Term::Const(word3))) + if word3 >> 28 == crate::bvh::DESCRIPTOR_TYPE => + { + out.bvh.push((site, BvhNodes::Memory { word1, word3 })); + } + _ => { + descriptor(rsrc, Role::Resource)?; + out.bvh.push((site, BvhNodes::Resource)); + } + } + } + Fields::Image { rsrc, sampler, .. } => { + descriptor(rsrc, Role::Resource)?; + if let Some(s) = sampler { + descriptor(s, Role::Sampler)?; + } + } + // Cache invalidations name a buffer's address space but do + // not read its descriptor; the host has no cache to drop. + Fields::Buffer { rsrc, .. } if !inst.name().ends_with("_inv") => { + descriptor(rsrc, Role::Resource)? + } + Fields::Buffer { .. } => {} + Fields::Smem { base, .. } if inst.name().starts_with("s_buffer_") => { + descriptor(base, Role::Resource)?; + } + Fields::Smem { + base, + offset, + soffset, + .. + } if inst.name().contains("_load_") || inst.name().contains("_store_") => { + let address = t + .smem_address(inst, base, *offset, soffset) + .or_else(|why| t.by_address(why)) + .map_err(fail)?; + out.scalar.push((site, address)); + } + Fields::Flat { + addr, + saddr, + offset, + .. + } if inst.name().starts_with("global_") => { + let address = t + .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + .or_else(|why| t.by_address(why)) + .map_err(fail)?; + out.scalar.push((site, address)); + } + _ => {} + } + if !first_lane.is_empty() { + let (accesses, reads) = first_lane_at.entry(b).or_default(); + accesses.push(i); + reads.extend(first_lane); + } + if !offset.is_empty() { + let (accesses, reads, loads) = offset_at.entry(b).or_default(); + accesses.push(i); + for (v, load) in offset { + reads.push(v); + loads.push(load); + } + } + } + } + // What follows traces no access of one block. + t.at.set(None); + // The proof needs the per-lane form. Without it nothing is emitted, and + // its failure is the one to report, so the reads stay unproven here. + if t.lanes.is_none() { + return Ok(out); + } + 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, + })?; + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); + } + // Unproven, an offset read stays the first lane's (one uniform entry), + // which is what the hardware reads outside a waterfall loop. + for (block, (accesses, mut reads, loads)) in offset_at { + reads.sort_unstable(); + reads.dedup(); + if let Ok(proof) = t.waterfall(block, &accesses, &reads) { + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); + out.waterfall.loads.extend(loads); + } + } + out.lane_copied = t.lane_copied.take(); + out.lane_copied.sort_unstable(); + out.lane_copied.dedup(); + out.root_indexed_views = out + .descriptors + .iter() + .filter_map(|d| t.root_indexed_view(d, &out.scalar)) + .collect(); + Ok(out) +} + +/// A dword after copy propagation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Term { + Const(u32), + Value(Value), +} + +/// A 32-bit sum: optional root parameter (as its first dword), constant, +/// optional computed term. +struct Sum { + base: Option<Value>, + offset: u32, + dynamic: Option<Value>, +} + +struct Tracer<'a> { + p: &'a Program, + layout: &'a [RootParam], + stage: HwStage, + /// Defining instruction per value (phis and inputs have none). + defs: Vec<Option<Site>>, + /// Block and index of each phi value. + phis: Vec<Option<(usize, usize)>>, + /// Register per input value. + inputs: Vec<Option<Reg>>, + origin: Vec<Term>, + /// See [`Resources::lane_copied`]. + lane_copied: std::cell::RefCell<Vec<Site>>, + lanes: Option<&'a Structured>, + /// While set, [`Self::sum`] keeps the first-lane read of an index as + /// the computed term instead of what the lanes hold. + read_first_lane: std::cell::Cell<bool>, + /// What the conditions asked of `lanes` so far came down to: the proofs + /// of one program ask about the same blocks and masks again and again. + meets: std::cell::RefCell<Meets>, + /// Reverse-postorder index per block. + rpo: Vec<usize>, + /// The block of the access being traced ([`Self::live`]). + at: std::cell::Cell<Option<usize>>, +} + +/// What lanes are known to satisfy: each [`Bool`] where its flag is set, +/// its negation where not. +type Known = Vec<(Bool, bool)>; + +const MAX_ROUNDS: usize = 64; +const MAX_JOINS: usize = 8; +/// VGPR values followed for one dword of a descriptor kept per lane. +const MAX_COPIES: usize = 64; + +impl<'a> Tracer<'a> { + fn new( + p: &'a Program, + layout: &'a [RootParam], + stage: HwStage, + lanes: Option<&'a Structured>, + ) -> Result<Self, ShaderError> { + let all = || { + p.inputs + .iter() + .map(|i| i.1) + .chain(p.blocks.iter().flat_map(|b| { + b.phis + .iter() + .map(|phi| phi.value) + .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1))) + })) + }; + let n = all().map(|v| v.0 as usize + 1).max().unwrap_or(0); + let mut defs = vec![None; n]; + let mut phis = vec![None; n]; + let mut inputs = vec![None; n]; + for &(reg, v) in &p.inputs { + inputs[v.0 as usize] = Some(reg); + } + for (b, block) in p.blocks.iter().enumerate() { + for (i, phi) in block.phis.iter().enumerate() { + phis[phi.value.0 as usize] = Some((b, i)); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs[v.0 as usize] = Some((b, i)); + } + } + } + let mut rpo = vec![usize::MAX; p.blocks.len()]; + for (n, b) in crate::ir::reverse_postorder(&p.blocks) + .into_iter() + .enumerate() + { + rpo[b] = n; + } + let mut t = Tracer { + p, + layout, + stage, + defs, + phis, + inputs, + origin: Vec::new(), + lane_copied: Default::default(), + lanes, + read_first_lane: Default::default(), + meets: Default::default(), + rpo, + at: Default::default(), + }; + t.origin = t.propagate_copies(n)?; + Ok(t) + } + + /// Optimistic copy propagation: a move's result is its source's + /// origin, a phi's the one origin its arguments agree on. + fn propagate_copies(&self, n: usize) -> Result<Vec<Term>, ShaderError> { + let mut o: Vec<Option<Term>> = vec![None; n]; + for &(_, v) in &self.p.inputs { + o[v.0 as usize] = Some(Term::Value(v)); + } + let order = crate::ir::reverse_postorder(&self.p.blocks); + for _ in 0..MAX_ROUNDS { + let mut changed = false; + for &b in &order { + let block = &self.p.blocks[b]; + for phi in &block.phis { + let own = Term::Value(phi.value); + let mut args = phi + .args + .iter() + .filter_map(|a| o[a.0 as usize]) + .filter(|&t| t != own); + let new = args + .next() + .map(|first| if args.all(|t| t == first) { first } else { own }); + if new.is_some() && new != o[phi.value.0 as usize] { + o[phi.value.0 as usize] = new; + changed = true; + } + } + for inst in &block.insts { + for (k, &(_, v)) in inst.writes.iter().enumerate() { + let new = match copy_source(inst, k).or_else(|| self.restored(inst)) { + Some(Moved::Const(c)) => Some(Term::Const(c)), + Some(Moved::Value(s)) => o[s.0 as usize], + None => Some(Term::Value(v)), + }; + if new.is_some() && new != o[v.0 as usize] { + o[v.0 as usize] = new; + changed = true; + } + } + } + } + if !changed { + return Ok(o + .into_iter() + .enumerate() + .map(|(v, t)| t.unwrap_or(Term::Value(Value(v as u32)))) + .collect()); + } + } + Err(ShaderError::Unsupported { + offset: 0, + what: "copies that do not settle", + }) + } + + /// Whether some lane can satisfy all of `conditions` ([`Bools::meet`]). + /// + /// [`Bools::meet`]: crate::structure::Bools::meet + fn meet(&self, lanes: &Structured, conditions: &[(Bool, bool)]) -> bool { + lanes + .bools + .meet_seen(conditions, &mut self.meets.borrow_mut()) + } + + fn inst(&self, (b, i): Site) -> &'a Inst { + &self.p.blocks[b].insts[i] + } + + fn def(&self, v: Value) -> Option<&'a Inst> { + self.defs[v.0 as usize].map(|s| self.inst(s)) + } + + fn origin(&self, v: Value) -> Term { + self.origin[v.0 as usize] + } + + /// The origin of a one-dword operand as `inst` reads it. + fn term(&self, inst: &Inst, op: &Operand) -> Option<Term> { + match *op { + Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)), + Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code))?)), + Operand::Const(c) => inline(c).map(Term::Const), + Operand::Literal(x) => Some(Term::Const(x)), + _ => None, + } + } + + /// Layout index and dword of the root parameter `reg` holds on entry. + fn param_of(&self, reg: Reg) -> Option<(usize, u32)> { + let Reg::S(code) = reg else { return None }; + self.layout.iter().enumerate().find_map(|(i, p)| { + let first = self.stage.user_sgpr(p.user_data); + let dword = u32::from(code).checked_sub(first.into())?; + (dword < p.sgprs).then_some((i, dword)) + }) + } + + /// The SOP2 operands of `v` if an instruction with one of `names` wrote it. + fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> { + let inst = self.def(v)?; + if !names.contains(&inst.name()) || inst.writes.first()?.1 != v { + return None; + } + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + Some(( + inst, + [ + self.term(inst, src.first()?)?, + self.term(inst, src.get(1)?)?, + ], + )) + } + + fn root_indexed_view( + &self, + descriptor: &Descriptor, + scalar: &[(Site, Address)], + ) -> Option<RootIndexedView> { + if descriptor.role != Role::Resource { + return None; + } + let Source::Loaded { load, first } = descriptor.source else { + return None; + }; + let i = scalar.binary_search_by_key(&load, |(site, _)| *site).ok()?; + let address = scalar[i].1; + let base = self.layout.get(address.param)?; + if base.root != RootType::Table { + return None; + } + let dynamic = address.dynamic?; + let (input, shift) = match self.sop2(dynamic, &["s_lshl_b32"]) { + Some((_, [Term::Value(input), Term::Const(shift)])) => (input, (shift & 31) as u8), + _ => (dynamic, 0), + }; + let (param, constant_dword) = self.param_of(self.inputs[input.0 as usize]?)?; + let constant = self.layout.get(param)?; + if constant.root != RootType::Constants { + return None; + } + Some(RootIndexedView { + table_slot: base.slot, + constant_slot: constant.slot, + constant_dword, + byte_offset: address.offset.wrapping_add(u32::from(first) * 4), + shift, + }) + } + + fn sum(&self, t: Term) -> Sum { + let v = match t { + Term::Const(c) => { + return Sum { + base: None, + offset: c, + dynamic: None, + }; + } + Term::Value(v) => v, + }; + let dynamic = Sum { + base: None, + offset: 0, + dynamic: Some(v), + }; + if let Some(reg) = self.inputs[v.0 as usize] { + return match self.param_of(reg) { + Some((_, 0)) => Sum { + base: Some(v), + offset: 0, + dynamic: None, + }, + _ => dynamic, + }; + } + if self.getpc(v).is_some() { + return Sum { + base: Some(v), + offset: 0, + dynamic: None, + }; + } + // 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 + // byte in the code whichever table a path took ([`Self::address`] adds no + // base to it). + if let Some(pc) = self.code_join(v) { + return Sum { + base: Some(pc), + offset: 0, + dynamic: Some(v), + }; + } + // An address computed in VGPRs and taken from the first lane (a + // table in the code indexed by a value held per lane, or a table + // offset held per lane, the console's waterfall): the sum of what + // the lanes hold. Loads at one offset in different loops (each with + // its own `v_readfirstlane_b32`) then have one address, which is + // what tells lowering that they read one descriptor. With + // `read_first_lane` a first-lane read of an index alone stays the + // computed term ([`Self::first_lane_offset`]). + if let Some(lane) = self.first_lane(v) { + let per_lane = self.sum(self.vorigin(lane)); + return if per_lane.base.is_some() || !self.read_first_lane.get() { + per_lane + } else { + dynamic + }; + } + let Some([a, b]) = self + .sop2(v, &["s_add_u32", "s_add_i32"]) + .map(|(_, t)| t) + .or_else(|| self.vadd(v)) + else { + return dynamic; + }; + let (x, y) = (self.sum(a), self.sum(b)); + if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { + return dynamic; + } + Sum { + base: x.base.or(y.base), + offset: x.offset.wrapping_add(y.offset), + dynamic: x.dynamic.or(y.dynamic), + } + } + + /// 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 + /// 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<Value> { + let (b, i) = self.phis[v.0 as usize]?; + let mut base = None; + for &a in &self.p.blocks[b].phis[i].args { + let Term::Value(x) = self.vorigin(a) else { + return None; + }; + if x == v { + continue; + } + let pc = self.code_base(x, 4)?; + base = base.or(Some(pc)); + } + base + } + + /// `t` is the high dword of an `s_getpc_b64`, or `s_addc_u32`s of one: + /// the carry may be added in steps (the counter's high dword plus 0 + /// where the table's offset is added, then plus the index's high dword). + fn code_high(&self, t: Term) -> bool { + self.code_high_in(t, 4) + } + + /// [`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) + }) { + return true; + } + depth > 0 + && self.sop2(x, &["s_addc_u32"]).is_some_and(|(_, [p, q])| { + self.code_high_in(p, depth - 1) || self.code_high_in(q, depth - 1) + }) + } + + /// The `s_getpc_b64` low dword among the terms `v` adds up (`depth` + /// additions deep; joins are not followed). + fn code_base(&self, v: Value, depth: u32) -> Option<Value> { + if self.getpc(v).is_some() { + return Some(v); + } + // Computed in VGPRs and taken from the first lane. + if let Some(lane) = self.first_lane(v) { + return match self.vorigin(lane) { + Term::Value(x) => self.code_base(x, depth), + Term::Const(_) => None, + }; + } + if depth == 0 || self.phis[v.0 as usize].is_some() { + return None; + } + let terms = self + .sop2(v, &["s_add_u32", "s_add_i32"]) + .map(|(_, t)| t) + .or_else(|| self.vadd(v))?; + terms.into_iter().find_map(|t| match t { + Term::Value(x) => self.code_base(x, depth - 1), + Term::Const(_) => None, + }) + } + + /// `t` is `high` or an `s_addc_u32` of it. + fn is_high(&self, t: Term, high: Value) -> bool { + match t { + Term::Value(x) => { + x == high + || self + .sop2(x, &["s_addc_u32"]) + .is_some_and(|(_, [p, q])| p == Term::Value(high) || q == Term::Value(high)) + } + Term::Const(_) => false, + } + } + + /// The VGPR value `v_readfirstlane_b32` reads to write the scalar `v`. + fn first_lane(&self, v: Value) -> Option<Value> { + let inst = self.def(v)?; + if inst.name() != "v_readfirstlane_b32" || inst.writes.first()?.1 != v { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + match *f.src.first()? { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + _ => None, + } + } + + /// The `s_getpc_b64` writing `lo` as its low dword. + fn getpc(&self, lo: Value) -> Option<&'a Inst> { + let inst = self.def(lo)?; + (inst.name() == "s_getpc_b64" && inst.writes.first().is_some_and(|w| w.1 == lo)) + .then_some(inst) + } + + /// The operands of a VALU addition (`v_add_co_u32`, `v_add_nc_u32`) + /// writing `v`, through VGPR copies of scalars. + fn vadd(&self, v: Value) -> Option<[Term; 2]> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if !matches!(inst.name(), "v_add_co_u32" | "v_add_nc_u32") + || f.dst.is_none_or(|d| !matches!(d, Operand::Vector { .. })) + || inst.write(Reg::V(match f.dst? { + Operand::Vector { reg, .. } => reg, + _ => return None, + })) != Some(v) + || f.abs != 0 + || f.neg != 0 + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + Some([ + self.vterm(inst, f.src.first()?)?, + self.vterm(inst, f.src.get(1)?)?, + ]) + } + + /// The origin of a VALU operand. + fn vterm(&self, inst: &Inst, op: &Operand) -> Option<Term> { + match *op { + Operand::Vector { reg, .. } => Some(self.vorigin(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), + } + } + + /// A VGPR value's origin through `v_mov_b32` copies. + fn vorigin(&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.vterm(inst, s)) + { + return t; + } + self.origin(v) + } + + /// The address of an access that traces to no root parameter (`why` + /// says how it failed): title memory at the address as it stands, in a + /// compute program. + fn by_address(&self, why: &'static str) -> Result<Address, &'static str> { + if self.stage == HwStage::Cs && RAW.contains(&why) { + Ok(Address { + param: MEMORY, + offset: 0, + dynamic: None, + }) + } else { + Err(why) + } + } + + /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR + /// pair. + fn flat_address( + &self, + inst: &Inst, + addr: Option<&Operand>, + saddr: Option<&Operand>, + offset: i16, + ) -> Result<Address, &'static str> { + let Some(&Operand::Vector { reg, .. }) = addr else { + return Err("a global address not in VGPRs"); + }; + let off = offset as i32 as u32; + match saddr { + Some(&Operand::Scalar { code, .. }) if code != NULL => { + let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("an address not in SGPRs"); + }; + let v = inst.read(Reg::V(reg)).ok_or("a global address")?; + let mut extra = self.sum(self.vorigin(v)); + if extra.base.is_some() { + return Err("an offset from a root parameter"); + } + extra.offset = extra.offset.wrapping_add(off); + self.address(lo, hi, extra) + } + _ => { + let word = |k| inst.read(Reg::V(reg + k)).map(|v| self.vorigin(v)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("a global address"); + }; + self.address( + lo, + hi, + Sum { + base: None, + offset: off, + dynamic: None, + }, + ) + } + } + } + + /// 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<Address, &'static str> { + // 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(hi) { + t @ Term::Const(_) => t, + Term::Value(v) if self.inputs[v.0 as usize].is_some() => Term::Value(v), + _ => hi, + }; + let s = self.sum(lo); + if s.dynamic.is_some() && extra.dynamic.is_some() { + return Err("an address with two computed terms"); + } + let base = s.base.ok_or_else(|| self.why_no_base(s.dynamic))?; + if let Some(pc) = self.getpc(base) { + // A table in the code: the base is the next instruction's offset. + let high = pc.writes.get(1).map(|w| w.1); + if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) { + return Err("an address with an untracked high half"); + } + // 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 }; + return Ok(Address { + param: CODE, + offset: first.wrapping_add(s.offset).wrapping_add(extra.offset), + dynamic: s.dynamic.or(extra.dynamic), + }); + } + let reg = self.inputs[base.0 as usize].ok_or("an address not from a root parameter")?; + let (param, _) = self + .param_of(reg) + .ok_or("an address not from a root parameter")?; + let high = match self.layout[param].root { + RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap => None, + RootType::Descriptor => { + let high = Reg::S(self.stage.user_sgpr(self.layout[param].user_data) + 1); + let input = self.p.inputs.iter().find(|i| i.0 == high); + Some(input.ok_or("a root descriptor without its high half")?.1) + } + _ => return Err("an address from a root parameter that is no address"), + }; + // shortcut: with a computed term, a high half that adds anything to the + // base's is taken as the carry of that term (offsets below 4 GB). + let dynamic = s.dynamic.or(extra.dynamic); + if !self.high_half(hi, high) + && !(dynamic.is_some() && high.is_some_and(|h| self.carried(hi, h))) + { + return Err("an address with an untracked high half"); + } + Ok(Address { + param, + offset: s.offset.wrapping_add(extra.offset), + dynamic: s.dynamic.or(extra.dynamic), + }) + } + + /// `hi` is `high` (0 for a table), possibly plus a carry. + fn high_half(&self, hi: Term, high: Option<Value>) -> bool { + let want = high.map_or(Term::Const(0), Term::Value); + hi == want + || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and( + |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0) + )) + } + + /// `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) = hi else { return false }; + if v == high { + return true; + } + // A join ([`Self::code_join`]): every path carries into the table's high half. + if let Some((b, i)) = self.phis[v.0 as usize] { + // A path may carry into another table's high half ([`Self::code_join`]). + let high_of = |t: Term| self.is_high(t, high) || self.code_high(t); + return self.p.blocks[b].phis[i].args.iter().all(|&a| { + let t = self.vorigin(a); + if t == Term::Value(v) || high_of(t) { + return true; + } + let Term::Value(x) = t else { + return false; + }; + // Computed in VGPRs and taken from the first lane. + let x = match self.first_lane(x).map(|lane| self.vorigin(lane)) { + Some(Term::Value(y)) => y, + Some(Term::Const(_)) => return false, + None => x, + }; + let Some(inst) = self.def(x) else { + return false; + }; + let Fields::Valu(f) = &inst.fields else { + return false; + }; + inst.name() == "v_add_co_ci_u32" + && f.src[..2.min(f.src.len())] + .iter() + .any(|o| self.vterm(inst, o).is_some_and(high_of)) + }); + } + if let Some(lane) = self.first_lane(v) { + return self.carried(self.vorigin(lane), high); + } + if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + return self.carried(a, high) || self.carried(b, high); + } + let Some(inst) = self.def(v) else { + return false; + }; + let Fields::Valu(f) = &inst.fields else { + return false; + }; + inst.name() == "v_add_co_ci_u32" + && f.src[..2.min(f.src.len())] + .iter() + .any(|o| self.vterm(inst, o).is_some_and(|t| self.carried(t, high))) + } + + fn why_no_base(&self, dynamic: Option<Value>) -> &'static str { + let Some(v) = dynamic else { + return "a constant address"; + }; + if self.inputs[v.0 as usize].is_some() { + return "an address in an SGPR that is no root parameter"; + } + if self + .leaves(v) + .any(|l| self.def(l).is_some_and(|i| i.name() == "s_getpc_b64")) + { + return "an address relative to the program counter"; + } + match self.def(v).map(|i| i.name()) { + 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", + } + } + + /// The terms of the additions that compute `v`. + fn leaves(&self, v: Value) -> Box<dyn Iterator<Item = Value> + '_> { + match self.sop2(v, &["s_add_u32", "s_add_i32"]) { + Some((_, terms)) => Box::new(terms.into_iter().flat_map(move |t| match t { + Term::Value(x) => self.leaves(x), + Term::Const(_) => Box::new(std::iter::empty()), + })), + None => Box::new(std::iter::once(v)), + } + } + + fn smem_address( + &self, + inst: &Inst, + base: &Operand, + offset: i32, + soffset: &Operand, + ) -> Result<Address, &'static str> { + let Operand::Scalar { code, .. } = *base else { + return Err("an address not in SGPRs"); + }; + let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("an address not in SGPRs"); + }; + let mut extra = self.sum( + self.term(inst, soffset) + .ok_or("an unknown offset operand")?, + ); + if extra.base.is_some() { + return Err("an offset from a root parameter"); + } + extra.offset = extra.offset.wrapping_add(offset as u32); + self.address(lo, hi, extra) + } + + /// The source of the descriptor operand `op` of `inst`, in block `at`. + fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> { + let Operand::Scalar { code, dwords } = *op else { + return Err("a descriptor not in SGPRs"); + }; + let words = (0..dwords) + .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) + .collect::<Option<Vec<_>>>() + .ok_or("a descriptor not in SGPRs")?; + // Only the lanes that reach the access read the descriptor. + let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); + self.classify(&words, &mut Vec::new(), &mut known) + } + + /// The source of a descriptor's words; `joins` are the phi blocks + /// being resolved, `known` holds in every lane that reads them. + fn classify( + &self, + words: &[Term], + joins: &mut Vec<usize>, + known: &mut Known, + ) -> Result<Source, &'static str> { + if let Some(source) = self.phi(words, joins, known)? { + return Ok(source); + } + if let Some(source) = self.select(words, joins, known)? { + return Ok(source); + } + let read = |w: &Term| match *w { + Term::Value(v) => self.first_lane_source(v), + Term::Const(_) => None, + }; + if let Some(sources) = words.iter().map(read).collect::<Option<Vec<_>>>() { + // One descriptor the code keeps per lane: the lanes agree. + if let Some(source) = self.lane_copies(words) { + return Ok(source); + } + // Read from the first active lane, as a waterfall loop does: the + // dwords each lane holds. + let lanes: Vec<Term> = sources.into_iter().map(Term::Value).collect(); + return self.per_lane(&lanes, joins, known); + } + if words.iter().any(|w| read(w).is_some()) { + return Err("a descriptor partly read from the first lane"); + } + if let Some(consts) = words + .iter() + .map(|w| match *w { + Term::Const(c) => Some(c), + Term::Value(_) => None, + }) + .collect::<Option<Vec<_>>>() + { + return Ok(Source::Constant(consts)); + } + if let Some(source) = self.loaded(words) { + return Ok(source); + } + if let [lo, hi, Term::Const(w2), Term::Const(w3)] = *words { + let (mut hi, mut bits) = (hi, 0); + while let Term::Value(v) = hi + && let Some((x, more)) = self.set_bits(v) + { + (hi, bits) = (x, bits | more); + } + let address = self.address( + lo, + hi, + Sum { + base: None, + offset: 0, + dynamic: None, + }, + )?; + return Ok(Source::Built { + address, + bits, + words: [w2, w3], + }); + } + let loaded = |w: &Term| { + matches!(*w, Term::Value(v) + if self.def(v).is_some_and(|i| i.name().starts_with("s_load_"))) + }; + Err(if words.iter().any(loaded) { + "a descriptor changed after loading" + } else { + "a descriptor neither loaded nor built" + }) + } + + /// The one edge into the join `block` that lanes satisfying `known` + /// can have taken, if the lanes' paths ([`Structured`]) rule out every + /// 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 + /// `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. + fn only_edge(&self, block: usize, known: &mut Known) -> Option<usize> { + let lanes = self.lanes?; + let preds = &self.p.blocks[block].preds; + if preds.len() < 2 || preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + return None; + } + let mut only = None; + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let possible = self.meet(lanes, known); + known.truncate(n); + if possible { + if only.is_some() { + return None; + } + only = Some(j); + } + } + only + } + + /// Whether lowering can make a handle for `source` in any block: its + /// heap index comes from root parameters and constants alone (a table + /// offset the code computes exists only where the load is). + fn anywhere(&self, source: &Source) -> bool { + match source { + Source::Constant(_) => true, + Source::Built { address, .. } => address.dynamic.is_none(), + Source::Loaded { load, .. } => { + let inst = self.inst(*load); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self + .smem_address(inst, base, *offset, soffset) + .is_ok_and(|a| a.dynamic.is_none()), + _ => false, + } + } + _ => false, + } + } + + /// `t` as the lanes that reach the access being traced hold it: through + /// joins they can have entered by one edge only ([`Self::only_edge`]). + fn live(&self, mut t: Term) -> Term { + let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { + return t; + }; + let mut known = vec![(lanes.reach[at], true)]; + for _ in 0..MAX_JOINS { + let Term::Value(v) = t else { break }; + let Some((block, i)) = self.phis[v.0 as usize] else { + break; + }; + let Some(j) = self.only_edge(block, &mut known) else { + break; + }; + t = self.origin(self.p.blocks[block].phis[i].args[j]); + } + t + } + + /// Words that phis of one block join, traced per predecessor (words + /// defined before the join hold on every edge). + fn phi( + &self, + words: &[Term], + joins: &mut Vec<usize>, + known: &mut Known, + ) -> Result<Option<Source>, &'static str> { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { + return Ok(None); + }; + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { + return Err("a descriptor joined in several blocks"); + } + if joins.contains(&block) { + return Err("a descriptor that changes in a loop"); + } + // Each level multiplies the sources by the predecessor count. + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(block); + let phis = &self.p.blocks[block].phis; + let edge = |j: usize| -> Vec<Term> { + words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => self.origin(phis[i].args[j]), + None => *w, + }) + .collect() + }; + let args = (0..self.p.blocks[block].preds.len()) + .map(|j| self.classify(&edge(j), joins, known)) + .collect::<Result<_, _>>(); + let source = match args { + Ok(args) => Ok(Source::Phi { block, args }), + // An edge holds no descriptor. With only one edge the lanes + // that read the descriptor can have come by, it is what the + // registers hold on that one (a wave that took another edge + // has no lane left that reads it), if that can be named where + // it is read. + Err(e) => match self.only_edge(block, known) { + Some(j) => match self.classify(&edge(j), joins, known) { + Ok(source) if self.anywhere(&source) => Ok(source), + _ => Err(e), + }, + None => Err(e), + }, + }; + joins.pop(); + source.map(Some) + } + + /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced + /// per outcome (other words are the same for both). + fn select( + &self, + words: &[Term], + joins: &mut Vec<usize>, + known: &mut Known, + ) -> Result<Option<Source>, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(scc) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + if picks.iter().flatten().any(|p| p.0 != scc) { + return Err("a descriptor chosen by several conditions"); + } + // Each level doubles the sources; selects count like joins (a + // marker no block index reaches). + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + let side = |set: bool| -> Vec<Term> { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| self.classify(&side(set), joins, known)) + .collect::<Result<_, _>>(); + joins.pop(); + Ok(Some(Source::Select { scc, args: args? })) + } + + /// For `v` written by `s_cselect_b32`/`_b64` or `s_cmov_b32`/`_b64`: + /// the SCC it reads and the dword it is when SCC is set, then clear. + fn picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let inst = self.def(v)?; + let Fields::Sop { dst, src, .. } = &inst.fields else { + return None; + }; + let k = inst.writes.iter().position(|w| w.1 == v)? as u8; + let wide = match inst.name() { + "s_cselect_b32" | "s_cmov_b32" => false, + "s_cselect_b64" | "s_cmov_b64" => true, + _ => return None, + }; + // A dword of a 32- or 64-bit operand: 64-bit inline integers are + // sign-extended; 64-bit literals and float constants are not + // followed. + let dword = |op: &Operand| match *op { + Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)), + Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code + k))?)), + Operand::Const(c) if !wide => inline(c).map(Term::Const), + Operand::Const(c @ 128..=208) => { + let low = inline(c)?; + Some(Term::Const(if k == 0 { + low + } else { + ((low as i32) >> 31) as u32 + })) + } + Operand::Literal(x) if !wide => Some(Term::Const(x)), + _ => None, + }; + let set = dword(src.first()?)?; + let clear = if inst.name().starts_with("s_cmov") { + dword(dst.as_ref()?)? + } else { + dword(src.get(1)?)? + }; + Some((inst.read(Reg::Scc)?, set, clear)) + } + + /// `v` as some other dword with constant bits set. + fn set_bits(&self, v: Value) -> Option<(Term, u32)> { + if let Some((_, [x, Term::Const(bits)] | [Term::Const(bits), x])) = + self.sop2(v, &["s_or_b32"]) + { + return Some((x, bits)); + } + let inst = self.def(v)?; + let Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + src, + .. + } = &inst.fields + else { + return None; + }; + match (inst.name(), self.term(inst, src.first()?)?) { + ("s_bitset1_b32", Term::Const(bit)) => { + Some((self.origin(inst.read(Reg::S(*code))?), 1 << (bit & 31))) + } + _ => None, + } + } + + /// For a `v_readfirstlane_b32` result: the VGPR value it reads. + fn first_lane_source(&self, v: Value) -> Option<Value> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if inst.name() != "v_readfirstlane_b32" || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + let Some(&Operand::Vector { reg, .. }) = f.src.first() else { + return None; + }; + inst.read(Reg::V(reg)) + } + + /// 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 + /// it, and lowering reads it per lane there. + fn first_lane_offset(&self, load: Site) -> Option<Value> { + let inst = self.inst(load); + let Fields::Smem { + base, + offset, + soffset, + .. + } = &inst.fields + else { + return None; + }; + self.read_first_lane.set(true); + let address = self.smem_address(inst, base, *offset, soffset); + self.read_first_lane.set(false); + match self.origin(address.ok()?.dynamic?) { + Term::Value(v) if self.first_lane_source(v).is_some() => Some(v), + _ => None, + } + } + + /// Whether the descriptor operand `op` of `inst` is one the code keeps + /// per lane ([`Self::lane_copies`]). + fn kept_per_lane(&self, inst: &Inst, op: &Operand) -> bool { + let Operand::Scalar { code, dwords } = *op else { + return false; + }; + (0..dwords) + .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) + .collect::<Option<Vec<_>>>() + .is_some_and(|words| self.lane_copies(&words).is_some()) + } + + /// The `v_readfirstlane_b32` results the descriptor operand `op` of + /// `inst` is, when every dword is one. + fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option<Vec<Value>> { + let Operand::Scalar { code, dwords } = *op else { + return None; + }; + (0..dwords) + .map(|k| match self.origin(inst.read(Reg::S(code + k))?) { + Term::Value(v) => self.first_lane_source(v).map(|_| v), + Term::Const(_) => None, + }) + .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 }; + let reg = match (self.inputs[v.0 as usize], self.phis[v.0 as usize]) { + (Some(reg), _) => Some(reg), + (None, Some((b, i))) => Some(self.p.blocks[b].phis[i].reg), + (None, None) => self + .def(v) + .and_then(|i| i.writes.iter().find(|w| w.1 == v)) + .map(|w| w.0), + }; + matches!(reg, Some(Reg::V(_))) + } + + /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy + /// it follows. + fn lane_value(&self, mut t: Term, known: &Known) -> Result<Term, &'static str> { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vstep(v); + if next == t { + break; + } + if self.varies(t) + && let Some(site) = self.defs[v.0 as usize] + { + self.runs(site, known)?; + } + t = next; + } + Ok(t) + } + + /// 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; + } + 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<Term> { + match *op { + Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), + } + } + + /// 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: &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.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"); + } + Ok(()) + } + + /// The source of descriptor dwords each lane holds its own of (a + /// waterfall loop reads them from the first active lane): the same in + /// every lane, loaded per lane from memory a heap address points to, or + /// picked per lane between such sources, by a lane mask or by the path + /// the lane took. `known` holds in every lane that accesses them. + fn per_lane( + &self, + words: &[Term], + joins: &mut Vec<usize>, + known: &mut Known, + ) -> Result<Source, &'static str> { + let words = words + .iter() + .map(|&w| self.lane_value(w, known)) + .collect::<Result<Vec<_>, _>>()?; + let words = &words[..]; + let Some(&lane) = words.iter().find(|&&w| self.varies(w)) else { + return self.classify(words, joins, known); + }; + if let Some(source) = self.fetched(words, known)? { + return Ok(source); + } + if let Some(source) = self.lane_select(words, joins, known)? { + return Ok(source); + } + if let Some(source) = self.lane_phi(words, joins, known)? { + return Ok(source); + } + let Term::Value(v) = lane else { unreachable!() }; + let name = self.def(v).map(|i| i.name()); + Err(match name { + _ if self.inputs[v.0 as usize].is_some() => { + "a descriptor read from the first lane of an input VGPR" + } + None => "a descriptor read from the first lane of a phi", + Some(n) if n.starts_with("ds_read") => { + "a descriptor read from the first lane of an LDS read" + } + Some(n) if n.starts_with("buffer_load") => { + "a descriptor read from the first lane of a buffer load" + } + Some(n) if n.starts_with("global_load") || n.starts_with("flat_load") => { + "a descriptor read from the first lane of a partial or mixed load" + } + Some(_) => "a descriptor read from the first lane of computed VGPRs", + }) + } + + /// Dwords of `global_load_dword*` that line up: `first..` of one load, + /// then the bytes that follow (an image descriptor takes two + /// `global_load_dwordx4`). + fn fetched(&self, words: &[Term], known: &Known) -> Result<Option<Source>, &'static str> { + let at = |w: &Term| -> Option<(Site, usize)> { + let Term::Value(v) = *w else { return None }; + let site = self.defs[v.0 as usize]?; + let inst = self.inst(site); + if !inst.name().starts_with("global_load_dword") { + return None; + } + let k = inst + .writes + .iter() + .filter(|w| matches!(w.0, Reg::V(_))) + .position(|w| w.1 == v)?; + Some((site, k)) + }; + let Some(sites) = words.iter().map(at).collect::<Option<Vec<_>>>() else { + return Ok(None); + }; + let address = |site: Site| { + let inst = self.inst(site); + let Fields::Flat { + addr, + saddr, + offset, + .. + } = &inst.fields + else { + return Err("a global load"); + }; + self.flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + }; + let (load, first) = sites[0]; + let a0 = address(load)?; + for (k, &(site, dword)) in sites.iter().enumerate() { + self.runs(site, known)?; + let a = address(site)?; + let want = a0.offset.wrapping_add(4 * (first + k) as u32); + if (a.param, a.dynamic) != (a0.param, a0.dynamic) + || a.offset.wrapping_add(4 * dword as u32) != want + { + return Err("a descriptor read from the first lane of loads that do not line up"); + } + } + Ok(Some(Source::Fetched { + load, + first: first as u8, + })) + } + + /// Words that `v_cndmask_b32` picks by one lane mask, traced per outcome + /// (other words are the same for both). + fn lane_select( + &self, + words: &[Term], + joins: &mut Vec<usize>, + known: &mut Known, + ) -> Result<Option<Source>, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.lane_picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + 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) { + if let (Term::Value(v), Some(_)) = (*w, p) + && let Some(site) = self.defs[v.0 as usize] + { + 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<Term> { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| { + let n = known.len(); + known.extend(bit.map(|b| (b, set))); + let arg = self.per_lane(&side(set), joins, known); + known.truncate(n); + arg + }) + .collect::<Result<_, _>>(); + joins.pop(); + Ok(Some(Source::Lanes { mask, args: args? })) + } + + /// For `v` written by a plain `v_cndmask_b32`: the low dword of the + /// 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 inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let Some(Operand::Vector { reg, .. }) = f.dst else { + return None; + }; + if inst.name() != "v_cndmask_b32" + || inst.write(Reg::V(reg)) != Some(v) + || f.abs != 0 + || f.neg != 0 + || f.clamp + || f.omod != 0 + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + let [clear, set, Operand::Scalar { code, .. }] = f.src[..] else { + return None; + }; + let mask = inst.read(Reg::S(code))?; + 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 + /// per-lane condition leaves them: traced on each edge into the block + /// that lanes in `known` can take (other words hold on every edge). + /// Lanes take their own paths ([`Structured`]), so each gets the value + /// of the edge it came by; an edge they cannot take is `None` (a flow + /// block's phi joins an arm's dwords with what lanes that skipped the + /// arm held before, which only they read). + fn lane_phi( + &self, + words: &[Term], + joins: &mut Vec<usize>, + known: &mut Known, + ) -> Result<Option<Source>, &'static str> { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { + return Ok(None); + }; + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { + return Err("a descriptor joined in several blocks"); + } + if joins.contains(&block) { + return Err("a descriptor that changes in a loop"); + } + let preds = &self.p.blocks[block].preds; + if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + // shortcut: what a lane holds after some passes is not traced. + return Err("a descriptor read from the first lane of a phi at a loop header"); + } + let Some(lanes) = self.lanes else { + return Err("a descriptor read from the first lane of a phi, without the lanes' paths"); + }; + // The other words must be there before the join: defined in a + // block that dominates it, which (both dominating the access) is + // one the join does not reach. + for w in words { + if let Term::Value(v) = *w + && phi_of(w).is_none() + && let Some((d, _)) = self.defs[v.0 as usize] + && (d == block || self.reaches(block, d)) + { + return Err("a descriptor partly joined by control flow"); + } + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(block); + let phis = &self.p.blocks[block].phis; + let mut args = Vec::new(); + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let arg = if self.meet(lanes, known) { + let edge: Vec<Term> = words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => Term::Value(phis[i].args[j]), + None => *w, + }) + .collect(); + self.per_lane(&edge, joins, known).map(Some) + } else { + Ok(None) + }; + known.truncate(n); + match arg { + Ok(a) => args.push(a), + Err(e) => { + joins.pop(); + return Err(e); + } + } + } + joins.pop(); + Ok(Some(Source::LanePhi { block, args })) + } + + /// Whether a path leads from block `from` to block `to` (to `from` + /// itself only through a back edge). + fn reaches(&self, from: usize, to: usize) -> bool { + let mut seen = vec![false; self.p.blocks.len()]; + let mut stack = self.p.blocks[from].exit.successors(); + while let Some(x) = stack.pop() { + if x == to { + return true; + } + if std::mem::replace(&mut seen[x], true) { + continue; + } + stack.extend(self.p.blocks[x].exit.successors()); + } + false + } + + /// Prove a single-block waterfall at the descriptor access. In each + /// iteration the access serves exactly the matching lanes, and the + /// back edge keeps exactly the other lanes active. Otherwise, why not. + /// + // shortcut: only the accesses are proven. Any other per-lane work in the + // loop is taken to run once for each lane, as the access does; a body + // whose effect adds up over the passes a lane waits through (a counter + // before the mask is narrowed) would differ. Compilers put nothing but + // the reads, the compares and the access in these loops. + fn waterfall( + &self, + b: usize, + accesses: &[usize], + reads: &[Value], + ) -> Result<Waterfall, &'static str> { + const LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + const SELECT: &str = "a waterfall loop whose compares do not select the access's lanes"; + const RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; + let access = accesses[0]; + let block = &self.p.blocks[b]; + let lanes = self.lanes.ok_or(LOOP)?; + let exit = block.insts.last().ok_or(LOOP)?; + if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) + || exit.name() != "s_cbranch_execnz" + { + return Err(LOOP); + } + let mask = |low: Option<Value>, high: Option<Value>| { + let high = if self.p.wave64 { Some(high?) } else { None }; + lanes.mask_bits(low?, high) + }; + let exec = |inst: &Inst| mask(inst.read(Reg::S(EXEC)), inst.read(Reg::S(EXEC + 1))); + // The reads belong to this loop's own block: a loop around this one + // (one per operand, as LLVM nests them for a per-lane image and + // sampler) is not followed. + if reads + .iter() + .any(|v| self.defs[v.0 as usize].is_none_or(|at| at.0 != b)) + { + return Err(SPLIT); + } + let selected = exec(&block.insts[access]).ok_or(SELECT)?; + if accesses + .iter() + .any(|&i| exec(&block.insts[i]) != Some(selected)) + { + return Err(SELECT); + } + let retry = exec(exit).ok_or(RETRY)?; + let first = self.defs[reads[0].0 as usize].ok_or(LOOP)?; + let remaining = exec(self.inst(first)).ok_or(SELECT)?; + if reads.iter().any(|v| { + self.defs[v.0 as usize] + .is_none_or(|at| at.1 >= access || exec(self.inst(at)) != Some(remaining)) + }) { + return Err(SELECT); + } + let reach = (lanes.reach[b], true); + let meet = |conditions: &[(Bool, bool)]| self.meet(lanes, conditions); + let mut out = Waterfall::default(); + let mut required = vec![(remaining, true)]; + for (i, inst) in block.insts[..access].iter().enumerate() { + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let Some(ty) = inst + .name() + .strip_prefix("v_cmp_eq_") + .or(inst.name().strip_prefix("v_cmpx_eq_")) + else { + continue; + }; + let dwords = match ty { + "u32" | "i32" => 1, + "u64" | "i64" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + // The first lane's dwords on one side, the lane's own on the + // other. + let pair = |first: &Operand, own: &Operand| -> Option<Vec<Value>> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = (first, own) + else { + return None; + }; + (0..dwords) + .map(|k| { + let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { + return None; + }; + let lane = inst.read(Reg::V(reg + k))?; + let (_, read) = self.defs[x.0 as usize]?; + let same = reads.contains(&x) + && read < i + && self.lane_term(Term::Value(self.first_lane_source(x)?)) + == self.lane_term(Term::Value(lane)); + same.then_some(x) + }) + .collect() + }; + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + continue; + }; + if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { + let code = if inst.name().starts_with("v_cmpx_") { + EXEC + } else if let Some(Operand::Scalar { code, .. }) = f.dst { + code + } else { + continue; + }; + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else { + continue; + }; + if meet(&[reach, (selected, true), (matched, false)]) { + continue; + } + required.push((matched, true)); + out.compares.push((b, i)); + for x in xs { + if !out.reads.contains(&x) { + out.reads.push(x); + } + } + } + } + if reads.iter().any(|v| !out.reads.contains(v)) + || meet(&[reach, (selected, true), (remaining, false)]) + { + return Err(SELECT); + } + // The access must take every match. + required.extend([reach, (selected, false)]); + if meet(&required) { + return Err(SELECT); + } + // The retry must keep exactly the lanes that were eligible but did + // not perform the access. + if meet(&[reach, (retry, true), (remaining, false)]) + || meet(&[reach, (retry, true), (selected, true)]) + || meet(&[reach, (remaining, true), (selected, false), (retry, false)]) + { + return Err(RETRY); + } + Ok(out) + } + + /// Consecutive dwords of one scalar load. + fn loaded(&self, words: &[Term]) -> Option<Source> { + let Term::Value(v0) = words[0] else { + return None; + }; + let load = self.defs[v0.0 as usize]?; + let inst = self.inst(load); + if !inst.name().starts_with("s_load_") { + return None; + } + let first = inst.writes.iter().position(|w| w.1 == v0)?; + let same = words.iter().enumerate().all(|(k, w)| { + inst.writes + .get(first + k) + .is_some_and(|x| *w == Term::Value(x.1)) + }); + same.then_some(Source::Loaded { + load, + first: first as u8, + }) + } + + /// A descriptor the code keeps per lane: every dword of `words` is the + /// first lane (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled + /// from SGPRs. The console compiler does this to a descriptor loaded on + /// both sides of a per-lane branch: the join is per lane, so it lives in + /// VGPRs, and the instruction that needs it in SGPRs runs in a loop over + /// the distinct values (the first lane's, the lanes holding the same, + /// then the rest). When every scalar those moves copy is the same dword + /// of loads from one constant address, the lanes agree and the + /// descriptor is any of those loads. + // shortcut: what else the VGPRs held (numbers, on paths or in lanes that + // never read them as a descriptor) is ignored, and a move is taken to + // leave either its source or what a move before it wrote; a descriptor + // read per lane from memory (`global_load_*`) refuses. + fn lane_copies(&self, words: &[Term]) -> Option<Source> { + let mut loads: Vec<Site> = Vec::new(); + let mut first = None; + for (k, w) in words.iter().enumerate() { + let Term::Value(v) = *w else { return None }; + let mut copies = Vec::new(); + if !self.scalar_copies(self.first_lane(v)?, &mut copies) { + return None; + } + let mut found = false; + for c in copies { + let Term::Value(c) = c else { continue }; + let Some(site) = self.defs[c.0 as usize] else { + continue; + }; + let load = self.inst(site); + if !load.name().starts_with("s_load_") { + continue; + } + // Dword k of the operand is dword `first + k` of each load. + let dword = load.writes.iter().position(|x| x.1 == c)?; + let f = dword.checked_sub(k)?; + if *first.get_or_insert(f) != f { + return None; + } + if !loads.contains(&site) { + loads.push(site); + } + found = true; + } + if !found { + return None; + } + } + let address = |site: Site| { + let inst = self.inst(site); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self.smem_address(inst, base, *offset, soffset).ok(), + _ => None, + } + }; + let a = address(*loads.first()?)?; + if a.dynamic.is_some() || loads.iter().any(|&l| address(l) != Some(a)) { + return None; + } + // The handle is made where the descriptor is used, from the load's + // operands: take a load whose base is the root parameter's own SGPR. + loads.sort_unstable(); + let load = *loads.iter().find(|&&l| self.base_from_entry(l))?; + self.lane_copied.borrow_mut().extend(&loads); + Some(Source::Loaded { + load, + first: first? as u8, + }) + } + + /// The scalars (as origins) that `v_mov_b32` copies put in VGPR value + /// `v`, through joins, moves between VGPRs and per-lane selects; a move + /// keeps what it wrote over in the lanes it does not run. False if the + /// VGPR may hold something read per lane from memory. + fn scalar_copies(&self, v: Value, out: &mut Vec<Term>) -> bool { + let (mut seen, mut work) = (Vec::new(), vec![v]); + while let Some(v) = work.pop() { + if seen.contains(&v) { + continue; + } + if seen.len() == MAX_COPIES { + return false; + } + seen.push(v); + if let Some((b, i)) = self.phis[v.0 as usize] { + work.extend(&self.p.blocks[b].phis[i].args); + continue; + } + // An entry value, or a number some instruction computed. + let Some(inst) = self.def(v) else { continue }; + if inst.name().starts_with("global_load_") { + return false; + } + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let sources = match inst.name() { + "v_mov_b32" => 1, + "v_cndmask_b32" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + for op in f.src.iter().take(sources) { + match *op { + Operand::Vector { reg, .. } => work.extend(inst.read(Reg::V(reg))), + Operand::Scalar { code, .. } if code != NULL => { + out.extend(inst.read(Reg::S(code)).map(|s| self.origin(s))); + } + _ => {} + } + } + // Lanes outside EXEC keep the old value. + if let Some(Operand::Vector { reg, .. }) = f.dst { + work.extend(inst.read(Reg::V(reg))); + } + } + true + } + + /// The load at `site` has a constant offset and takes its base from a + /// root parameter's SGPR through moves alone: a value that exists + /// wherever the descriptor is used. + fn base_from_entry(&self, site: Site) -> bool { + let inst = self.inst(site); + let Fields::Smem { + base: Operand::Scalar { code, .. }, + soffset: Operand::Scalar { code: NULL, .. }, + .. + } = &inst.fields + else { + return false; + }; + let Some(mut v) = inst.read(Reg::S(*code)) else { + return false; + }; + loop { + if self.inputs[v.0 as usize].is_some() { + return true; + } + let Some(def) = self.def(v) else { return false }; + let Some(k) = def.writes.iter().position(|w| w.1 == v) else { + return false; + }; + match copy_source(def, k) { + Some(Moved::Value(s)) => v = s, + _ => return false, + } + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Moved { + Const(u32), + Value(Value), +} + +impl Tracer<'_> { + /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that + /// lane, found by following the VGPR's `v_writelane_b32` writes. + fn restored(&self, inst: &Inst) -> Option<Moved> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + if inst.name() != "v_readlane_b32" { + return None; + } + let [Operand::Vector { reg, .. }, lane] = v.src[..] else { + return None; + }; + self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + .ok() + .flatten() + } + + /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in + /// `seen` (already being resolved), `Err` if not a spilled SGPR. + fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> { + if let Some((b, i)) = self.phis[v.0 as usize] { + if seen.contains(&v) { + return Ok(None); + } + seen.push(v); + let mut found = None; + for &a in &self.p.blocks[b].phis[i].args { + if let Some(m) = self.spilled(a, lane, seen)? { + if found.is_some_and(|f| f != m) { + return Err(()); + } + found = Some(m); + } + } + return Ok(found); + } + let inst = self.def(v).ok_or(())?; + let Fields::Valu(w) = &inst.fields else { + return Err(()); + }; + let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { + return Err(()); + }; + if inst.name() != "v_writelane_b32" { + return Err(()); + } + if lane_of(*at).ok_or(())? != lane { + return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); + } + match *value { + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).map(Moved::Value) + } + Operand::Literal(x) => Some(Moved::Const(x)), + Operand::Const(c) => inline(c).map(Moved::Const), + _ => None, + } + .map(Some) + .ok_or(()) + } +} + +/// A lane select given as a constant. +fn lane_of(op: Operand) -> Option<u32> { + match op { + Operand::Const(c) => inline(c), + Operand::Literal(x) => Some(x), + _ => None, + } +} + +/// What dword `k` of a move's result copies. +fn copy_source(inst: &Inst, k: usize) -> Option<Moved> { + let Fields::Sop { src, imm, .. } = &inst.fields else { + return None; + }; + if inst.name() == "s_movk_i32" { + return Some(Moved::Const(i32::from((*imm)? as i16) as u32)); + } + let src = src.first()?; + match (inst.name(), *src) { + ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => { + inst.read(Reg::S(code + k as u8)).map(Moved::Value) + } + ("s_mov_b32" | "s_mov_b64", Operand::Scalar { .. }) => Some(Moved::Const(0)), + ("s_mov_b32", Operand::Literal(x)) => Some(Moved::Const(x)), + ("s_mov_b32", Operand::Const(c)) => inline(c).map(Moved::Const), + // shortcut: only the one-operand ways the compiler makes a constant + // that has no inline form; fold more if descriptors need it. + ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())), + ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)), + // 64-bit inline integers are sign-extended. + ("s_mov_b64", Operand::Const(c @ 128..=208)) => { + let low = inline(c)?; + Some(Moved::Const(if k == 0 { + low + } else { + ((low as i32) >> 31) as u32 + })) + } + _ => None, + } +} + +/// The 32-bit value of an inline constant operand. +pub(crate) fn inline(code: u8) -> Option<u32> { + let float = |f: f32| Some(f.to_bits()); + match code { + 128..=192 => Some(u32::from(code) - 128), + 193..=208 => Some((192 - i32::from(code)) as u32), + 240 => float(0.5), + 241 => float(-0.5), + 242 => float(1.0), + 243 => float(-1.0), + 244 => float(2.0), + 245 => float(-2.0), + 246 => float(4.0), + 247 => float(-4.0), + 248 => Some(0x3E22_F983), + _ => None, + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::native::RootType::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn track_words(words: &[u32], layout: &[RootParam], stage: HwStage) -> Resources { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + track(&p, layout, stage, lanes(&p).as_ref()).unwrap() + } + + /// `p` as one lane runs it, if it structures. + fn lanes(p: &Program) -> Option<Structured> { + crate::structure::structure(p).ok() + } + + fn param(root: RootType, user_data: u8, sgprs: u32) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot: 0, + } + } + + fn at(param: usize, offset: u32) -> Address { + Address { + param, + offset, + dynamic: None, + } + } + + #[test] + fn table_descriptors_are_loaded_from_their_range() { + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0204, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[8:9], null + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xF080_0F08, + 0x0040_0002, // image_sample v[0:3], v[2:3], s[0:7], s[8:11] + S_ENDPGM, + ], + &[param(Table, 8, 1), param(Table, 9, 1)], + HwStage::Ps, + ); + assert_eq!(r.scalar, [((0, 3), at(0, 0)), ((0, 4), at(1, 0))]); + let roles: Vec<_> = r.descriptors.iter().map(|d| (d.role, &d.source)).collect(); + assert_eq!( + roles, + [ + ( + Role::Resource, + &Source::Loaded { + load: (0, 4), + first: 0 + } + ), + ( + Role::Sampler, + &Source::Loaded { + load: (0, 3), + first: 0 + } + ), + ] + ); + } + + #[test] + fn root_descriptors_are_built_in_code() { + let r = track_words( + &[ + 0x8801_FF0B, + 0x0010_0000, // s_or_b32 s1, s11, 0x100000 + 0xBE80_030A, // s_mov_b32 s0, s10 + 0xBE82_03C1, // s_mov_b32 s2, -1 + 0xBE83_03FF, + 0x1101_4FAC, // s_mov_b32 s3, 0x11014fac + 0xF430_0000, + 0xFA00_0000, // s_buffer_load_dwordx16 s[0:15], s[0:3], null + S_ENDPGM, + ], + &[param(Descriptor, 10, 2)], + HwStage::Vs, + ); + assert_eq!( + r.descriptors[0].source, + Source::Built { + address: at(0, 0), + bits: 0x10_0000, + words: [u32::MAX, 0x1101_4FAC] + } + ); + assert_eq!( + r.params.iter().map(|p| (p.1, p.2)).collect::<Vec<_>>(), + [(0, 0), (0, 1)] + ); + } + + #[test] + fn heap_indices_from_root_constants_in_a_merged_stage() { + // User data starts at s8: the constant (index 6) is s14, the heap + // (index 10) s18. + let code = [ + 0x8F08_850E, // s_lshl_b32 s8, s14, 5 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0xF408_0209, + 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8 + 0xE000_2000, + 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen + S_ENDPGM, + ]; + let r = track_words( + &code, + &[param(Constants, 6, 1), param(ResourceHeap, 10, 1)], + HwStage::Ms, + ); + let index = r.params.iter().find(|p| p.1 == 0).unwrap().0; + let shift = r.scalar[0].1.dynamic.unwrap(); + assert_eq!(r.scalar[0].1.param, 1); + // The computed term is the shifted constant, not the constant itself. + assert_ne!(shift, index); + assert_eq!( + r.descriptors[0].source, + Source::Loaded { + load: (0, 2), + first: 0 + } + ); + assert!(r.root_indexed_views.is_empty()); + let table = RootParam { + slot: 7, + ..param(Table, 10, 1) + }; + let indexed = track_words(&code, &[param(Constants, 6, 1), table], HwStage::Ms); + assert_eq!( + indexed.root_indexed_views, + [RootIndexedView { + table_slot: 7, + constant_slot: 0, + constant_dword: 0, + byte_offset: 0, + shift: 5, + }] + ); + let nonconstant = track_words(&code, &[param(Table, 6, 1), table], HwStage::Ms); + assert!(nonconstant.root_indexed_views.is_empty()); + } + + #[test] + fn spilled_sgprs_are_followed_through_vgpr_lanes() { + let r = track_words( + &[ + 0xD761_0000, + 0x0001_0609, // v_writelane_b32 v0, s9, 3 + 0xD760_0002, + 0x0001_0700, // v_readlane_b32 s2, v0, 3 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]); + } + + #[test] + fn descriptors_joined_by_control_flow_are_traced_per_edge() { + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0003, // s_cbranch_scc1 -> 0x1c + 0xF408_0001, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[2:3], null + 0xBF82_0002, // s_branch -> 0x24 + 0xF408_0001, + 0xFA00_0010, // 0x1c: s_load_dwordx4 s[0:3], s[2:3], 0x10 + 0xF420_0100, + 0xFA00_0000, // 0x24: s_buffer_load_dword s4, s[0:3], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let Source::Phi { args, .. } = &r.descriptors[0].source else { + panic!("{:?}", r.descriptors) + }; + let offsets: Vec<_> = args + .iter() + .map(|a| match a { + Source::Loaded { load, .. } => { + r.scalar.iter().find(|s| s.0 == *load).unwrap().1.offset + } + a => panic!("{a:?}"), + }) + .collect(); + assert_eq!(offsets.len(), 2); + assert!( + offsets.contains(&0) && offsets.contains(&0x10), + "{offsets:?}" + ); + } + + /// Two paths add an index to one table in the code and meet before one load + /// (hair `CS_InterpolateStrands`): the join is the computed term, counted + /// from the `s_getpc_b64`. + #[test] + fn two_paths_into_one_code_table_load() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0x8002_FF02, + 0x0000_0040, // s_add_u32 s2, s2, 0x40 + 0x8203_8003, // s_addc_u32 s3, s3, 0 + 0xBF06_8001, // 0x10: s_cmp_eq_u32 s1, 0 + 0xBF85_0005, // 0x14: s_cbranch_scc1 -> 0x2c + 0xD70F_0457, + 0x0000_054A, // 0x18: v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xBF82_0004, // 0x28: s_branch -> 0x3c + 0xD70F_0457, + 0x0000_054B, // 0x2c: v_add_co_u32 v87, s4, v75, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xDC34_8000, + 0x577D_0057, // 0x3c: global_load_dwordx2 v[87:88], v[87:88], null + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + 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"); + } + + /// An address into a table in the code computed per lane and taken from + /// the first lane (`avgLuminanceCompute` `ColorDownsample`): the per-lane + /// sum carries the `s_getpc_b64` base, so the first-lane read is looked + /// through and the lane's index is the computed term. (A first-lane read + /// of an index alone stays the computed term itself; see + /// `the_console_waterfall_over_a_first_lane_offset_is_one`.) + #[test] + fn a_code_table_address_taken_from_the_first_lane() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0xD70F_0457, + 0x0000_054A, // v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0x7E0C_0557, // v_readfirstlane_b32 s6, v87 + 0x7E0E_0558, // v_readfirstlane_b32 s7, v88 + 0xF400_0203, + 0xFA00_0000, // s_load_dword s8, s[6:7], 0x0 + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + let a = r.scalar[0].1; + assert_eq!((a.param, a.offset), (CODE, 4)); + assert!(a.dynamic.is_some(), "the lane's index is the computed term"); + } + + #[test] + fn a_descriptor_kept_per_lane_is_its_load_and_needs_no_waterfall() { + // The console compiler's way with a descriptor it joins per lane: + // the dwords go to VGPRs and come back from the first lane. Every + // lane holds the one load's dwords, so the descriptor is that load + // (`lane_copied`), and no waterfall is asked for. + let mut words = vec![ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + ]; + // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10.. + words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k)); + words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | (0x100 + 10 + k))); + words.extend([ + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ]); + let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps); + let load = (0, 2); + assert_eq!(r.scalar, [(load, at(0, 0))]); + let sources: Vec<_> = r.descriptors.iter().map(|d| &d.source).collect(); + assert_eq!(sources, [&Source::Loaded { load, first: 0 }]); + assert_eq!(r.lane_copied, [load]); + assert_eq!(r.waterfall, Waterfall::default()); + } + + #[test] + fn loads_at_one_first_lane_offset_have_one_address() { + // Two loads of the table entry at the offset v4 holds, each with + // its own first-lane read, as the console compiler loads a + // descriptor again wherever it needs it: one address, by which + // lowering knows them for the same descriptor. + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0x7E08_0504, // v_readfirstlane_b32 s4, v4 + 0xF40C_0201, + 0x0800_0000, // s_load_dwordx8 s[8:15], s[2:3], s4 + 0x7E0A_0504, // v_readfirstlane_b32 s5, v4 + 0xF40C_0401, + 0x0A00_0000, // s_load_dwordx8 s[16:23], s[2:3], s5 + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let [(_, a), (_, b)] = r.scalar[..] else { + panic!("{:?}", r.scalar) + }; + assert_eq!(a, b); + assert_eq!((a.param, a.offset), (0, 0)); + assert!( + a.dynamic.is_some(), + "the lane's offset is the computed term" + ); + } + + #[test] + fn descriptors_selected_by_scc_are_traced_per_outcome() { + // Two buffer descriptors loaded from the table at s9 and one + // picked with s_cselect_b64 per half, as the compiler makes a + // conditional choice of resources without a branch. + let r = track_words( + &[ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0602, // s_cselect_b64 s[10:11], s[2:3], s[6:7] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let Source::Select { args, .. } = &r.descriptors[0].source else { + panic!("{:?}", r.descriptors) + }; + // SCC set picks the first operand. + assert_eq!( + args[..], + [ + Source::Loaded { + load: (0, 2), + first: 0 + }, + Source::Loaded { + load: (0, 3), + first: 0 + }, + ] + ); + assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]); + } + + #[test] + fn a_selection_that_mixes_two_descriptors_fails() { + // The high half picked from the first load whatever SCC is: when + // clear, the descriptor is half of one load and half of the other. + let code: Vec<u8> = [ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0202, // s_cselect_b64 s[10:11], s[2:3], s[2:3] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 36, + what: "a descriptor changed after loading" + } + ); + } + + #[test] + fn untraceable_addresses_fail_with_a_reason() { + let code: Vec<u8> = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 0, + what: "an address in an SGPR that is no root parameter" + } + ); + } + + /// 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 + /// first active lane's descriptor into s[12:19], samples with the lanes + /// whose descriptor it is, and repeats for the others. The sampler comes + /// from the table at s1; the result goes to LDS so the sample is needed. + pub(crate) const WATERFALL_FETCHED_WAVE32: &[u32] = &[ + 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 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// [`WATERFALL_FETCHED_WAVE32`] in wave64: 64-bit lane masks. + pub(crate) const WATERFALL_FETCHED_WAVE64: &[u32] = &[ + 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 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_047E, // s_mov_b64 s[20:21], exec + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0016, + 0x0002_080C, // v_cmp_eq_u64_e64 s[22:23], s[12:13], v[4:5] + 0xD4E2_0018, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s[24:25], s[14:15], v[6:7] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1010, // v_cmp_eq_u64_e64 s[24:25], s[16:17], v[8:9] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1412, // v_cmp_eq_u64_e64 s[24:25], s[18:19], v[10:11] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xBE96_2416, // s_and_saveexec_b64 s[22:23], s[22:23] + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x89FE_167E, // s_xor_b64 exec, exec, s[22:23] + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0414, // s_mov_b64 exec, s[20:21] + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// The same waterfall over one of two image descriptors loaded from the + /// table at s0, picked per lane by `v_cndmask_b32` (lanes below 16 take + /// the first). + pub(crate) const WATERFALL_PICKED_WAVE32: &[u32] = &[ + 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_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x7c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x7c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// The waterfall loop of [`WATERFALL_PICKED_WAVE32`] over one of two + /// image descriptors loaded from the table at s0, chosen by control flow + /// as the compiler lowers an if/else on a per-lane condition: lanes below + /// 16 move the first into v[4:11], the others the second, each arm + /// skipped when no lane takes it. The sample goes to the buffer at dword + /// 16 of the table, at lane * 4. + pub(crate) const WATERFALL_JOINED_WAVE32: &[u32] = &[ + 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_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 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_0008, // s_cbranch_execz -> 0x70 + 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 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBE94_3D14, // 0x70: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0008, // s_cbranch_execz -> 0x9c + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0x887E_147E, // 0x9c: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0xa4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xa4 + 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 + ]; + + /// The console compiler's waterfall (Grand Theft Auto VI'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 + /// (`v_cmpx_eq_u32`), loads that entry with `s_load_dwordx8` and samples, + /// then drops those lanes (`s_andn2_wrexec_b32`). The sample goes to the + /// buffer at dword 16 of the table, at lane * 4. + pub(crate) const WATERFALL_INDEXED_WAVE32: &[u32] = &[ + 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 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E_0081, // v_and_b32 v7, 1, v0 + 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // 0x40: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF6, // s_cbranch_execnz -> 0x40 + 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 + ]; + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_is_one() { + let r = waterfall(WATERFALL_INDEXED_WAVE32, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Loaded { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + let (_, address) = r.scalar.iter().find(|s| s.0 == load).unwrap(); + assert!(address.dynamic.is_some(), "{address:?}"); + assert_eq!(r.waterfall.compares.len(), 1); + assert_eq!(r.waterfall.reads.len(), 1); + assert_eq!(r.waterfall.loads, [load]); + } + + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes + /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, + /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the + /// first entry, the rest the second). + pub(crate) const WATERFALL_JOINED_MIXED_WAVE32: &[u32] = &[ + 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_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 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 -> 0x68 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xBE94_3D14, // 0x68: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0011, // s_cbranch_execz -> 0xb8 + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0x887E_147E, // 0xb8: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x7E18_0504, // 0xc4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xc4 + 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 + ]; + + /// A waterfall loop whose descriptor changes on each pass: v[4:11] holds + /// the first table entry on entry and the second after every pass, so + /// the first lane's dwords are phis of the loop header. + pub(crate) const WATERFALL_LOOPED_WAVE32: &[u32] = &[ + 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_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 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 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0x64: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0xBF89_FFDE, // s_cbranch_execnz -> 0x64 + 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 + ]; + + /// A waterfall loop over one of two buffer descriptors (four dwords) + /// loaded from the table at s0, chosen by nested if/else: lanes below 16 + /// move the first into v[4:7], lanes from 16 to 23 the second, and the + /// others keep what v[4:7] held. Only lanes below 24 (the same mask) + /// run the loop, which loads dword `lane` of the chosen buffer, and + /// store it to the buffer at dword 16 of the table. + pub(crate) const WATERFALL_JOINED_BUFFER_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0602, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xF408_0802, + 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xD4C4_001E, + 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, 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 -> 0x50 + 0x7E08_0218, // 0x40: 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, // 0x50: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0007, // s_cbranch_execz -> 0x78 + 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30 + 0xBF88_0004, // s_cbranch_execz -> 0x74 + 0x7E08_0220, // 0x64: v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x887E_1F7E, // 0x74: s_or_b32 exec_lo, exec_lo, s31 + 0x887E_147E, // 0x78: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30 + 0xBF88_0013, // s_cbranch_execz -> 0xd0 + 0xBE9D_037E, // s_mov_b32 s29, exec_lo + 0x7E18_0504, // 0x88: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xE030_1000, + 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF1, // s_cbranch_execnz -> 0x88 + 0xBEFE_031D, // s_mov_b32 exec_lo, s29 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0x887E_177E, // 0xd0: s_or_b32 exec_lo, exec_lo, s23 + 0xBF81_0000, // s_endpgm + ]; + + fn waterfall(words: &[u32], wave64: bool) -> Result<Resources, ShaderError> { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, wave64, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + track(&p, &layout, HwStage::Cs, lanes(&p).as_ref()) + } + + #[test] + fn descriptors_read_from_the_first_lane_of_per_lane_loads_are_traced_to_them() { + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + ] { + let r = waterfall(words, wave64).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Fetched { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + // The first of the two loads: entry v0 * 32 of the table at s0. + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The sampler is the same for every lane. + let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler); + assert!(matches!( + sampler.unwrap().source, + Source::Loaded { first: 0, .. } + )); + // Four 64-bit compares of the first lane's dwords with the lane's + // own; the eight reads become the lane's own dwords. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_a_per_lane_choice_are_traced_per_lane() { + let r = waterfall(WATERFALL_PICKED_WAVE32, false).unwrap(); + let image = &r.descriptors[0]; + let Source::Lanes { args, .. } = &image.source else { + panic!("{:?}", image.source) + }; + // Lanes with their bit set take the first load (offset 0), the + // others the second (0x20). + let offsets: Vec<u32> = args + .iter() + .map(|a| match *a { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|s| s.0 == load).unwrap().1.offset + } + ref a => panic!("{a:?}"), + }) + .collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn a_first_lane_read_outside_a_loop_is_no_waterfall() { + // The waterfall without its back edge: the s_cbranch_execnz is an + // s_nop, so lanes the first one does not match never get a pass. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let back = words.iter().position(|&w| w == 0xBF89_FFE6).unwrap(); + words[back] = 0xBF80_0000; + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + ), + "{err:?}" + ); + } + + /// Why resource tracking refuses `words`. + fn refusal(words: &[u32], wave64: bool) -> &'static str { + match waterfall(words, wave64) { + Err(ShaderError::Unsupported { what, .. }) => what, + other => panic!("not refused: {other:?}"), + } + } + + const NO_LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const NOT_SELECTED: &str = "a waterfall loop whose compares do not select the access's lanes"; + const BAD_RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + + /// The index of `word` in `words`. + fn word_at(words: &[u32], word: u32) -> usize { + words.iter().position(|&w| w == word).unwrap() + } + + #[test] + fn a_first_lane_read_without_its_compare_is_no_waterfall() { + // The loop without the compare of dwords 0 and 1: nothing makes + // the first lane's dwords the lane's own there. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let cmp = word_at(&words, 0x0002_080C); + words[cmp - 1..=cmp].copy_from_slice(&[0xBF80_0000, 0xBF80_0000]); + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn a_compare_that_does_not_mask_the_access_is_no_waterfall() { + // The compares are all there, but their result never narrows EXEC: + // every lane samples with the first lane's descriptor (reported by + // ifBars on upstream PR #566). + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let save = word_at(&words, 0xBE95_3C15); + words[save] = 0xBE95_037E; // s_mov_b32 s21, exec_lo + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn an_access_under_a_further_mask_is_no_waterfall() { + // The access runs for the matching lanes that VCC also holds, yet + // the retry removes every matching lane. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let nop = word_at(&words, 0xBE95_3C15) + 1; + assert_eq!(words[nop], 0xBF80_0000); + words[nop] = 0x877E_6A7E; // s_and_b32 exec_lo, exec_lo, vcc_lo + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn a_loop_that_drops_unmatched_lanes_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = word_at(&words, 0x897E_157E); + words[retry] = 0xBEFE_0380; // s_mov_b32 exec_lo, 0 + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_retry_that_keeps_other_lanes_than_those_waiting_is_no_waterfall() { + // The retry keeps the lanes of VCC that did not just sample, not + // the waiting ones: lanes 16 and up never sample on the console. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = word_at(&words, 0x897E_157E); + words[retry] = 0x8A7E_7E6A; // s_andn2_b32 exec_lo, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_wave64_retry_of_one_half_is_no_waterfall() { + // Only the low half of EXEC loses the lanes just served. + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let retry = word_at(&words, 0x89FE_167E); + words[retry] = 0x897E_167E; // s_xor_b32 exec_lo, exec_lo, s22 + assert_eq!(refusal(&words, true), BAD_RETRY); + } + + #[test] + fn a_descriptor_used_after_exec_is_restored_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let sample = word_at(&words, 0xF09C_0F08); + let restore = word_at(&words, 0xBEFE_0317); + let image = [words[sample], words[sample + 1]]; + words[sample..sample + 2].fill(0xBF80_0000); // Keep the branch offsets. + words.splice(restore + 1..restore + 1, image); + assert_eq!(refusal(&words, false), NO_LOOP); + } + + #[test] + fn a_wave64_access_with_exec_hi_overwritten_is_no_waterfall() { + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let save = word_at(&words, 0xBE96_2416); + words[save + 1] = 0xBEFF_03C1; // s_mov_b32 exec_hi, -1 + assert_eq!(refusal(&words, true), NOT_SELECTED); + } + + /// The waterfall with `v_cmpx_eq` narrowing EXEC itself, and the retry + /// as `todo & !EXEC` (`folded`: in one `s_andn2_wrexec`), as LLVM's + /// AMDGPU backend writes it for GFX10 and later. + pub(crate) fn cmpx_waterfall(wave64: bool, folded: bool) -> Vec<u32> { + let (base, todo, restore): (&[u32], u32, u32) = if wave64 { + (WATERFALL_FETCHED_WAVE64, 0xBE94_047E, 0xBEFE_0414) + } else { + (WATERFALL_JOINED_WAVE32, 0xBE97_037E, 0xBEFE_0317) + }; + let reads = word_at(base, 0x7E18_0504); + let sample = word_at(base, 0xF09C_0F08); + let mut w = base[..=word_at(base, todo)].to_vec(); + // s_mov_b32 s21, exec_lo / s_mov_b64 s[22:23], exec + w.push(if wave64 { 0xBE96_047E } else { 0xBE95_037E }); + w.extend(&base[reads..reads + 8]); // v_readfirstlane_b32 s12..s19 + w.extend([ + 0x7DE4_080C, // v_cmpx_eq_u64 s[12:13], v[4:5] + 0x7DE4_0C0E, // v_cmpx_eq_u64 s[14:15], v[6:7] + 0x7DE4_1010, // v_cmpx_eq_u64 s[16:17], v[8:9] + 0x7DE4_1412, // v_cmpx_eq_u64 s[18:19], v[10:11] + ]); + w.extend(&base[sample..sample + 2]); // image_sample_lz + match (wave64, folded) { + // s_andn2_wrexec_b32 s21, s21; s_cbranch_execnz + (false, true) => w.extend([0xBE95_4715, 0xBF89_FFF0]), + // s_andn2_b32 s21, s21, exec_lo; s_mov_b32 exec_lo, s21 + (false, false) => w.extend([0x8A15_7E15, 0xBEFE_0315, 0xBF89_FFEF]), + // s_andn2_wrexec_b64 s[22:23], s[22:23] + (true, true) => w.extend([0xBE96_3A16, 0xBF89_FFF0]), + // s_andn2_b64 s[22:23], s[22:23], exec; s_mov_b64 exec, s[22:23] + (true, false) => w.extend([0x8A96_7E16, 0xBEFE_0416, 0xBF89_FFEF]), + } + w.extend(&base[word_at(base, restore)..]); + w + } + + #[test] + fn a_waterfall_narrowed_by_v_cmpx_is_one() { + for wave64 in [false, true] { + for folded in [false, true] { + let r = waterfall(&cmpx_waterfall(wave64, folded), wave64) + .unwrap_or_else(|e| panic!("wave64 {wave64} folded {folded}: {e:?}")); + assert_eq!(r.waterfall.compares.len(), 4, "{wave64} {folded}"); + assert_eq!(r.waterfall.reads.len(), 8, "{wave64} {folded}"); + } + } + } + + #[test] + fn a_v_cmpx_waterfall_whose_retry_drops_lanes_is_none() { + let mut words = cmpx_waterfall(false, false); + let retry = word_at(&words, 0x8A15_7E15); + words[retry] = 0x8A15_7E6A; // s_andn2_b32 s21, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_waterfall_nested_in_another_is_refused_by_name() { + // An image whose resource and sampler are both per lane, with one + // loop per operand, the one for the sampler inside the one for the + // resource (what the SelectionDAG legalisation in LLVM would give). + // The console gives each lane its own pair. Refused for now: the + // access of the inner loop reads the first-lane dwords of the outer + // loop, which another block holds. + let words = [ + 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 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 0x3622_0080, // v_and_b32 v17, 0, v0 + 0x3422_2284, // v_lshlrev_b32 v17, 4, v17 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xDC38_8000, + 0x1406_0011, // global_load_dwordx4 v[20:23], v17, s[6:7] + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + // L1, the loop over the resource: + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, + 0x7E1C_0506, + 0x7E1E_0507, + 0x7E20_0508, + 0x7E22_0509, + 0x7E24_050A, + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + // L2, the loop over the sampler: + 0x7E10_0514, // v_readfirstlane_b32 s8, v20 + 0x7E12_0515, // v_readfirstlane_b32 s9, v21 + 0x7E14_0516, // v_readfirstlane_b32 s10, v22 + 0x7E16_0517, // v_readfirstlane_b32 s11, v23 + 0xD4E2_0018, + 0x0002_2808, // v_cmp_eq_u64_e64 s24, s[8:9], v[20:21] + 0xD4E2_0019, + 0x0002_2C0A, // v_cmp_eq_u64_e64 s25, s[10:11], v[22:23] + 0x8718_1918, // s_and_b32 s24, s24, s25 + 0xBE98_3C18, // s_and_saveexec_b32 s24, s24 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0x897E_187E, // s_xor_b32 exec_lo, exec_lo, s24 + 0xBF89_FFF2, // s_cbranch_execnz L2 + 0xBEFE_031A, // s_mov_b32 exec_lo, s26 + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFDA, // s_cbranch_execnz L1 + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + assert_eq!(refusal(&words, false), SPLIT); + } + + #[test] + fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() { + // The waterfall over descriptors each lane read from LDS: + // ds_read_b128 v[4:7], v1 and ds_read_b128 v[8:11], v1 offset:16 + // in place of the global loads. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + words[5..9].copy_from_slice(&[0xDBFC_0000, 0x0400_0001, 0xDBFC_0010, 0x0800_0001]); + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of an LDS read", + .. + } + ), + "{err:?}" + ); + } + + /// The block of `p` at byte `offset`. + fn block_at(words: &[u32], offset: usize) -> usize { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + p.blocks.iter().position(|b| b.offset == offset).unwrap() + } + + /// The table offset of what the scalar load of `s` reads. + fn table_offset(r: &Resources, s: &Source) -> u32 { + match *s { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|x| x.0 == load).unwrap().1.offset + } + ref s => panic!("{s:?}"), + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_an_if_else_join_are_traced_per_path() { + let words = WATERFALL_JOINED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The join after the else arm: lanes that ran it (lanes from 16 on) + // take the second entry (0x20); the others come through the flow + // block, whose join gives lanes that ran the then arm the first one + // (0). No lane that skipped the then arm comes that way, so the + // dwords they held before (the inputs) are not traced. + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x9c)); + let [Some(flow), Some(other)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + let Source::LanePhi { block, args } = flow else { + panic!("{flow:?}") + }; + assert_eq!(*block, block_at(words, 0x70)); + let [None, Some(then)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // The loop's compares are of the joined dwords; still recognised. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + // Without the lanes' paths the join is refused. + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + let err = track(&p, &layout, HwStage::Cs, None).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi, without the lanes' paths", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn descriptors_joined_from_a_per_lane_load_and_a_per_lane_choice_are_traced_per_path() { + let words = WATERFALL_JOINED_MIXED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0xb8)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::Lanes { args: picked, .. }), + ] = &args[..] + else { + panic!("{args:?}") + }; + // The then arm loads each lane's entry from the table at s0. + let [None, Some(Source::Fetched { load, first: 0 })] = flow[..] else { + panic!("{flow:?}") + }; + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The else arm picks the first entry where vcc is set. + let offsets: Vec<u32> = picked.iter().map(|s| table_offset(&r, s)).collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn a_descriptor_read_from_the_first_lane_of_a_loop_phi_fails_naming_it() { + let err = waterfall(WATERFALL_LOOPED_WAVE32, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi at a loop header", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_per_lane_descriptor_some_lanes_do_not_write_fails() { + // The else arm of WATERFALL_JOINED_WAVE32 not skipped (its + // s_cbranch_execz an s_nop): it runs with EXEC clear in the lanes + // of the then arm, which keep the first entry; the second is not + // every lane's. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let skip = words.iter().rposition(|&w| w == 0xBF88_0008).unwrap(); + words[skip] = 0xBF80_0000; + 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 a_buffer_descriptor_joined_per_lane_is_traced_on_the_paths_of_lanes_that_load() { + let words = WATERFALL_JOINED_BUFFER_WAVE32; + let r = waterfall(words, false).unwrap(); + let buffer = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The outer join: lanes from the else arm's inner join, or (below + // 16) through the flow block. + let Source::LanePhi { block, args } = &buffer.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x78)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::LanePhi { + block: inner, + args: nested, + }), + ] = &args[..] + else { + panic!("{args:?}") + }; + let [None, Some(then)] = &flow[..] else { + panic!("{flow:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // Lanes from 24 on skip the inner arm and keep the inputs, but do + // not load: that edge is not traced. + assert_eq!(*inner, block_at(words, 0x74)); + let [None, Some(other)] = &nested[..] else { + panic!("{nested:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + assert_eq!(r.waterfall.compares.len(), 2); + assert_eq!(r.waterfall.reads.len(), 4); + } +} diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs new file mode 100644 index 000000000..9af1c4f20 --- /dev/null +++ b/crates/victory-shader/src/spill.rs @@ -0,0 +1,380 @@ +//! The spilled user-data table of a compute program. +//! +//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A +//! root signature that needs more dwords than that keeps none of its +//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit +//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and +//! the parameter the layout declares at user-data index N (16 or above) is +//! at byte `4 * (N - 16)` of that table. The code reads it with +//! `s_load_dword*` through that pointer. (Every compute program of the +//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this +//! kind; measured there: 118 of 118 such loads land on a declared parameter.) +//! +//! [`user_data`] rewrites those loads away: each dword they read becomes the +//! entry value of the SGPR its user-data index names, as if the parameter +//! had arrived in a register. Resource tracking and lowering then treat a +//! spilled parameter like any other (the host binds user data by root slot +//! and dword, not by register). + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{self, Program, Reg, Value}; +use crate::native::{HwStage, NativeProgram, StageIo}; + +/// The user-data index of the table's first dword. +const FIRST: u32 = 16; + +/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads +/// of a spilled user-data table rewritten ([`user_data`]). +pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> { + let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + user_data(&mut p, native); + Ok(p) +} + +/// Whether `native` is a compute program that keeps its root parameters in +/// a spilled user-data table (see the module): the entries no register +/// holds, as (first user-data index, dwords), if the table starts at index +/// 16 and the program has the two registers of its address. +fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> { + let StageIo::Cs(cs) = &native.io else { + return None; + }; + if native.stage != HwStage::Cs { + return None; + } + let registers = u32::from(cs.user_sgprs()); + let spilled: Vec<(u32, u32)> = native + .layout + .iter() + .filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers) + .map(|e| (u32::from(e.user_data), e.sgprs)) + .collect(); + // Only the one arrangement seen: the table starts at index 16. + (spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled) +} + +/// Whether `native` reads its root parameters from a spilled user-data +/// table. (In Grand Theft Auto VI exactly the compute programs of the +/// console's ray-tracing structure builder do.) +pub fn is_spilled(native: &NativeProgram) -> bool { + spilled(native).is_some() +} + +/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns +/// how many loads it replaced. Nothing changes unless the program is a +/// compute program whose layout has entries past its user SGPRs, the first +/// at index 16. A load is left alone (and resource tracking then refuses it +/// as before) when its offset is not a constant on a dword, or when a dword +/// it reads and the program uses is in no layout entry. +pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize { + let Some(spilled) = spilled(native) else { + return 0; + }; + let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1); + let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else { + return 0; + }; + + // The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies. + let mut lows = vec![low]; + let mut highs: Vec<Value> = Vec::new(); + let mut raw_highs = vec![high]; + // Instructions that only form the pointer: dropped when nothing reads + // them any more. + let mut forming: Vec<(usize, usize)> = Vec::new(); + loop { + let mut changed = false; + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let Fields::Sop { dst, src, .. } = &inst.fields else { + continue; + }; + let Some(Operand::Scalar { code: d, .. }) = *dst else { + continue; + }; + let Some(out) = inst.write(Reg::S(d)) else { + continue; + }; + let read = |op: &Operand| match *op { + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let found = match (inst.name(), &src[..]) { + ("s_mov_b32", [s]) => match read(s) { + Some(v) if lows.contains(&v) => Some(&mut lows), + Some(v) if highs.contains(&v) => Some(&mut highs), + Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs), + _ => None, + }, + ("s_and_b32", [x, y]) => { + let masked = |a: &Operand, m: &Operand| { + matches!(*m, Operand::Literal(0xff)) + && read(a).is_some_and(|v| raw_highs.contains(&v)) + }; + (masked(x, y) || masked(y, x)).then_some(&mut highs) + } + _ => None, + }; + if let Some(set) = found + && !set.contains(&out) + { + set.push(out); + forming.push((b, i)); + changed = true; + } + } + } + if !changed { + break; + } + } + if highs.is_empty() { + return 0; + } + + // Values some instruction or phi reads. + let mut read_somewhere = std::collections::HashSet::new(); + for block in &p.blocks { + read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1))); + } + let mut next = p + .inputs + .iter() + .map(|i| i.1) + .chain(p.blocks.iter().flat_map(|b| { + b.phis + .iter() + .map(|phi| phi.value) + .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1))) + })) + .map(|v| v.0 + 1) + .max() + .unwrap_or(0); + + // Each load through the pointer: its dwords become entry values. + let mut replaced: std::collections::HashMap<Value, Value> = Default::default(); + let mut gone: Vec<(usize, usize)> = Vec::new(); + let mut inputs = p.inputs.clone(); + for (b, block) in p.blocks.iter().enumerate() { + 'insts: for (i, inst) in block.insts.iter().enumerate() { + let Fields::Smem { + data: Some(Operand::Scalar { code: first, .. }), + base: Operand::Scalar { code: base, .. }, + offset, + soffset, + .. + } = inst.fields + else { + continue; + }; + if !inst.name().starts_with("s_load_dword") + || !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)) + { + continue; + } + let mut dwords = Vec::new(); + for &(reg, v) in &inst.writes { + let Reg::S(code) = reg else { + continue 'insts; + }; + let Some(k) = code.checked_sub(first) else { + continue 'insts; + }; + let index = FIRST + offset as u32 / 4 + u32::from(k); + let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n); + if !declared { + if read_somewhere.contains(&v) { + continue 'insts; + } + continue; + } + // SGPR codes end at 105; no root signature reaches there. + let Ok(code) = u8::try_from(index) else { + continue 'insts; + }; + if code > 105 { + continue 'insts; + } + dwords.push((Reg::S(code), v)); + } + for (reg, v) in dwords { + let value = match inputs.iter().find(|e| e.0 == reg) { + Some(e) => e.1, + None => { + let value = Value(next); + next += 1; + inputs.push((reg, value)); + value + } + }; + replaced.insert(v, value); + } + gone.push((b, i)); + } + } + if gone.is_empty() { + return 0; + } + p.inputs = inputs; + let renamed = |v: &mut Value| { + if let Some(&to) = replaced.get(v) { + *v = to; + } + }; + for block in &mut p.blocks { + for phi in &mut block.phis { + phi.args.iter_mut().for_each(renamed); + } + for inst in &mut block.insts { + inst.reads.iter_mut().for_each(|r| renamed(&mut r.1)); + } + } + // The loads go, then what only formed the pointer (last first, so a + // copy goes before what it copied). + let mut drop = gone.clone(); + loop { + let read_somewhere = { + let mut used = std::collections::HashSet::new(); + for (b, block) in p.blocks.iter().enumerate() { + used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + for (i, inst) in block.insts.iter().enumerate() { + if !drop.contains(&(b, i)) { + used.extend(inst.reads.iter().map(|r| r.1)); + } + } + } + used + }; + let before = drop.len(); + for &site in &forming { + let inst = &p.blocks[site.0].insts[site.1]; + if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) { + drop.push(site); + } + } + if drop.len() == before { + break; + } + } + for (b, block) in p.blocks.iter_mut().enumerate() { + let mut i = 0; + block.insts.retain(|_| { + i += 1; + !drop.contains(&(b, i - 1)) + }); + } + // The pointer's registers are no inputs once nothing reads them. + let mut read = std::collections::HashSet::new(); + for block in &p.blocks { + read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1))); + } + p.inputs + .retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v)); + gone.len() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::native::{ComputeIo, RootParam, RootType}; + + fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + } + } + + /// A compute program with `registers` user SGPRs and the group id after + /// them. + fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram { + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout, + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: registers << 1 | 1 << 7, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } + } + + // s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3], + // 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm. + const TABLE: [u32; 8] = [ + 0x8703_FF01, + 0x0000_00FF, + 0xBE82_0300, + 0xF400_0141, + 0xFA00_0010, + 0xF404_0001, + 0xFA00_0000, + 0xBF81_0000, + ]; + + #[test] + fn loads_of_the_spilled_table_become_entry_registers() { + let n = native( + &TABLE, + 4, + vec![ + param(RootType::Descriptor, 16, 2, 0), + param(RootType::Descriptor, 18, 2, 1), + param(RootType::Constants, 20, 16, 2), + ], + ); + 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(); + 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. + let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect(); + regs.sort(); + assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]); + } + + #[test] + fn parameters_in_registers_are_left_alone() { + // The same code where s0 and s1 are a root view the layout declares. + let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]); + let mut p = ir::build(&n.code, false, 256).unwrap(); + let before = p.clone(); + assert_eq!(user_data(&mut p, &n), 0); + assert_eq!(p, before); + } + + #[test] + fn a_used_dword_no_parameter_declares_keeps_its_load() { + // As above with `s_mov_b32 s6, s5` before the end: the dword at + // byte 0x10 (index 20) is read, and here nothing declares it. + let mut words = TABLE.to_vec(); + words.insert(7, 0xBE86_0305); + let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]); + let mut p = ir::build(&n.code, false, 256).unwrap(); + assert_eq!(user_data(&mut p, &n), 1); + let loads = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name().starts_with("s_load_")) + .count(); + assert_eq!(loads, 1); + // The pointer is still read, by the load that stays. + assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0))); + } +} diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs new file mode 100644 index 000000000..a913176c6 --- /dev/null +++ b/crates/victory-shader/src/structure.rs @@ -0,0 +1,1848 @@ +//! Control-flow structurisation (decision 0003): the program as one lane +//! runs it, without EXEC. +//! +//! Lane masks (EXEC, compare and carry results, the SGPRs they are saved +//! in) become per-lane booleans ([`Bools`]). A branch on a wave-wide test of +//! a mask (`s_cbranch_execz`, `vccz`, SCC of a mask operation) becomes a +//! branch on the lane's own bit: compiled code only skips work that lanes +//! outside the mask would not change, or tests a value that is the same in +//! every lane, so either way each lane can decide alone. A path-sensitive +//! pass then proves, for each vector instruction, that EXEC holds in every +//! lane that reaches it; what it cannot prove stays as the instruction's +//! guard, a per-lane `if` around it. +//! +//! The control-flow graph keeps its shape and must be reducible (DXIL's +//! only requirement). Helper lanes of a pixel shader count as live: on PC +//! their side effects are dropped too, and what they compute is only read +//! through derivatives. + +use std::collections::{HashMap, HashSet}; +use std::hash::{BuildHasherDefault, Hasher}; + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, VCC, Value}; + +/// A per-lane boolean: a node of [`Bools`]. Equal functions are equal nodes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Bool(u32); + +impl Bool { + pub const FALSE: Bool = Bool(0); + pub const TRUE: Bool = Bool(1); +} + +/// What a variable of [`Bools`] stands for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Atom { + /// The lane's bit of the compare or carry result in this VALU-written + /// value, before EXEC masking. + Lane(Value), + /// An SCC value, the same in every lane. + Uniform(Value), + /// A lane mask joined at a block entry, by its low dword's phi. + Phi(Value), + /// `s_wqm` result: some lane of the quad is in the source mask. + Quad(Value), + /// A mask the pass cannot see into (loaded, built from scalars, an + /// EXEC write it does not follow): the lane's bit of the register pair + /// this value is a dword of. + Opaque(Value), + /// A constant mask other than all lanes or none. + Constant(u64), +} + +/// Reduced ordered binary decision diagrams over [`Atom`]s. +#[derive(Debug, Clone)] +pub struct Bools { + /// (variable, low, high); nodes 0 and 1 are the constants. + nodes: Vec<(u32, Bool, Bool)>, + unique: Map<(u32, Bool, Bool), Bool>, + memo: Map<(Bool, Bool, Bool), Bool>, + atoms: Vec<Atom>, + /// Reverse-postorder index of the block that defines each atom. + born: Vec<usize>, + ids: Map<Atom, u32>, + overflow: bool, +} + +/// The tables below have small integer keys; SipHash dominated run time. +type Map<K, V> = HashMap<K, V, BuildHasherDefault<Fx>>; + +/// FxHash's multiply-rotate step. +#[derive(Default)] +struct Fx(u64); + +impl Hasher for Fx { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_u64(u64::from(b)); + } + } + + fn write_u32(&mut self, n: u32) { + self.write_u64(u64::from(n)); + } + + fn write_u64(&mut self, n: u64) { + self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(0x517c_c1b7_2722_0a95); + } + + fn write_usize(&mut self, n: usize) { + self.write_u64(n as u64); + } +} + +const TERMINAL: u32 = u32::MAX; +const MAX_NODES: usize = 1 << 21; +/// Case splits [`Bools::meet`] makes before it gives up. +const MAX_MEET: usize = 1 << 16; +/// Conditions [`Meets`] keeps; past that, they are searched anew. +const MAX_MEETS: usize = 1 << 18; + +/// What [`Bools::meet`] found out about one [`Bools`], for its later calls: +/// the conditions no lane satisfies, and the case splits it took to find +/// that out of each. +#[derive(Debug, Default)] +pub struct Meets { + none: Map<Box<[u32]>, usize>, +} + +impl Bools { + fn new() -> Self { + Bools { + nodes: vec![ + (TERMINAL, Bool::FALSE, Bool::FALSE), + (TERMINAL, Bool::TRUE, Bool::TRUE), + ], + unique: Map::default(), + memo: Map::default(), + atoms: Vec::new(), + born: Vec::new(), + ids: Map::default(), + overflow: false, + } + } + + /// The atom tested at the top of `b` and the results when it is false + /// and true; `None` for the constants. + pub fn node(&self, b: Bool) -> Option<(Atom, Bool, Bool)> { + let (v, lo, hi) = self.nodes[b.0 as usize]; + (v != TERMINAL).then(|| (self.atoms[v as usize], lo, hi)) + } + + /// The atoms `b` depends on, in variable order. + pub fn support(&self, b: Bool) -> Vec<Atom> { + let mut vars = self.vars(b); + vars.sort_unstable(); + vars.into_iter().map(|v| self.atoms[v as usize]).collect() + } + + fn vars(&self, b: Bool) -> Vec<u32> { + 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.contains(&b) { + continue; + } + seen.push(b); + if !vars.contains(&v) { + vars.push(v); + } + stack.extend([lo, hi]); + } + vars + } + + fn atom(&mut self, atom: Atom, born: usize) -> Bool { + let v = *self.ids.entry(atom).or_insert_with(|| { + self.atoms.push(atom); + self.born.push(born); + (self.atoms.len() - 1) as u32 + }); + self.mk(v, Bool::FALSE, Bool::TRUE) + } + + fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool { + if lo == hi { + return lo; + } + if let Some(&b) = self.unique.get(&(v, lo, hi)) { + return b; + } + if self.nodes.len() >= MAX_NODES { + // The caller fails once it sees `overflow`. + self.overflow = true; + return Bool::FALSE; + } + let b = Bool(self.nodes.len() as u32); + self.nodes.push((v, lo, hi)); + self.unique.insert((v, lo, hi), b); + b + } + + /// Cofactors of `b` for `v`, which is `b`'s top variable or above it. + fn split(&self, b: Bool, v: u32) -> (Bool, Bool) { + match self.nodes[b.0 as usize] { + (bv, lo, hi) if bv == v => (lo, hi), + _ => (b, b), + } + } + + fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool { + 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.nodes[b.0 as usize].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 + } + + fn and(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, b, Bool::FALSE) + } + + fn or(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, Bool::TRUE, b) + } + + fn not(&mut self, a: Bool) -> Bool { + self.ite(a, Bool::FALSE, Bool::TRUE) + } + + fn xor(&mut self, a: Bool, b: Bool) -> Bool { + let nb = self.not(b); + self.ite(a, nb, b) + } + + /// Whether some lane can satisfy every `(b, holds)` of `all` at once: + /// `b` where `holds`, its negation where not. Yes when the search grows + /// too large to finish. + pub fn meet(&self, all: &[(Bool, bool)]) -> bool { + self.meet_seen(all, &mut Meets::default()) + } + + /// [`Self::meet`], which looks up in `seen` what earlier calls on these + /// `Bools` found out and adds what it finds. The answer is the one + /// `meet` gives. + pub fn meet_seen(&self, all: &[(Bool, bool)], seen: &mut Meets) -> bool { + self.meet_within(all, MAX_MEET, seen) + } + + /// [`Self::meet_seen`] with `budget` case splits. + fn meet_within(&self, all: &[(Bool, bool)], mut budget: usize, seen: &mut Meets) -> bool { + let mut work = all + .iter() + .map(|&(b, holds)| b.0 << 1 | u32::from(holds)) + .collect(); + self.meet_in(0, &mut work, &mut budget, seen) + } + + /// The search of [`Self::meet`] for the conditions `work[at..]` (a node + /// doubled, plus one where it must hold), which it takes off `work`. + /// + /// The search is a case split on the top variable, and the cofactors of + /// a few large functions come down to the same conditions over and over + /// (a block's reach under a mask and under its negation share most of + /// their nodes), so splitting each anew is exponential where the + /// distinct conditions are few. `seen` keeps the conditions that no lane + /// satisfies with the case splits it took to find that out: meeting + /// them again takes those splits off the budget at once. A search + /// therefore gives up exactly where one that split everything anew + /// would (nothing below such conditions ends it early, so it either + /// makes all those splits or runs out among them), and gives the same + /// answer. + fn meet_in( + &self, + at: usize, + work: &mut Vec<u32>, + budget: &mut usize, + seen: &mut Meets, + ) -> bool { + // Constants either fail or say nothing. + let mut kept = at; + for i in at..work.len() { + let (b, holds) = (work[i] >> 1, work[i] & 1 != 0); + if b > Bool::TRUE.0 { + work[kept] = work[i]; + kept += 1; + } else if (b == Bool::TRUE.0) != holds { + work.truncate(at); + return false; + } + } + work.truncate(kept); + if kept == at || *budget == 0 { + work.truncate(at); + return true; + } + // As a set: neither order nor repeats change the search. + work[at..].sort_unstable(); + let mut end = at + 1; + for i in at + 1..kept { + if work[i] != work[end - 1] { + work[end] = work[i]; + end += 1; + } + } + work.truncate(end); + if let Some(&splits) = seen.none.get(&work[at..]) { + let within = splits <= *budget; + *budget = budget.saturating_sub(splits); + work.truncate(at); + return !within; + } + let before = *budget; + *budget -= 1; + let top = |code: u32| self.nodes[(code >> 1) as usize].0; + let v = work[at..].iter().map(|&c| top(c)).min().expect("not empty"); + let mut found = false; + for value in [false, true] { + for i in at..end { + let (lo, hi) = self.split(Bool(work[i] >> 1), v); + work.push((if value { hi } else { lo }).0 << 1 | work[i] & 1); + } + if self.meet_in(end, work, budget, seen) { + found = true; + break; + } + } + if !found && seen.none.len() < MAX_MEETS { + seen.none.insert(work[at..end].into(), before - *budget); + } + work.truncate(at); + found + } + + 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, Bool>) -> Bool { + let (v, lo, hi) = self.nodes[b.0 as usize]; + if v == TERMINAL { + return b; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let lo = self.forget(lo, from, memo); + let hi = self.forget(hi, from, memo); + let r = if self.born[v as usize] >= from { + self.or(lo, hi) + } else { + self.mk(v, lo, hi) + }; + memo.insert(b, r); + r + } + + fn restrict(&mut self, b: Bool, v: u32, value: bool, memo: &mut Map<Bool, Bool>) -> Bool { + let (bv, lo, hi) = self.nodes[b.0 as usize]; + if bv == TERMINAL || bv > v { + return b; + } + if bv == v { + return if value { hi } else { lo }; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let l = self.restrict(lo, v, value, memo); + let h = self.restrict(hi, v, value, memo); + let r = self.mk(bv, l, h); + memo.insert(b, r); + r + } + + /// `b` with each atom that `known` decides replaced by its value. + fn given(&mut self, mut b: Bool, known: Bool) -> Bool { + for v in self.vars(b) { + let x = self.mk(v, Bool::FALSE, Bool::TRUE); + let nx = self.not(x); + if self.implies(known, x) { + b = self.restrict(b, v, true, &mut Map::default()); + } else if self.implies(known, nx) { + b = self.restrict(b, v, false, &mut Map::default()); + } + } + b + } +} + +/// How a lane leaves a block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LaneExit { + Jump(usize), + /// To `taken` in lanes where `when` holds. A condition over + /// [`Atom::Uniform`]s only is a uniform branch. + Branch { + when: Bool, + taken: usize, + not_taken: usize, + }, + End, + Indirect, +} + +/// A [`Program`] as one lane runs it: same blocks, per-lane branches. +#[derive(Debug, Clone)] +pub struct Structured { + pub bools: Bools, + /// Per block. + pub exits: Vec<LaneExit>, + /// Per block and instruction: the condition, beyond reaching it, under + /// which a lane runs a vector instruction; `None` when reaching it is + /// enough (lanes outside EXEC then never get there, so a VGPR write + /// needs no old value). Always `None` for scalar instructions. + pub guards: Vec<Vec<Option<Bool>>>, + /// Per block: what holds in every lane that enters it (over forward + /// edges; a loop header forgets what its loop redefines). + pub reach: Vec<Bool>, + /// The lane's bit of each lane-mask value, by its low dword's value. + pub masks: HashMap<Value, Bool>, + /// Exact Wave64 pairs for checking masks at their uses. + paired_masks: Map<Key, Bool>, + /// Wave64 masks: low dword's value by the high dword's. + pub highs: HashMap<Value, Value>, + /// Masks (low dwords) set only in lanes whose EXEC bit is set where + /// they are written: every such lane reaches the writing block, so a + /// ballot there gives the mask as data. No split low dword, as in + /// `masks`. + pub active: HashSet<Value>, + /// Incoming lane boolean per predecessor edge (in block predecessor order) + /// for each [`Atom::Phi`] id. + pub phi_masks: HashMap<Value, Vec<Bool>>, + /// Blocks whose closing branch the whole wave takes together ([`structure_wide`]): its + /// `when` is still the lane's own bit; the wave goes by all of them. + pub wide: HashSet<usize>, + /// Per block closed by a branch on a lane mask: whether the console takes it when some + /// lane's `when` holds (`true`) or when every lane's does (`false`). + pub wave_any: Vec<Option<bool>>, + /// SCC values a mask operation sets when some lane's bit of its result is set, with that + /// lane bit: as data such an SCC is "some lane of the wave has it". + pub scc_some: HashMap<Value, Bool>, +} + +impl Structured { + pub(crate) fn mask_bits(&self, low: Value, high: Option<Value>) -> Option<Bool> { + match high { + Some(high) => self.paired_masks.get(&(low, high)), + None => self.masks.get(&low), + } + .copied() + } +} + +/// Builds the per-lane form of `program`. +pub fn structure(program: &Program) -> Result<Structured, ShaderError> { + structure_wide(program, &HashSet::new()) +} + +/// [`structure`], with the branches that close the blocks of `wide` kept as the console has +/// them: one decision for the whole wave (`s_cbranch_execz` and `vccz`: taken when no lane's +/// bit is set; `execnz` and `vccnz`: when some lane's is; SCC of a mask operation likewise, +/// [`Structured::wave_any`]), which every lane follows. A lane +/// then learns nothing about its own bit from the way it went, so past such a branch EXEC +/// stays a guard on every vector instruction, as it is on the console. For a console wave +/// run as two host waves, which exchange that decision and can then meet (a group barrier) +/// inside the branch. +pub fn structure_wide(program: &Program, wide: &HashSet<usize>) -> Result<Structured, ShaderError> { + let mut l = Lanes::new(program)?; + l.wide = wide.clone(); + loop { + let execs = l.masks_in_order(); + let cond = l.paths()?; + let (wrong, new_derived) = l.check_joins(&cond); + if l.b.overflow { + return Err(TOO_LARGE); + } + if wrong.is_empty() && new_derived.is_empty() { + return l.finish(&execs, &cond); + } + l.unresolved.extend(wrong); + l.derived_phis.extend(new_derived); + l.reset(); + } +} + +/// A lane mask by the values of its low and high dword (both the low one in +/// wave32). +type Key = (Value, Value); + +struct Lanes<'a> { + p: &'a Program, + order: Vec<usize>, + /// Reverse-postorder index per block. + index: Vec<usize>, + /// Per block, in predecessor order: (block, over its taken edge). + incoming: Vec<Vec<(usize, bool)>>, + /// Block and instruction index writing each value. + defs: Map<Value, (usize, usize)>, + /// Block and index of each phi value. + phis: Map<Value, (usize, usize)>, + /// Mask joins found wrong when resolved to a constant: atoms instead. + unresolved: HashSet<Value>, + /// Phi ids whose joins depend on EXEC or VALU results (including along + /// back edges), carried across resets so their joins stay in `masks`. + derived_phis: HashSet<Value>, + b: Bools, + /// Masks derived from EXEC and VALU results. + masks: Map<Key, Bool>, + /// Other values read as masks: constants, uniform selects, opaque ones. + other: Map<Key, Bool>, + /// Pairs read as masks that `mask` does not see: carry-ins, and pairs + /// joins take over back edges. + seen: Vec<Key>, + /// For branches: SCC of a mask operation ("some lane is set") as the + /// lane's own bit. + scc_lane: Map<Value, Bool>, + /// Joins resolved to a constant, to check once all edges are known. + joins: Vec<Join>, + /// [`Atom::Phi`] joins created in the current pass, resolved in + /// `check_joins` and exported in `finish`. + phi_joins: Vec<PhiJoin>, + phi_join_ids: HashSet<Value>, + /// Per block: what a lane knows on entry, over forward edges only. + first: Vec<Bool>, + /// Per block ending in a branch: when a lane takes it. + when: Vec<Option<Bool>>, + /// See [`Structured::active`]. + active: HashSet<Value>, + /// See [`Structured::wide`]. + wide: HashSet<usize>, + /// SCC values of [`Self::scc_lane`] that are set when EVERY lane's bit is (`s_cmp_eq` of + /// two masks: "no lane differs"); the others are set when some lane's is. + scc_every: HashSet<Value>, + /// See [`Structured::wave_any`]. + wave_any: Vec<Option<bool>>, +} + +/// A mask join taken as `value` in every lane that reaches `block`: each +/// incoming mask held (or failed) on its edge. +struct Join { + block: usize, + /// The phi value naming the join. + id: Value, + value: bool, + derived: bool, + args: Vec<Key>, +} + +/// A mask join represented as [`Atom::Phi`], whose incoming edge masks are +/// resolved once every block (including loop back edges) has been visited. +struct PhiJoin { + block: usize, + id: Value, + derived: bool, + args: Vec<Key>, +} + +struct SopMasks { + dst: Option<(Key, Bool)>, + exec: Option<(Key, Bool)>, + /// Some operand derives from EXEC or a VALU result. + derived: bool, + /// For branches: SCC ("result is not zero") per lane. + scc: Option<Bool>, +} + +const MAX_ROUNDS: usize = 256; + +impl<'a> Lanes<'a> { + fn new(p: &'a Program) -> Result<Self, ShaderError> { + let blocks = &p.blocks; + let order = crate::ir::reverse_postorder(blocks); + let mut index = vec![usize::MAX; blocks.len()]; + for (i, &b) in order.iter().enumerate() { + index[b] = i; + } + check_reducible(p, &order, &index)?; + let mut incoming = vec![Vec::new(); blocks.len()]; + let (mut defs, mut phis) = (Map::default(), Map::default()); + for (b, block) in blocks.iter().enumerate() { + for (k, s) in block.exit.successors().into_iter().enumerate() { + incoming[s].push((b, k == 0)); + } + for (i, phi) in block.phis.iter().enumerate() { + phis.insert(phi.value, (b, i)); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs.insert(v, (b, i)); + } + } + } + Ok(Lanes { + p, + order, + index, + incoming, + defs, + phis, + unresolved: HashSet::new(), + derived_phis: HashSet::new(), + b: Bools::new(), + masks: Map::default(), + other: Map::default(), + seen: Vec::new(), + scc_lane: Map::default(), + joins: Vec::new(), + phi_joins: Vec::new(), + phi_join_ids: HashSet::new(), + first: vec![Bool::FALSE; blocks.len()], + when: vec![None; blocks.len()], + active: HashSet::new(), + wide: HashSet::new(), + scc_every: HashSet::new(), + wave_any: vec![None; blocks.len()], + }) + } + + fn reset(&mut self) { + self.b = Bools::new(); + self.masks.clear(); + self.other.clear(); + self.seen.clear(); + self.scc_lane.clear(); + self.scc_every.clear(); + self.wave_any.fill(None); + self.joins.clear(); + self.phi_joins.clear(); + self.phi_join_ids.clear(); + self.first.fill(Bool::FALSE); + self.when.fill(None); + self.active.clear(); + } + + /// Lane masks, branch conditions and forward-edge knowledge, block by + /// block in reverse postorder; returns EXEC at each instruction reading it. + fn masks_in_order(&mut self) -> Vec<Vec<Option<Bool>>> { + let p = self.p; + let input = |reg| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1); + if let Some(lo) = input(Reg::S(EXEC)) { + let hi = if p.wave64 { + input(Reg::S(EXEC + 1)).unwrap_or(lo) + } else { + lo + }; + self.masks.insert((lo, hi), Bool::TRUE); + self.active.insert(lo); + } + let mut execs: Vec<Vec<Option<Bool>>> = + p.blocks.iter().map(|b| vec![None; b.insts.len()]).collect(); + for n in 0..self.order.len() { + let b = self.order[n]; + let mut c = if n == 0 { Bool::TRUE } else { Bool::FALSE }; + for k in 0..self.incoming[b].len() { + let (q, taken) = self.incoming[b][k]; + if self.index[q] < n { + let e = self.edge(self.first[q], q, taken); + c = self.b.or(c, e); + } + } + self.first[b] = c; + // EXEC joined at the block's entry holds the lanes that arrive. + for phi in &p.blocks[b].phis { + if phi.reg == Reg::S(EXEC) { + self.active.insert(phi.value); + } + } + // EXEC where known in this block (read or written so far). + let mut now = None; + for (i, inst) in p.blocks[b].insts.iter().enumerate() { + if inst.read(Reg::S(EXEC)).is_some() { + let e = self.exec(inst); + execs[b][i] = Some(e); + now = Some(e); + } + self.step(inst, now); + if let Some(k) = self.key(|r| inst.write(r), EXEC) { + now = self.masks.get(&k).or(self.other.get(&k)).copied(); + } + } + if let Exit::Branch { .. } = p.blocks[b].exit + && let Some(last) = p.blocks[b].insts.last() + { + self.when[b] = Some(self.branch(last)); + self.wave_any[b] = self.wave_kind(last); + } + } + execs + } + + /// `c` narrowed by the branch at the end of `q` towards one successor. + fn edge(&mut self, c: Bool, q: usize, taken: bool) -> Bool { + if self.wide.contains(&q) { + // the wave's decision: it says nothing about this lane's own bit + return c; + } + match self.when[q] { + Some(w) if taken => self.b.and(c, w), + Some(w) => { + let nw = self.b.not(w); + self.b.and(c, nw) + } + None => c, + } + } + + /// Joins whose constant fails on some edge, and joins that need another + /// pass because a later edge turned out to derive from EXEC or VALU. + fn check_joins(&mut self, cond: &[Bool]) -> (Vec<Value>, Vec<Value>) { + let mut wrong = Vec::new(); + let mut new_derived = Vec::new(); + let mut seen_derived = HashSet::new(); + let mut j = 0; + let mut p = 0; + // Checking an argument can resolve another join; it is checked too. + while j < self.joins.len() || p < self.phi_joins.len() { + while j < self.joins.len() { + let (block, id, value, was_derived) = ( + self.joins[j].block, + self.joins[j].id, + self.joins[j].value, + self.joins[j].derived, + ); + let mut failed = false; + for (n, a) in self.joins[j].args.clone().into_iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + let e = self.edge(cond[q], q, taken); + let (mut m, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } + if !value { + m = self.b.not(m); + } + if !failed && !self.b.implies(e, m) { + wrong.push(id); + failed = true; + } + } + j += 1; + } + while p < self.phi_joins.len() { + let (id, was_derived) = (self.phi_joins[p].id, self.phi_joins[p].derived); + for a in self.phi_joins[p].args.clone() { + let (_, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } + } + p += 1; + } + } + (wrong, new_derived) + } + + fn finish( + mut self, + execs: &[Vec<Option<Bool>>], + cond: &[Bool], + ) -> Result<Structured, ShaderError> { + let phi_joins = std::mem::take(&mut self.phi_joins); + let mut phi_masks = HashMap::with_capacity(phi_joins.len()); + for pj in phi_joins { + let incoming: Vec<Bool> = pj + .args + .into_iter() + .enumerate() + .map(|(n, a)| { + let (q, taken) = self.incoming[pj.block][n]; + let e = self.edge(cond[q], q, taken); + let m = self.mask(a).0; + self.b.given(m, e) + }) + .collect(); + phi_masks.insert(pj.id, incoming); + } + let blocks = &self.p.blocks; + let b = &mut self.b; + 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 + } + (&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.given(self.when[n].unwrap_or(Bool::FALSE), cond[n]), + taken, + not_taken, + }, + }) + .collect(); + if self.b.overflow { + return Err(TOO_LARGE); + } + // Exports go by low dword. A low dword read with two high dwords + // (one rewritten alone) names no one mask: it is left out, so + // lowering refuses what reads it instead of taking the other + // pair's lanes 32-63. Not where the low dword holds a number: see + // the shortcut in `mask`. + let (mut high, mut split) = (Map::default(), HashSet::new()); + let keys = self.masks.keys().chain(self.other.keys()); + for &(lo, hi) in keys.chain(&self.seen) { + if *high.entry(lo).or_insert(hi) != hi { + split.insert(lo); + } + } + self.masks.retain(|k, _| !split.contains(&k.0)); + self.active.retain(|lo| !split.contains(lo)); + Ok(Structured { + masks: self.masks.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() }, + active: self.active, + wide: self.wide, + wave_any: self.wave_any, + scc_some: self + .scc_lane + .iter() + .filter(|(scc, _)| !self.scc_every.contains(scc)) + .map(|(&scc, &m)| (scc, m)) + .collect(), + phi_masks, + bools: self.b, + exits, + guards, + reach: cond.to_vec(), + }) + } + + fn key(&self, value: impl Fn(Reg) -> Option<Value>, code: u8) -> Option<Key> { + let lo = value(Reg::S(code))?; + let hi = if self.p.wave64 { + value(Reg::S(code + 1))? + } else { + lo + }; + Some((lo, hi)) + } + + fn born(&self, v: Value) -> usize { + match (self.defs.get(&v), self.phis.get(&v)) { + (Some(&(b, _)), _) | (_, Some(&(b, _))) => self.index[b], + _ => 0, + } + } + + fn exec(&mut self, inst: &Inst) -> Bool { + match self.key(|r| inst.read(r), EXEC) { + Some(k) => self.mask(k).0, + None => Bool::TRUE, + } + } + + /// The mask a value pair holds, and whether it derives from EXEC or a + /// VALU result. + fn mask(&mut self, k: Key) -> (Bool, bool) { + if let Some(&m) = self.masks.get(&k) { + return (m, true); + } + if let Some(&m) = self.other.get(&k) { + return (m, false); + } + let p = self.p; + let (m, derived) = match self.join(k) { + Some(join) => join, + None => { + let (lo, hi) = (self.defs.get(&k.0).copied(), self.defs.get(&k.1).copied()); + let def = |d: Option<(usize, usize)>| d.map(|(b, i)| &p.blocks[b].insts[i]); + let m = match (lo, hi) { + (Some(at), Some(hi)) if at == hi => def(lo) + .and_then(|i| self.sop(i)) + .and_then(|r| r.dst) + .map(|d| d.1), + _ => None, + }; + // What an EXEC write the pass does not follow leaves there. + let exec_write = |d: Option<(usize, usize)>, v: Value| { + def(d).is_some_and(|i| { + i.write(Reg::S(EXEC)) == Some(v) || i.write(Reg::S(EXEC + 1)) == Some(v) + }) + }; + let derived = exec_write(lo, k.0) || exec_write(hi, k.1); + // shortcut: the atom names the pair by its low dword, and + // lowering takes the high dword written beside it. For halves + // written apart (two `s_mov_b32`) lanes 32-63 are wrong unless + // lowering has no value for the low dword (EXEC, compares) + // and refuses. Give the atom both dwords when such code + // turns up. + let m = m.unwrap_or_else(|| { + let born = self.born(k.0); + self.b.atom(Atom::Opaque(k.0), born) + }); + (m, derived) + } + }; + let cache = if derived { + &mut self.masks + } else { + &mut self.other + }; + cache.insert(k, m); + (m, derived) + } + + /// A mask joined by phis at a block entry, and whether a mask coming in + /// on a forward edge derives from EXEC or a VALU result. Where every + /// lane arriving so far has the incoming mask set (or clear), the join + /// is that constant, for a lane can only read it after arriving. + fn join(&mut self, k: Key) -> Option<(Bool, bool)> { + let p = self.p; + let (lo, hi) = (self.phis.get(&k.0).copied(), self.phis.get(&k.1).copied()); + let block = match (lo, hi) { + (Some((a, _)), Some((b, _))) if a != b => return None, + (Some((b, _)), _) | (_, Some((b, _))) => b, + _ => return None, + }; + let target = &p.blocks[block]; + let arg = |phi: Option<(usize, usize)>, own: Value, n: usize| { + phi.map_or(own, |(_, i)| target.phis[i].args[n]) + }; + let args: Vec<Key> = (0..target.preds.len()) + .map(|n| (arg(lo, k.0, n), arg(hi, k.1, n))) + .collect(); + let id = lo.map_or(k.1, |_| k.0); + let mut derived = self.derived_phis.contains(&id); + // (edge condition, mask) per forward edge; back edges come later. + let mut forward = Vec::new(); + for (n, &a) in args.iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + if self.index[q] < self.index[block] { + let (m, d) = self.mask(a); + derived |= d; + let e = self.edge(self.first[q], q, taken); + forward.push((e, m)); + } else { + self.seen.push(a); + } + } + if forward.len() == args.len() + && let Some(&(_, m)) = forward.first() + && forward.iter().all(|f| f.1 == m) + { + return Some((m, derived)); + } + if !self.unresolved.contains(&id) { + for value in [true, false] { + let b = &mut self.b; + let holds = forward.iter().all(|&(e, m)| { + let m = if value { m } else { b.not(m) }; + b.implies(e, m) + }); + if holds { + self.joins.push(Join { + block, + id, + value, + derived, + args, + }); + let m = if value { Bool::TRUE } else { Bool::FALSE }; + return Some((m, derived)); + } + } + } + if self.phi_join_ids.insert(id) { + self.phi_joins.push(PhiJoin { + block, + id, + derived, + args, + }); + } + let born = self.index[block]; + Some((self.b.atom(Atom::Phi(id), born), derived)) + } + + fn operand(&mut self, inst: &Inst, op: &Operand) -> Option<(Bool, bool)> { + let wave64 = self.p.wave64; + let constant = |b: &mut Bools, v: u64| { + let v = if wave64 { v } else { v & 0xFFFF_FFFF }; + match v { + 0 => Bool::FALSE, + _ if v == u64::MAX >> (32 * u8::from(!wave64)) => Bool::TRUE, + _ => b.atom(Atom::Constant(v), 0), + } + }; + Some(match *op { + Operand::Scalar { code, .. } if code != NULL => { + let k = self.key(|r| inst.read(r), code)?; + self.mask(k) + } + Operand::Const(c @ 128..=208) => { + let v = if c <= 192 { + i64::from(c) - 128 + } else { + 192 - i64::from(c) + }; + (constant(&mut self.b, v as u64), false) + } + Operand::Literal(x) => (constant(&mut self.b, u64::from(x)), false), + _ => return None, + }) + } + + /// Lane-mask meaning of a lane-width scalar operation. + fn sop(&mut self, inst: &Inst) -> Option<SopMasks> { + let Fields::Sop { dst, src, .. } = &inst.fields else { + return None; + }; + let width = if self.p.wave64 { "_b64" } else { "_b32" }; + let op = inst.name().strip_prefix("s_")?.strip_suffix(width)?; + let dst = match dst { + Some(Operand::Scalar { code, .. }) if *code != NULL => { + self.key(|r| inst.write(r), *code) + } + _ => None, + }; + let exec_out = self.key(|r| inst.write(r), EXEC); + let (save, f) = match (op.strip_suffix("_saveexec"), op.strip_suffix("_wrexec")) { + (Some(f), _) => (Some(true), f), + (_, Some(f)) => (Some(false), f), + _ => (None, op), + }; + let mut derived = exec_out.is_some() || save.is_some(); + let mut arg = |n: usize, l: &mut Self| { + let (m, d) = l.operand(inst, src.get(n)?)?; + derived |= d; + Some(m) + }; + if let Some(saveexec) = save { + let s = arg(0, self)?; + let exec = self.exec(inst); + let new = self.combine(f, s, exec)?; + let saved = if saveexec { exec } else { new }; + return Some(SopMasks { + dst: dst.map(|d| (d, saved)), + exec: exec_out.map(|e| (e, new)), + derived, + scc: Some(new), + }); + } + let (result, scc) = match op { + "mov" => (arg(0, self)?, None), + "not" => { + let a = arg(0, self)?; + let r = self.b.not(a); + (r, Some(r)) + } + "wqm" => { + let a = arg(0, self)?; + let lo = dst.or(exec_out)?.0; + let born = self.born(lo); + let q = self.b.atom(Atom::Quad(lo), born); + let r = self.b.or(a, q); + (r, Some(r)) + } + "cselect" => { + let (a, c) = (arg(0, self)?, arg(1, self)?); + let scc = inst.read(Reg::Scc)?; + if self.clear_after_loop(scc) { + (c, None) + } else { + let born = self.born(scc); + let u = self.b.atom(Atom::Uniform(scc), born); + (self.b.ite(u, a, c), None) + } + } + _ => { + let (a, c) = (arg(0, self)?, arg(1, self)?); + let r = self.combine(op, a, c)?; + (r, Some(r)) + } + }; + Some(SopMasks { + dst: dst.map(|d| (d, result)), + exec: exec_out.map(|e| (e, result)), + derived, + scc, + }) + } + + /// Whether SCC value `scc` is clear wherever it is read: the instruction before an + /// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not + /// empty" (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)` + /// with EXEC empty. A read inside the loop or behind another way out of it sees a + /// join of this value, not the value itself. + fn clear_after_loop(&self, scc: Value) -> bool { + let Some(&(b, i)) = self.defs.get(&scc) else { + return false; + }; + let block = &self.p.blocks[b]; + let (Some(writer), Some(last)) = (block.insts.get(i), block.insts.last()) else { + return false; + }; + let exec = writer.write(Reg::S(EXEC)); + let back = match block.exit { + Exit::Branch { taken, .. } => self.index[taken] <= self.index[b], + _ => false, + }; + back && i + 2 == block.insts.len() + && exec.is_some() + && last.name() == "s_cbranch_execnz" + && last.read(Reg::S(EXEC)) == exec + && (!self.p.wave64 || last.read(Reg::S(EXEC + 1)) == writer.write(Reg::S(EXEC + 1))) + } + + fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option<Bool> { + let b = &mut self.b; + Some(match f { + "and" => b.and(a, c), + "or" => b.or(a, c), + "xor" => b.xor(a, c), + "andn2" => { + let nc = b.not(c); + b.and(a, nc) + } + "orn2" => { + let nc = b.not(c); + b.or(a, nc) + } + "andn1" => { + let na = b.not(a); + b.and(na, c) + } + "orn1" => { + let na = b.not(a); + b.or(na, c) + } + "nand" => { + let r = b.and(a, c); + b.not(r) + } + "nor" => { + let r = b.or(a, c); + b.not(r) + } + "xnor" => { + let r = b.xor(a, c); + b.not(r) + } + _ => return None, + }) + } + + /// Records the masks `inst` defines; `exec` is EXEC there, if known. + fn step(&mut self, inst: &Inst, exec: Option<Bool>) { + let name = inst.name(); + match &inst.fields { + Fields::Sop { src, .. } => { + let mut takes_mask = false; + for s in src { + if let Operand::Scalar { code, .. } = *s + && code != NULL + && let Some(k) = self.key(|r| inst.read(r), code) + { + let phi = self.phis.contains_key(&k.0) || self.phis.contains_key(&k.1); + takes_mask |= self.masks.contains_key(&k) || phi && self.mask(k).1; + } + } + let touches_exec = + inst.write(Reg::S(EXEC)).is_some() || inst.read(Reg::S(EXEC)).is_some(); + if (takes_mask || touches_exec) + && let Some(r) = self.sop(inst).filter(|r| r.derived) + { + for (k, m) in r.dst.into_iter().chain(r.exec) { + self.masks.insert(k, m); + // EXEC itself holds the lanes that run here. + if r.exec.is_some_and(|e| e.0 == k) + || exec.is_some_and(|e| self.b.implies(m, e)) + { + self.active.insert(k.0); + } + } + if let (Some(scc), Some(m)) = (inst.write(Reg::Scc), r.scc) { + self.scc_lane.insert(scc, m); + } + } + // `s_cmp_eq/lg` of a mask: "no lane differs" per lane. + let width = if self.p.wave64 { "64" } else { "32" }; + if takes_mask + && let (Some(rest), Some(scc)) = + (name.strip_prefix("s_cmp_"), inst.write(Reg::Scc)) + && rest + .strip_suffix(width) + .is_some_and(|r| r == "eq_u" || r == "lg_u") + && let [a, c] = &src[..] + && let (Some((a, _)), Some((c, _))) = + (self.operand(inst, a), self.operand(inst, c)) + { + let ne = self.b.xor(a, c); + let m = if rest.starts_with("eq") { + self.b.not(ne) + } else { + ne + }; + self.scc_lane.insert(scc, m); + if rest.starts_with("eq") { + self.scc_every.insert(scc); + } + } + // `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar + // condition, or EXEC itself): its SCC, "some lane is set", is each lane's own + // bit. A branch on it then reads no ballot. + if takes_mask + && name.starts_with("s_bcnt1_i32_b") + && let Some(scc) = inst.write(Reg::Scc) + && let [a] = &src[..] + && let Some((m, true)) = self.operand(inst, 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.scc_lane.insert(scc, own); + } + } + } + Fields::Valu(v) => { + let exec = self.exec(inst); + let lane = |l: &mut Self, k: Key| { + let born = l.born(k.0); + let a = l.b.atom(Atom::Lane(k.0), born); + let m = l.b.and(exec, a); + l.masks.insert(k, m); + l.active.insert(k.0); + }; + // A select reads a mask nothing else may: a join of compare + // results is resolved here, as for EXEC. A carry-in is only + // recorded for `finish`: resolving its join would turn a + // refusal into a per-lane phi, wrong after a divergent branch. + if (name == "v_cndmask_b32" || name.contains("_co_ci_")) + && let Some(&Operand::Scalar { code, .. }) = v.src.get(2) + && code != NULL + && let Some(k) = self.key(|r| inst.read(r), code) + { + if name == "v_cndmask_b32" { + self.mask(k); + } else { + self.seen.push(k); + } + } + if matches!(name, "v_div_fmas_f32" | "v_div_fmas_f64") + && let Some(k) = self.key(|r| inst.read(r), VCC) + { + self.mask(k); + } + if name.starts_with("v_cmpx") { + if let Some(k) = self.key(|r| inst.write(r), EXEC) { + lane(self, k); + } + } else { + let compare = v.dst.filter(|_| name.starts_with("v_cmp")); + for op in compare.iter().chain(&v.carry) { + if let Operand::Scalar { code, .. } = *op + && let Some(k) = self.key(|r| inst.write(r), code) + { + lane(self, k); + } + } + } + } + _ => {} + } + } + + /// The per-lane condition under which a block's closing branch is taken. + /// How the console decides the branch `inst` on a lane mask, in terms of the lanes' own + /// `when` ([`Self::branch`]): taken when some lane's holds (`true`) or when every lane's + /// does (`false`). `execnz`/`vccnz` ask for some set bit, `execz`/`vccz` for none; SCC + /// of a mask operation is "some lane's bit is set", SCC of `s_cmp_eq` of two masks is + /// "every lane's is" ([`Self::scc_every`]), and `scc0` branches on the opposite. None + /// for a branch on a scalar condition. + fn wave_kind(&self, inst: &Inst) -> Option<bool> { + match inst.name() { + "s_cbranch_execnz" | "s_cbranch_vccnz" => Some(true), + "s_cbranch_execz" | "s_cbranch_vccz" => Some(false), + n @ ("s_cbranch_scc0" | "s_cbranch_scc1") => { + let scc = inst.read(Reg::Scc)?; + self.scc_lane.get(&scc)?; + // set: SCC is 1 when some lane's bit is set (every lane's, for a compare) + let every = self.scc_every.contains(&scc); + Some((n == "s_cbranch_scc1") != every) + } + _ => None, + } + } + + fn branch(&mut self, inst: &Inst) -> Bool { + let exec = self.exec(inst); + match inst.name() { + "s_cbranch_execz" => self.b.not(exec), + "s_cbranch_execnz" => exec, + n @ ("s_cbranch_vccz" | "s_cbranch_vccnz") => { + let vcc = match self.key(|r| inst.read(r), VCC) { + Some(k) => self.mask(k).0, + None => Bool::FALSE, + }; + let any = self.b.and(vcc, exec); + if n.ends_with("nz") { + any + } else { + self.b.not(any) + } + } + n => { + let Some(scc) = inst.read(Reg::Scc) else { + return Bool::FALSE; + }; + let set = match self.scc_lane.get(&scc) { + Some(&m) => m, + None => { + let born = self.born(scc); + self.b.atom(Atom::Uniform(scc), born) + } + }; + if n == "s_cbranch_scc1" { + set + } else { + self.b.not(set) + } + } + } + } + + /// What a lane knows on entering each block, to a fixpoint. A loop + /// header forgets what the back edge says about atoms the loop redefines. + fn paths(&mut self) -> Result<Vec<Bool>, ShaderError> { + let n = self.p.blocks.len(); + let mut cond = vec![Bool::FALSE; n]; + if let Some(&entry) = self.order.first() { + cond[entry] = Bool::TRUE; + } + for _ in 0..MAX_ROUNDS { + let mut changed = false; + for i in 1..self.order.len() { + let s = self.order[i]; + 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 = self.b.forget(e, i, &mut Map::default()); + } + c = self.b.or(c, e); + } + if c != cond[s] { + cond[s] = c; + changed = true; + } + } + if self.b.overflow { + return Err(TOO_LARGE); + } + if !changed { + return Ok(cond); + } + } + Err(ShaderError::Isa { + offset: 0, + reason: "lane conditions do not settle", + }) + } +} + +const TOO_LARGE: ShaderError = ShaderError::Isa { + offset: 0, + reason: "lane conditions too large", +}; + +/// `ir::build` splits irreducible loops; checked again because everything +/// here assumes a reducible graph. +fn check_reducible(p: &Program, order: &[usize], index: &[usize]) -> Result<(), ShaderError> { + match crate::ir::irreducible_edge(&p.blocks, order, index) { + Some((from, _)) => Err(ShaderError::Unsupported { + offset: p.blocks[from].offset, + what: "irreducible control flow", + }), + None => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn build(words: &[u32], wave64: bool) -> Program { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + ir::build(&code, wave64, 256).unwrap() + } + + fn guarded(s: &Structured) -> usize { + s.guards.iter().flatten().filter(|g| g.is_some()).count() + } + + /// 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 { + 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 all.is_empty() || *budget == 0 { + return true; + } + *budget -= 1; + let top = |x: Bool| b.nodes[x.0 as usize].0; + let v = all.iter().map(|&(x, _)| top(x)).min().expect("not empty"); + [false, true].into_iter().any(|value| { + let next = all + .iter() + .map(|&(x, holds)| { + let (lo, hi) = b.split(x, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + meet_anew(b, next, budget) + }) + } + + #[test] + fn a_search_that_remembers_answers_as_one_made_anew() { + // Functions of 12 variables put together at random, and conditions + // of two to five of them (repeats and constants among them), under + // budgets that run out early, late and never: the answer, and where + // no lane is found the budget left, are those of the search that + // remembers nothing; with what one `Meets` gathered over all of + // them, and with an empty one. + let mut b = Bools::new(); + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut random = move |n: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % n as u64) as usize + }; + let mut f: Vec<Bool> = (0..12).map(|i| b.atom(Atom::Constant(i + 2), 0)).collect(); + f.extend([Bool::FALSE, Bool::TRUE]); + for _ in 0..120 { + let (x, y) = (f[random(f.len())], f[random(f.len())]); + let made = match random(4) { + 0 => b.and(x, y), + 1 => b.or(x, y), + 2 => b.xor(x, y), + _ => b.not(x), + }; + f.push(made); + } + let mut seen = Meets::default(); + let (mut none, mut some, mut gave_up) = (0, 0, 0); + for _ in 0..1500 { + let all: Vec<(Bool, bool)> = (0..2 + random(4)) + .map(|_| (f[random(f.len())], random(2) == 0)) + .collect(); + for budget in [0, 1, 2, 3, 5, 9, 20, 60, 250, 1000, MAX_MEET] { + let mut left = budget; + let anew = meet_anew(&b, all.clone(), &mut left); + for fresh in [false, true] { + let mut empty = Meets::default(); + let seen = if fresh { &mut empty } else { &mut seen }; + let mut work = all + .iter() + .map(|&(x, holds)| x.0 << 1 | u32::from(holds)) + .collect(); + let mut mine = budget; + let found = b.meet_in(0, &mut work, &mut mine, seen); + assert_eq!(found, anew, "{all:?} within {budget}"); + assert!(work.is_empty()); + if !found { + assert_eq!(mine, left, "{all:?} within {budget}"); + } + } + assert_eq!(b.meet_within(&all, budget, &mut seen), anew); + if !anew { + none += 1; + } else if meet_anew(&b, all.clone(), &mut usize::MAX.clone()) { + some += 1; + } else { + gave_up += 1; + } + } + } + // All three outcomes came up, and searches were remembered. + assert!( + none > 100 && some > 100 && gave_up > 100, + "{none} {some} {gave_up}" + ); + assert!(seen.none.len() > 100); + } + + #[test] + fn divergent_if_becomes_a_lane_branch() { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE80_3C6A, // s_and_saveexec_b32 s0, vcc_lo + 0xBF88_0001, // s_cbranch_execz -> 16 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x887E_007E, // 16: s_or_b32 exec_lo, exec_lo, s0 + 0x7E04_0280, // v_mov_b32 v2, 0 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let LaneExit::Branch { + when, + taken: 2, + not_taken: 1, + } = s.exits[0] + else { + panic!("{:?}", s.exits) + }; + // Skipped exactly where the compare fails. + let cmp = p.blocks[0].insts[0].write(Reg::S(VCC)).unwrap(); + assert_eq!( + s.bools.node(when), + Some((Atom::Lane(cmp), Bool::TRUE, Bool::FALSE)) + ); + assert_eq!(guarded(&s), 0, "{:?}", s.guards); + } + + #[test] + fn exec_narrowed_without_a_branch_leaves_a_guard() { + let p = build( + &[ + 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + assert_eq!(s.guards[0][0], None, "the compare runs in every lane"); + let g = s.guards[0][1].expect("guard"); + assert!(matches!(s.bools.support(g)[..], [Atom::Lane(_)])); + } + + #[test] + fn divergent_loop_exits_per_lane() { + let p = build( + &[ + 0xBE82_0480, // s_mov_b64 s[2:3], 0 + 0x4A00_0081, // 4: v_add_nc_u32 v0, 1, v0 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x8882_026A, // s_or_b64 s[2:3], vcc, s[2:3] + 0x8AFE_027E, // s_andn2_b64 exec, exec, s[2:3] + 0xBF89_FFFB, // s_cbranch_execnz -> 4 + 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + assert_eq!(guarded(&s), 0, "{:?}", s.guards); + let LaneExit::Branch { + when, + taken: 1, + not_taken: 2, + } = s.exits[1] + else { + panic!("{:?}", s.exits) + }; + // Back while the lane's compare fails. + assert!(matches!( + s.bools.node(when), + Some((Atom::Lane(_), Bool::TRUE, Bool::FALSE)) + )); + } + + /// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning + /// programs): the loop is left when no lane remains, so the select takes + /// its second operand; it was a uniform atom whose value no lane has. + #[test] + fn a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand() { + let cnd = 256 | (256 << 9) | (3 << 18); + let p = build( + &[ + 0xBE83_037E, // 0: s_mov_b32 s3, exec_lo + 0xBE9C_037E, // s_mov_b32 s28, exec_lo + 0x7E3A_0507, // 8: v_readfirstlane_b32 s29, v7 + 0x7DA4_0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7 + 0xBE9C_471C, // s_andn2_wrexec_b32 s28, s28 + 0xBF89_FFFC, // s_cbranch_execnz -> 8 + 0xBEFE_0303, // s_mov_b32 exec_lo, s3 + 0x8503_807E, // s_cselect_b32 s3, exec_lo, 0 + 0xD501_0001, + cnd, // v_cndmask_b32 v1, v0, v0, s3 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let select = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.name() == "s_cselect_b32") + .expect("the select"); + let mask = select.write(Reg::S(3)).unwrap(); + assert_eq!(s.masks.get(&mask), Some(&Bool::FALSE)); + } + + #[test] + fn scalar_branches_stay_uniform() { + let p = build( + &[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12 + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, // 12 + ], + true, + ); + let s = structure(&p).unwrap(); + let LaneExit::Branch { when, .. } = s.exits[0] else { + panic!() + }; + assert!(matches!(s.bools.support(when)[..], [Atom::Uniform(_)])); + assert_eq!(guarded(&s), 0); + } + + #[test] + fn a_mask_whose_high_dword_is_rewritten_is_not_the_compare() { + for reader in [ + 0x0202_0480, // v_cndmask_b32 v1, 0, v2, vcc + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ] { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + reader, + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let lo = p.blocks[0].insts[2].read(Reg::S(VCC)).unwrap(); + assert_eq!(p.blocks[0].insts[0].write(Reg::S(VCC)), Some(lo)); + // The reader sees (compare low dword, 0): lanes 32-63 are clear. + // The mask exported for that low dword must not be the compare. + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)), + "{reader:#x}: vcc_hi was zeroed after the compare" + ); + } + } + + #[test] + fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x0202_0480, // 4: v_cndmask_b32 v1, 0, v2, vcc + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + 0xBF85_FFFC, // s_cbranch_scc1 -> 4 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + // The select reads the loop header's join; over the back edge it + // takes (compare low dword, 0), which only the join sees. + let lo = p.blocks[1].insts[1].write(Reg::S(VCC)).unwrap(); + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)) + ); + } + + #[test] + fn irreducible_loops_are_split() { + let p = build( + &[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12, into the loop's middle + 0x8002_8102, // 8: s_add_u32 s2, s2, 1 + 0xBF84_FFFE, // 12: s_cbranch_scc0 -> 8 + S_ENDPGM, + ], + false, + ); + // The loop keeps 12 as its header; the entry into 8 gets a copy of it. + let copy = &p.blocks[4]; + assert_eq!((copy.offset, copy.exit), (8, ir::Exit::Jump(2))); + assert_eq!(p.blocks[0].exit.successors(), [2, 4]); + assert_eq!(p.blocks[1].preds, [2]); + assert!(structure(&p).is_ok()); + } + + #[test] + fn mask_phi_joining_constant_and_compare_records_edge_bools() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBF06_8000, // 0: s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // 4: s_cbranch_scc1 -> 16 + 0xBE82_0380, // 8: s_mov_b32 s2, 0 + 0xBF82_0002, // 12: s_branch -> 24 + 0xD4C2_0002, + 0x0002_0080, // 16: v_cmp_eq_u32 s2, 0, v0 + 0xD501_0001, + cnd, // 24: v_cndmask_b32 v1, v2, v3, s2 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("mask phi for s2"); + assert_eq!( + s.masks.get(&phi.value).and_then(|&m| s.bools.node(m)), + Some((Atom::Phi(phi.value), Bool::FALSE, Bool::TRUE)) + ); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); + } + + #[test] + fn loop_mask_accumulator_from_zero_tracks_phi_and_edges() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBE82_0480, // 0: s_mov_b64 s[2:3], 0 + 0xBE84_0380, // 4: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3] + 0x7D84_0080, // 16: v_cmp_eq_u32 vcc, 0, v0 + 0x8882_026A, // 20: s_or_b64 s[2:3], vcc, s[2:3] + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFF9, // 32: s_cbranch_scc1 -> 8 + 0xD501_0004, + cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3] + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s[2:3]"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!(edges.iter().any(|&e| { + let sup = s.bools.support(e); + sup.contains(&Atom::Phi(phi.value)) && sup.iter().any(|a| matches!(a, Atom::Lane(_))) + })); + } + + #[test] + fn loop_mask_phi_reset_to_constant_on_back_edge() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xD4C2_0002, + 0x0002_0080, // 0: v_cmp_eq_u32 s2, 0, v0 + 0xBE84_0380, // 8: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 12: v_cndmask_b32 v1, v2, v3, s2 + 0xBE82_0380, // 20: s_mov_b32 s2, 0 + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFFA, // 32: s_cbranch_scc1 -> 12 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s2"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); + } +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 000000000..4952df31f --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,99 @@ +# Architecture + +``` + user's files (outside repo) VIctory + ─────────────────────────── ───────────────────────────────────────── + game assets ──────────────────────────► victory-pipeline + victory-game + (victory-formats, victory-shader) + │ + â–¼ + cache_dir: converted data + │ + game executable ─► victory-loader ────► title code (native x86-64) + prepare, map, bind │ imports + â–¼ + victory-hle ── host Windows (shared APIs) + │ D3D12.X + â–¼ + victory-gpu ─► host D3D12 + │ shaders at pipeline creation + â–¼ + victory-shader ◄─► cache_dir +``` + +Shaders are translated when the title creates a pipeline, from the bytes it +passes, wherever it loaded them from (executable, archive, memory). +Converting them ahead of time from files is only a warm-up. + +## Crates + +| Crate | Role | +|-------|------| +| `victory-core` | config, asset-policy guard, logging | +| `victory-pe` | read-only PE32+ and import-library analysis | +| `victory-loader` | prepare, map, bind and start the title image | +| `victory-hle` | console API implementations, host pass-through policy | +| `victory-gpu` | D3D12.X objects, command lists and GPU memory → host D3D12 | +| `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 | +| `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 | + +Everything except `victory-game` is platform-level and can be tested with +any Xbox Series title. + +## Import resolution + +For every `dll!function` the title imports, in order: + +1. our implementation in `victory-hle::modules` (always wins); +2. the host's own function, if `HostPolicy` allows that DLL; +3. an export of a DLL the title ships beside its executable, mapped like + the executable (only DLLs neither of the above serves); +4. a generated stub that names the import when called (`--unimplemented + trap` breaks into the debugger and aborts; `zero` logs once and returns 0). + +`LoadLibrary*` of a console-only DLL we implement (e.g. `xgameruntime.dll`) +returns a pseudo handle; `GetProcAddress` on it finds our functions. +`LoadLibrary*` of a title DLL returns its mapped image, mapping it first if +nothing imports it. By name, as by import, a title gets only host DLLs +`HostPolicy` passes through, and `GetProcAddress` on one returns our +override where import binding would. +`QueryApiImpl` hands out our runtime objects by provider and interface id +(`victory-hle::modules::xgameruntime` lists the areas); online areas answer +as an offline console. Game saves are files under `VICTORY_DATA_DIR`. + +Title storage is a drive on the console, and titles build paths on that. +`victory-hle::modules::files` binds every path-taking title import +(kernel32 and the C/C++ runtime) and rewrites paths on a virtual drive to +the host folder behind it; persistent local storage is one such drive over +a folder under `VICTORY_DATA_DIR`. Other paths reach the host unchanged. + +An exe's code reaches its static TLS as slot 0; mapped as a DLL it gets +another slot, so the loader redirects those loads (`victory-loader::tls`). +`victory run --execute` installs a crash reporter that names faults as +`module+rva` and unwinds the faulting thread's stack +(`victory-loader::crash`). + +`victory census` shows this classification without running anything (it +does not map title DLLs; `victory run` without `--execute` does). + +## Shaders + +`victory_shader::ir::build` turns a native program into SSA, one +instruction per machine instruction. `victory_shader::structure` then +removes EXEC: lane masks become per-lane booleans, wave-wide mask tests +become per-lane branches, and vector instructions keep a guard only where +a lane can reach them with its EXEC bit clear. `victory_shader::resource` +traces each descriptor and scalar memory address to the root parameter it +comes from (table, heap, root descriptor or constant). A descriptor a +waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced +to the per-lane load or choice that gives each lane its own (a mask's +`v_cndmask_b32`, or an if/else whose arms each set it: traced on the paths +the lanes take, from structurisation), and accessed with a non-uniform heap +index in one pass. `victory translate` +runs every shader it finds (containers, SGD5 files) through these and +lists what they cannot handle yet. diff --git a/docs/asset-policy.md b/docs/asset-policy.md new file mode 100644 index 000000000..f87c84f06 --- /dev/null +++ b/docs/asset-policy.md @@ -0,0 +1,60 @@ +# Asset policy (rule #1) + +**Nothing from the game is ever stored in this repository.** Everything is +built on the user's machine from files the user supplies. The same applies +to other titles used for testing, and to any other proprietary material. + +## Not allowed + +In any form (files, string literals, fixtures, snapshots, docs): + +* assets: models, textures, shaders, audio, video, text, archives; +* the executable or any part of it: data sections, strings, tables, + resources, code beyond the signatures below; +* anything derived from those: converted assets, decompiled or + disassembled code, shader dumps, extracted tables, screenshots. + +## Allowed + +* our own code that understands formats; +* build identities: BLAKE3 of an executable, CodeView GUID/age; +* per-build offsets of functions we hook, under names we choose; +* byte-pattern signatures that locate functions or data in the executable; +* small interoperability constants (magic numbers, enum values) we write; +* synthetic test data generated by our own code. + +## The one exception + +`crates/victory-formats/src/bcpack-tables.bin` (about 78 KB): the constant +tables of the BCPack format (entropy models, index rank tables, control +codes, per-format dictionaries). A BCPack stream cannot be decoded without +exactly these tables and they cannot be derived, so they ship with VIctory +by the project owner's decision (2026-11-23), entered as an exception in +`xtask/src/policy.rs`. They are part of the format, not our work, and the +repository's licence does not cover them. Nothing else of this kind is +accepted. + +## Where data lives + +Outside the repository, configured in `victory.toml`: `game_dir` (the +user's dump), `test_titles`, and `cache_dir` for everything derived +(default `%LOCALAPPDATA%\victory\cache`). + +## Enforcement + +1. `.gitignore` keeps common data types out of `git status`. +2. `cargo xtask policy` (run by the pre-commit hook; install with + `cargo xtask install-hooks`) is an allowlist: files must have an allowed + type, be under 512 KiB, contain no binary data or known binary + signatures, and hold no long hex/base64 runs. Exceptions need an entry + with a reason in `xtask/src/policy.rs`. +3. At runtime, everything that writes derived data calls + `victory_core::ensure_outside_repo`. +4. Tests that need real files take their paths from environment variables + and skip when unset. They assert on properties, never on snapshots. + +## If something slips through + +A follow-up commit is not enough. Rewrite history +(`git filter-repo --path <file> --invert-paths`), force-push, and have +everyone re-clone. diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md new file mode 100644 index 000000000..0dbfc4236 --- /dev/null +++ b/docs/fork-ray-tracing.md @@ -0,0 +1,85 @@ +# Ray tracing in this fork: what the title does and what has been built + +Status, 2026-11-25: **nothing is lit by ray tracing yet.** Most of the +machinery translates and is unit-tested; it has not yet run end to end in the +game. Everything here is off by default. + +## What the title does + +Grand Theft Auto VI'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. + +The title does not use a ray-tracing API: + +- Traversal is ordinary compute-shader code: a per-thread stack in shared + memory, and loads through raw 40-bit addresses of title memory. +- The static world's acceleration structures ship pre-built in the title's + data, in the console GPU's native node format (64-byte nodes: box nodes with + four children and 16-bit float bounds, 128-byte box nodes with 32-bit float + bounds, triangle nodes, instance nodes). They are unpacked on the GPU. +- A set of builder programs (from the title's `XboxBvhBuilder.dll`, 52 compute + programs) builds and refits the dynamic structures on the GPU every frame. +- Only the per-node test is hardware: the instructions + `image_bvh64_intersect_ray` and `image_bvh_intersect_ray`. One call tests a + ray against a box node's four children (returning the hit children, nearest + first) or against a triangle node (returning the intersection's numerator, + denominator and barycentric numerators). + +So mapping this onto the host's own ray tracing (DXR) is not practical: the +layer would have to know the geometry behind structures the title never +describes to it, and the traversal loops live in 64 of the title's own +programs. This fork runs the title's builder and traversal as translated +shaders and emulates the one instruction. + +## What this fork adds + +1. **The builder programs translate** (49 of 52; all that the title creates in + the scenes tested). They pass buffer addresses in a spilled parameter table + rather than in descriptors. Added: the spilled user-data table, root + unordered-access views (translator and host binding), byte and 16-bit buffer + accesses, and several control-flow shapes. +2. **Title memory by raw address from shaders.** A directory with one entry per + 64 KiB of title address space leads a shader to the layer's host copy of + that memory; loads, stores, atomic add/sub and float min/max go through it. + Before a dispatch the host makes ready the memory its root views and root + constants name. +3. **The ray test, emulated in DXIL.** Four slab tests and a sorting network + for box nodes; a watertight ray/triangle test for triangle nodes; both forms + of the instruction. A plain Rust reference lives in + `crates/victory-shader/src/bvh.rs`; tests run the emitted DXIL on the GPU + over 311 ray/node cases and compare with the reference bit for bit. +4. **The trace and shading programs translate** (59 of 64 trace programs, and + the irradiance-cache shading program). This needed lane masks treated as + plain numbers on some paths, and exact forms for programs written for + 64-lane waves running on a GPU with 32-lane waves. +5. **A safety rule on the host side.** The builder's stages run only while + every builder pipeline the title has created has a host pipeline; otherwise + none run (`VICTORY_BVH_BUILDER=1` asks for it; `VICTORY_BVH_QUARANTINE=1` + also keeps the builder's stores out of title memory, for a first test). A + partly working builder wrote garbage bounds into title memory and crashed + the title. + +## Known gaps + +- With `VICTORY_BVH_BUILDER=1` the builder still stays off in a real run: a few + of its pipelines are refused by the host (they still ask for 64-lane waves on + a 32-lane GPU) or do not translate. +- Five shadow-mask trace programs do not translate yet. +- An access to a title page that has no host copy is lost (a read gives zero, a + store is dropped). +- Not publicly documented, and assumed: the instruction's rounding, the order + of two boxes entered at the same distance, and the result for a ray exactly + through an edge. +- Cost on the GPU is unmeasured. + +## Where to look + +- `crates/victory-shader/src/bvh.rs`: the reference for the node test. +- `crates/victory-shader/src/emit/lower.rs`: the lowering of the two + instructions and of memory by address (`Lower::memory`). +- `crates/victory-shader/src/resource.rs`: address tracking for descriptors + and raw addresses. +- `crates/victory-gpu/src/pipeline.rs`, `draw.rs`: the builder rule and the + host side of root views and title memory. diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 000000000..080921b01 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,5 @@ +[toolchain] +channel = "1.98.1" +targets = ["x86_64-pc-windows-msvc"] +components = ["rustfmt", "clippy"] +profile = "minimal" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..8d1691c59 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 100 +use_field_init_shorthand = true diff --git a/tests/fixtures/hle-probe/Cargo.lock b/tests/fixtures/hle-probe/Cargo.lock new file mode 100644 index 000000000..354c81d8f --- /dev/null +++ b/tests/fixtures/hle-probe/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "hle-probe" +version = "0.0.0" diff --git a/tests/fixtures/hle-probe/Cargo.toml b/tests/fixtures/hle-probe/Cargo.toml new file mode 100644 index 000000000..6c7f87b22 --- /dev/null +++ b/tests/fixtures/hle-probe/Cargo.toml @@ -0,0 +1,18 @@ +# A tiny stand-in for an Xbox title, used by victory-loader's integration +# tests. It is NOT a workspace member: the tests build it on demand into its +# own target directory. It imports from DLLs that do not exist on a PC +# (via raw-dylib), so it can only work when loaded through victory-loader. +[package] +name = "hle-probe" +version = "0.0.0" +edition = "2024" +license = "GPL-3.0-or-later" +publish = false + +[lib] +crate-type = ["cdylib"] + +[profile.dev] +panic = "abort" + +[workspace] diff --git a/tests/fixtures/hle-probe/build.rs b/tests/fixtures/hle-probe/build.rs new file mode 100644 index 000000000..45ab457ed --- /dev/null +++ b/tests/fixtures/hle-probe/build.rs @@ -0,0 +1,4 @@ +fn main() { + println!("cargo:rustc-link-arg-cdylib=/DELAYLOAD:victory-probe-delayed.dll"); + println!("cargo:rustc-link-lib=delayimp"); +} diff --git a/tests/fixtures/hle-probe/src/lib.rs b/tests/fixtures/hle-probe/src/lib.rs new file mode 100644 index 000000000..1eca794ce --- /dev/null +++ b/tests/fixtures/hle-probe/src/lib.rs @@ -0,0 +1,123 @@ +//! A stand-in for a title, written by us. It imports from DLLs that do not +//! exist on a PC, which is exactly the situation victory-loader handles. +//! Loaded normally, this DLL would fail with "module not found". + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; + +const DLL_THREAD_ATTACH: u32 = 2; + +#[link(name = "xgameruntime", kind = "raw-dylib")] +unsafe extern "system" { + fn XGameRuntimeInitialize() -> i32; +} + +#[link(name = "victory-probe-missing", kind = "raw-dylib")] +unsafe extern "system" { + fn VIctoryProbeNotImplemented(x: u64) -> u64; +} + +// A DLL the "title" ships; the test supplies a renamed copy of version.dll. +#[link(name = "victory-probe-title", kind = "raw-dylib")] +unsafe extern "system" { + fn GetFileVersionInfoSizeW(path: *const u16, handle: *mut u32) -> u32; +} + +// Delay-loaded (see build.rs): bound through the delay-load table. +#[link(name = "victory-probe-delayed", kind = "raw-dylib")] +unsafe extern "system" { + fn VIctoryProbeDelayed() -> u32; +} + +#[link(name = "kernel32")] +unsafe extern "system" { + fn GetTickCount() -> u32; + fn GetCurrentProcessId() -> u32; +} + +/// Console-only API, answered by the resolver's HLE implementation. +#[unsafe(no_mangle)] +pub extern "system" fn probe_xgameruntime_init() -> i32 { + unsafe { XGameRuntimeInitialize() } +} + +/// Exists on the host too, but the resolver overrides it. +#[unsafe(no_mangle)] +pub extern "system" fn probe_tick() -> u32 { + unsafe { GetTickCount() } +} + +/// Exists on the host and is passed through to it. +#[unsafe(no_mangle)] +pub extern "system" fn probe_pid() -> u32 { + unsafe { GetCurrentProcessId() } +} + +/// An export of a title-shipped DLL: the version-info size of kernel32.dll. +#[unsafe(no_mangle)] +pub extern "system" fn probe_title() -> u32 { + let path: Vec<u16> = r"C:\Windows\System32\kernel32.dll" + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut handle = 0; + unsafe { GetFileVersionInfoSizeW(path.as_ptr(), &mut handle) } +} + +/// A delay-loaded console API. +#[unsafe(no_mangle)] +pub extern "system" fn probe_delayed() -> u32 { + unsafe { VIctoryProbeDelayed() } +} + +/// Nobody implements this one: it must land in an unimplemented-import stub. +#[unsafe(no_mangle)] +pub extern "system" fn probe_missing() -> u64 { + unsafe { VIctoryProbeNotImplemented(42) } +} + +static TLS_THREAD_STARTS: AtomicU32 = AtomicU32::new(0); +static MAIN_THREAD_STARTS: AtomicU32 = AtomicU32::new(0); + +/// A TLS callback, as titles have: counts thread starts. +unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) { + if reason == DLL_THREAD_ATTACH { + TLS_THREAD_STARTS.fetch_add(1, Ordering::Relaxed); + } +} + +#[used] +#[unsafe(link_section = ".CRT$XLB")] +static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread; + +/// Called by the CRT's DLL entry point: counts thread starts too, and calls +/// an import the resolver overrides, as title code calls our runtime. +#[unsafe(no_mangle)] +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); + unsafe { GetTickCount() }; + } + if reason == DLL_PROCESS_DETACH { + DETACHES.fetch_add(1, Ordering::Relaxed); + } + 1 +} + +const DLL_PROCESS_DETACH: u32 = 0; +static DETACHES: AtomicU32 = AtomicU32::new(0); + +/// `DLL_PROCESS_DETACH` notices seen by `DllMain`. +#[unsafe(no_mangle)] +pub extern "system" fn probe_detaches() -> u32 { + DETACHES.load(Ordering::Relaxed) +} + +/// Thread starts seen by the TLS callback (high half) and `DllMain` (low). +#[unsafe(no_mangle)] +pub extern "system" fn probe_thread_starts() -> u64 { + // SAFETY: reading our own static keeps the linker from dropping it. + unsafe { std::ptr::from_ref(&ON_THREAD).read_volatile() }; + u64::from(TLS_THREAD_STARTS.load(Ordering::Relaxed)) << 32 + | u64::from(MAIN_THREAD_STARTS.load(Ordering::Relaxed)) +} diff --git a/victory.example.toml b/victory.example.toml new file mode 100644 index 000000000..0b37ff210 --- /dev/null +++ b/victory.example.toml @@ -0,0 +1,19 @@ +# Copy to `victory.toml` (git-ignored) and point it at YOUR files. +# Every path must be OUTSIDE the repository; the tools refuse otherwise. +# Environment variables (shown below) take precedence over this file. +# VICTORY_CONFIG selects a different config file. + +[paths] +# Your own dump of Grand Theft Auto VI. env: VICTORY_GAME_DIR +game_dir = 'D:\victory-data\game' + +# Derived data. Default: %LOCALAPPDATA%\victory\cache. env: VICTORY_CACHE_DIR +# cache_dir = 'D:\victory-data\cache' + +# What titles save (persistent local storage), kept apart from the cache. +# Default: %LOCALAPPDATA%\victory\data. env: VICTORY_DATA_DIR +# data_dir = 'D:\victory-data\data' + +# Other Xbox Series titles used to test platform-level code. +# env: VICTORY_TEST_TITLES (separated by ';') +test_titles = [] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 000000000..d8e74bfea --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "xtask" +description = "Repository maintenance: asset-policy enforcement and git hooks." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow.workspace = true +clap.workspace = true +walkdir.workspace = true + +[lints] +workspace = true diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 000000000..911ed8087 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,56 @@ +//! Repository maintenance. Run with `cargo xtask <command>`. + +mod policy; + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[command(name = "xtask")] +struct Cli { + #[command(subcommand)] + command: Cmd, +} + +#[derive(Subcommand)] +enum Cmd { + /// Enforce the asset policy: the repository holds only small text files + /// we wrote. Checks tracked and untracked-but-not-ignored files. + Policy { + /// Check only what is staged for commit (used by the pre-commit hook). + #[arg(long)] + staged: bool, + }, + /// Point git at .githooks/ so every commit runs the policy check. + InstallHooks, +} + +fn main() -> Result<()> { + let root = workspace_root(); + match Cli::parse().command { + Cmd::Policy { staged } => policy::run(&root, staged), + Cmd::InstallHooks => { + let status = Command::new("git") + .args(["config", "core.hooksPath", ".githooks"]) + .current_dir(&root) + .status() + .context("running git")?; + anyhow::ensure!( + status.success(), + "git config failed (is this a git repository?)" + ); + println!("hooks installed: commits now run `cargo xtask policy --staged`"); + Ok(()) + } + } +} + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("xtask lives in the workspace") + .into() +} diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs new file mode 100644 index 000000000..9bcf24cc8 --- /dev/null +++ b/xtask/src/policy.rs @@ -0,0 +1,223 @@ +//! Rule #1, statically: the repository only ever contains small text files +//! that we wrote. See docs/asset-policy.md. +//! +//! This is an allowlist, not a blocklist: a file passes only if its name is +//! on the list, it is not too big, it is text, and it does not smuggle data +//! inside text (long hex/base64 runs). + +use std::path::Path; +use std::process::Command; + +use anyhow::{Context, Result, bail}; + +const MAX_FILE_SIZE: usize = 512 * 1024; +const MAX_ENCODED_RUN: usize = 512; + +const ALLOWED_EXTENSIONS: &[&str] = &[ + "rs", "toml", "md", "txt", "lock", "yml", "yaml", "json", "hlsl", "hlsli", "ps1", "cmd", "sh", +]; +const ALLOWED_NAMES: &[&str] = &[ + ".gitignore", + ".gitattributes", + ".editorconfig", + ".victory-root", + "pre-commit", + "LICENSE", + "LICENSE-MIT", + "LICENSE-APACHE", +]; + +/// Paths explicitly exempted, with a reason. Keep this empty if at all possible. +const EXCEPTIONS: &[(&str, &str)] = &[( + "crates/victory-formats/src/bcpack-tables.bin", + "the BCPack format's constant tables: nothing decodes without them and they cannot be derived (owner's decision, 2026-11-23; docs/asset-policy.md)", +)]; + +/// Signatures of formats that must never be committed. +const FORBIDDEN_MAGIC: &[(&[u8], &str)] = &[ + (b"MZ", "PE executable"), + (b"DXBC", "shader container"), + (b"DDS ", "DDS texture"), + (b"RIFF", "RIFF (audio/video)"), + (b"BC\xC0\xDE", "LLVM bitcode"), + (b"Microsoft C/C++ MSF", "PDB"), + (b"!<arch>", "library archive"), + (b"PK\x03\x04", "zip"), + (b"7z\xBC\xAF", "7-zip"), + (b"MSCF", "cabinet"), + (b"\xD0\xCF\x11\xE0", "MSI/OLE"), +]; + +pub fn run(root: &Path, staged: bool) -> Result<()> { + let files = list_files(root, staged)?; + let mut violations = Vec::new(); + for path in &files { + if EXCEPTIONS.iter().any(|(p, _)| p == path) { + continue; + } + let content = if staged { + let out = Command::new("git") + .args(["show", &format!(":{path}")]) + .current_dir(root) + .output()?; + if !out.status.success() { + continue; // deleted in the index + } + out.stdout + } else { + match std::fs::read(root.join(path)) { + Ok(c) => c, + Err(_) => continue, + } + }; + for problem in check(path, &content) { + violations.push(format!("{path}: {problem}")); + } + } + if violations.is_empty() { + println!("asset policy: {} files ok", files.len()); + return Ok(()); + } + for v in &violations { + eprintln!("POLICY: {v}"); + } + bail!( + "{} asset-policy violation(s). Nothing from the game may be committed; \ + see docs/asset-policy.md", + violations.len() + ) +} + +fn list_files(root: &Path, staged: bool) -> Result<Vec<String>> { + let git = |args: &[&str]| -> Result<Option<Vec<String>>> { + let out = Command::new("git") + .args(args) + .current_dir(root) + .output() + .context("running git")?; + if !out.status.success() { + return Ok(None); + } + Ok(Some( + out.stdout + .split(|&b| b == 0) + .filter(|s| !s.is_empty()) + .map(|s| String::from_utf8_lossy(s).replace('\\', "/")) + .collect(), + )) + }; + if staged { + return git(&[ + "diff", + "--cached", + "--name-only", + "--diff-filter=ACMR", + "-z", + ])? + .context("--staged needs a git repository"); + } + if let Some(mut tracked) = git(&[ + "ls-files", + "-z", + "--cached", + "--others", + "--exclude-standard", + ])? { + tracked.sort(); + tracked.dedup(); + return Ok(tracked); + } + // Not a git repository: walk everything except build output. + Ok(walkdir::WalkDir::new(root) + .into_iter() + .filter_entry(|e| !matches!(e.file_name().to_str(), Some("target" | ".git"))) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()) + .filter_map(|e| { + e.path() + .strip_prefix(root) + .ok() + .map(|p| p.to_string_lossy().replace('\\', "/")) + }) + .collect()) +} + +/// All problems with one file. Pure, for testing. +pub fn check(path: &str, content: &[u8]) -> Vec<String> { + let mut problems = Vec::new(); + let name = path.rsplit('/').next().unwrap_or(path); + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()); + let allowed = ALLOWED_NAMES.contains(&name) + || ext + .as_deref() + .is_some_and(|e| ALLOWED_EXTENSIONS.contains(&e)); + if !allowed { + problems.push("file type not on the allowlist".to_owned()); + } + if content.len() > MAX_FILE_SIZE { + problems.push(format!( + "{} bytes exceeds the {MAX_FILE_SIZE}-byte limit", + content.len() + )); + } + for (magic, what) in FORBIDDEN_MAGIC { + if content.starts_with(magic) { + problems.push(format!("looks like a {what}")); + } + } + if content.contains(&0) { + problems.push("binary content (NUL bytes)".to_owned()); + } else if let Some(run) = longest_encoded_run(content) + && run > MAX_ENCODED_RUN + { + problems.push(format!("{run}-character hex/base64 run (embedded data?)")); + } + problems +} + +/// Longest run of characters that could be hex or base64 payload. +fn longest_encoded_run(content: &[u8]) -> Option<usize> { + let is_payload = |b: &u8| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='); + content.split(|b| !is_payload(b)).map(<[u8]>::len).max() +} + +#[cfg(test)] +mod tests { + use super::check; + + /// Enforces the policy wherever tests run, even in clones without the hook. + #[test] + fn repository_passes_policy() { + super::run(&crate::workspace_root(), false).unwrap(); + } + + #[test] + fn accepts_source() { + assert!(check("crates/x/src/lib.rs", b"fn main() {}\n").is_empty()); + assert!(check(".gitignore", b"/target/\n").is_empty()); + assert!(check(".githooks/pre-commit", b"#!/bin/sh\n").is_empty()); + } + + #[test] + fn rejects_game_like_files() { + assert!(!check("assets/tex.dds", b"DDS \x7c\0\0\0").is_empty()); + assert!( + !check("notes.txt", b"MZ\x90\0").is_empty(), + "magic wins over extension" + ); + assert!( + !check("data.bin", b"hello").is_empty(), + "extension not allowed" + ); + assert!( + !check("a.rs", &vec![b'a'; 600 * 1024]).is_empty(), + "too big" + ); + } + + #[test] + fn rejects_data_smuggled_into_text() { + let blob = format!("const DATA: &str = \"{}\";", "A1".repeat(400)); + assert!(!check("src/blob.rs", blob.as_bytes()).is_empty()); + } +} From ba0b1dc5d80785312d766ac58eaf74c9dff77d3f Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 10:12:03 -0500 Subject: [PATCH 02/57] Series S without DLSS: the title keeps its own upscaler, not FSR 4 (28.5 -> 30.9 fps in the prologue's cell) With `--console series-s` the title picks FSR 4 where a Series X uses its own upscaler. Here FSR 4 runs, through the translator, and it is the dearer of the two. Two functions of the known build that make the choice now return 6 (the Series X's), so the Series S profile renders with the title's own upscaler. Measured on an RTX 3090 Ti (driver 616.92), Ryzen 9 9950X3D, Windows 11, this fork's launcher settings with `-SeriesS` and no NVIDIA files, in the prologue's cell at 4,300 to 4,700 draws a frame, medians of the frame lines of one run each: FSR 4 own upscaler frames a second 28.5 30.9 frame 35.1 ms 32.4 ms title memory copied a frame 88 MB 38 MB copied back a frame 21.6 MB 0.8 MB The picture is the same in both as far as I can tell from screenshots (hair, the print on the shirt, the walls; the haze through the cell's window is there with either). Not applied when the title's FidelityFX path is asked for: DLSS, frame generation and VICTORY_FSR_PATH take the title's FidelityFX upscaler (`native_1440p::prepare_upscaler` patches the same function, at +0x7e9421), so `victory run` then leaves the choice to the title and says so. I have no NVIDIA files here: that the line is printed and no patch applied with VICTORY_FSR_PATH=1 is what I checked of that side. VICTORY_TITLE_PATCHES=0 turns the patches off; VICTORY_TITLE_PATCH=<rva>: <old hex>:<new hex> adds one for experiments. The patched image is cached under a name of its own. From fxceless/victory-fork#798 (same author), where FSR 4's frames were black on the Series S profile. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- apps/victory/src/run.rs | 72 +++++++++++++++++++++++- crates/victory-game/src/lib.rs | 71 +++++++++++++++++++++++- crates/victory-loader/src/prepare.rs | 83 +++++++++++++++++++++++++++- 3 files changed, 221 insertions(+), 5 deletions(-) diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index e218ae39e..425e6c6c9 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -81,10 +81,15 @@ pub fn run( let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; let mut prepared = victory_loader::prepare(&original)?; let hash = prepared.original_hash.to_hex(); - match victory_game::identify(&hash) { + let build = victory_game::identify(&hash); + match build { Some(build) => println!("build {} ({hash})", build.label), None => println!("build unknown ({hash})"), } + // (Not with the title's FidelityFX path asked for: DLSS, frame + // generation and `VICTORY_FSR_PATH` take the title's FidelityFX + // upscaler, which the known build's patches turn off.) + apply_title_patches(&mut prepared, build, upscaler.is_none())?; // A 1440p output instead of the Series X's 4K one (`native_1440p`): the // patched image goes to a folder of its own, beside the stock one. @@ -679,3 +684,68 @@ mod cpu_check_tests { pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> { anyhow::bail!("running titles requires Windows") } + +/// Bytes as lower-case hex. +#[cfg(windows)] +fn hex_str(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// The known build's code patches (`VICTORY_TITLE_PATCHES=0`: none; none +/// either unless `own_upscaler`: they make the title keep its own upscaler, +/// and the FidelityFX path of DLSS and frame generation needs the title's +/// choice left alone), then +/// any from `VICTORY_TITLE_PATCH=<rva>:<old hex>:<new hex>,...`. The old +/// bytes must be there (another build of the title is refused), and the +/// patched copy has a file name of its own. +#[cfg(windows)] +fn apply_title_patches( + prepared: &mut victory_loader::PreparedImage, + build: Option<&victory_game::KnownBuild>, + own_upscaler: bool, +) -> Result<()> { + let mut patches = Vec::new(); + let mut names = Vec::new(); + if !own_upscaler && build.is_some_and(|b| !b.patches.is_empty()) { + println!("title patch none: the title's FidelityFX path is asked for, its choice of upscaler is left to it"); + } else if std::env::var("VICTORY_TITLE_PATCHES").as_deref() != Ok("0") { + for p in build.map_or(&[][..], |b| b.patches) { + patches.push((p.rva, p.expect.to_vec(), p.write.to_vec())); + names.push(p.name.to_owned()); + } + } + let spec = std::env::var("VICTORY_TITLE_PATCH").unwrap_or_default(); + for one in spec.split(',').filter(|p| !p.trim().is_empty()) { + let parts: Vec<&str> = one.split(':').collect(); + anyhow::ensure!( + parts.len() == 3, + "VICTORY_TITLE_PATCH entry is not <rva>:<old>:<new>: {one}" + ); + let rva = u32::from_str_radix(parts[0].trim().trim_start_matches("0x"), 16)?; + patches.push((rva, from_hex(parts[1])?, from_hex(parts[2])?)); + names.push("VICTORY_TITLE_PATCH".to_owned()); + } + if patches.is_empty() { + return Ok(()); + } + prepared.patch(&patches)?; + for ((rva, old, new), name) in patches.iter().zip(names) { + println!( + "title patch +{rva:#x} {name}: {} -> {}", + hex_str(old), + hex_str(new) + ); + } + Ok(()) +} + +/// Bytes from hex digits. +#[cfg(windows)] +fn from_hex(s: &str) -> Result<Vec<u8>> { + let s = s.trim(); + anyhow::ensure!(s.len().is_multiple_of(2), "odd hex length: {s}"); + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(anyhow::Error::from)) + .collect() +} diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs index affa682b4..13e967eb5 100644 --- a/crates/victory-game/src/lib.rs +++ b/crates/victory-game/src/lib.rs @@ -12,10 +12,55 @@ pub struct KnownBuild { pub label: &'static str, /// BLAKE3 of the original executable, hex. pub blake3: &'static str, + /// Changes to its code made before it is mapped. + pub patches: &'static [CodePatch], } -/// Builds we support. Empty until the executable is available. -pub const KNOWN_BUILDS: &[KnownBuild] = &[]; +/// A change to title code: at `rva`, the bytes `expect` (a short signature +/// checked before anything is written) become `write`, our own code. +#[derive(Debug, Clone, Copy)] +pub struct CodePatch { + /// Our name for it, as logged. + pub name: &'static str, + pub rva: u32, + pub expect: &'static [u8], + pub write: &'static [u8], +} + +/// `mov eax, 6; ret`: the upscaler a Series X uses. +const UPSCALER_6: &[u8] = &[0xb8, 0x06, 0x00, 0x00, 0x00, 0xc3]; + +/// Builds we support. +pub const KNOWN_BUILDS: &[KnownBuild] = &[KnownBuild { + label: "Xbox Series master", + blake3: "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93", + // The title picks its upscaler by console: on a Series S with the + // FidelityFX upscaler's capability, FSR 4 (type 7), else its own + // (type 6, as on a Series X). Both functions that make the choice + // return 6, so a Series S runs its own render profile with its own + // upscaler. (From fxceless/victory-fork#798, where FSR 4's frames were + // black with `--console series-s`.) On this tree FSR 4 runs, through + // the translator, and costs: in the prologue's cell (RTX 3090 Ti, + // 4,300 to 4,700 draws a frame) a median of 28.5 frames a second with + // it against 30.9 without, 88 against 38 MB a frame of title memory + // copied for the card and 21.6 against 0.8 MB a frame copied back. + // Not applied when the title's FidelityFX path is asked for (DLSS, + // frame generation, `VICTORY_FSR_PATH`: `victory run` says so). + patches: &[ + CodePatch { + name: "upscaler choice", + rva: 0x7e_93f0, + expect: &[0x48, 0x83, 0xec, 0x28, 0x80, 0x3d], + write: UPSCALER_6, + }, + CodePatch { + name: "upscaler choice (the per-frame copy)", + rva: 0x540_0190, + expect: &[0x48, 0x83, 0xec, 0x28, 0x48, 0x8b], + write: UPSCALER_6, + }, + ], +}]; /// Looks up a build by the BLAKE3 hash of its executable. pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { @@ -23,3 +68,25 @@ pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { .iter() .find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_builds_are_well_formed() { + for build in KNOWN_BUILDS { + assert_eq!(build.blake3.len(), 64); + assert!(build.blake3.bytes().all(|b| b.is_ascii_hexdigit())); + assert_eq!( + identify(&build.blake3.to_uppercase()).map(|b| b.label), + Some(build.label) + ); + for patch in build.patches { + assert!(!patch.write.is_empty(), "{}", patch.name); + assert_eq!(patch.expect.len(), patch.write.len(), "{}", patch.name); + } + } + assert!(identify("00").is_none()); + } +} diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index c8935081b..48f36c3a7 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -22,12 +22,60 @@ pub struct PreparedImage { pub bytes: Vec<u8>, /// BLAKE3 of the original bytes: identifies the exact build. pub original_hash: blake3::Hash, + /// BLAKE3 of the title-code patches applied ([`PreparedImage::patch`]), + /// if any: part of the copy's file name, so a patched copy and the + /// plain one never stand in for each other. + pub patched: Option<blake3::Hash>, } impl PreparedImage { - /// File name for the patched copy, unique per original build. + /// File name for the patched copy, unique per original build (and per + /// set of title-code patches). pub fn file_name(&self) -> String { - format!("victory-image-{}.dll", &self.original_hash.to_hex()[..16]) + match &self.patched { + None => format!("victory-image-{}.dll", &self.original_hash.to_hex()[..16]), + Some(p) => format!( + "victory-image-{}-p{}.dll", + &self.original_hash.to_hex()[..16], + &p.to_hex()[..8] + ), + } + } + + /// Changes title code: each patch is (RVA, the bytes expected there, + /// the bytes to write). Every expected run is checked before anything + /// is written, so a patch made for another build of the title changes + /// nothing and is an error. + pub fn patch(&mut self, patches: &[(u32, Vec<u8>, Vec<u8>)]) -> Result<(), PrepareError> { + let mut at = Vec::with_capacity(patches.len()); + for (rva, old, new) in patches { + if old.len() != new.len() || new.is_empty() { + return Err(PrepareError::Patch( + "a title patch's old and new bytes differ in length", + )); + } + let offset = self + .info + .rva_to_file_offset(*rva) + .ok_or(PrepareError::Patch( + "a title patch's RVA is not file-backed", + ))? as usize; + if self.bytes.get(offset..offset + old.len()) != Some(old.as_slice()) { + return Err(PrepareError::Patch( + "a title patch's expected bytes are not there (another build?)", + )); + } + at.push(offset); + } + let mut id = blake3::Hasher::new(); + for ((rva, old, new), offset) in patches.iter().zip(at) { + self.bytes[offset..offset + new.len()].copy_from_slice(new); + id.update(&rva.to_le_bytes()); + id.update(old); + id.update(new); + } + self.patched = Some(id.finalize()); + Ok(()) } } @@ -110,6 +158,7 @@ pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> { info, bytes, original_hash: blake3::hash(original), + patched: None, }) } @@ -280,4 +329,34 @@ mod tests { let b = prepare(&original).unwrap(); assert_eq!(a.file_name(), b.file_name()); } + + #[test] + fn title_patches_check_before_they_write() { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let mut prepared = prepare(&original).unwrap(); + let plain = prepared.file_name(); + let section = prepared.info.sections[0].clone(); + let rva = section.rva + 16; + let at = prepared.info.rva_to_file_offset(rva).unwrap() as usize; + let old = prepared.bytes[at..at + 4].to_vec(); + let new: Vec<u8> = old.iter().map(|b| !b).collect(); + + // Wrong expected bytes (another build): an error, nothing written. + let before = prepared.bytes.clone(); + let wrong = (rva, new.clone(), old.clone()); + assert!( + prepared + .patch(&[(rva, old.clone(), new.clone()), wrong]) + .is_err() + ); + assert_eq!(prepared.bytes, before); + assert_eq!(prepared.file_name(), plain); + assert!(prepared.patch(&[(rva, old.clone(), vec![0])]).is_err()); + + prepared.patch(&[(rva, old.clone(), new.clone())]).unwrap(); + assert_eq!(&prepared.bytes[at..at + 4], new.as_slice()); + let patched = prepared.file_name(); + assert_ne!(patched, plain, "a patched copy has a file name of its own"); + assert!(patched.starts_with(plain.trim_end_matches(".dll"))); + } } From 69e0a9344b16777fce3e92eb75ea87aac0c774aa Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 10:12:35 -0500 Subject: [PATCH 03/57] Pipelines: the host first sees the static samplers in the same order in every launch On an NVIDIA card a pipeline library is only good for launches that first make their static samplers in the order of the launches that filled it. Seen on this tree (RTX 3090 Ti, driver 616.92, prologue's cell): a cache that launches of the Series S profile with FSR 4 and of the Series X profile at two sizes had filled; then a launch of the Series S profile with the title's own upscaler, which makes its pipelines in another order: the print on the back of the prologue's shirt was missing in every screenshot of the run. The same build on a library of its own had the print. With this change the first cache had it again, in two launches. Seen before on fxceless/victory-fork (its issue #1459, pull request #1461, same author): one more static sampler unlike the title's own, made before the title's first root signature and never bound, gave the wrong picture for the whole run in 20 runs of 20, against 0 of 12 without it. The reading that fits: the driver numbers a device's different static samplers in the order they are first made, a compiled pipeline names them by number, and a pipeline kept in the library keeps the numbers of the launch that compiled it. I cannot look inside the driver; what I have is that the case that went wrong comes out right with the order kept. So the order is kept. The static samplers a cache has seen are listed in static-samplers.txt beside the library (ten words a line), in the order they were first made. Before a launch's first root signature each is made again in that order, alone in a root signature that lives for the run; a sampler not listed yet goes to the list's end, and its own root signature is made under the same lock before the one that asked for it. A library with no list beside it was filled in whatever order its launches had: it is let go once (said in the log) and its pipelines are made again. The pipeline book is untouched, so `victory warm` makes them ahead as before. VICTORY_SAMPLER_ORDER=0: none of this. VICTORY_EXTRA_STATIC_SAMPLER=1 (diagnostics builds): one more static sampler before the title's first root signature, for reproducing the fault with the order off. Tests: three in the module (a sampler's line; a list's order and a line cut short; on the host device, a new sampler goes to the file's end and a second start reads the same order back). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/pipeline.rs | 2 + crates/victory-gpu/src/pipeline/host.rs | 3 + crates/victory-gpu/src/pipeline/library.rs | 32 ++ crates/victory-gpu/src/pipeline/samplers.rs | 366 ++++++++++++++++++++ 4 files changed, 403 insertions(+) create mode 100644 crates/victory-gpu/src/pipeline/samplers.rs diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index c462b0e25..cd627fe5d 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -767,6 +767,8 @@ pub(crate) mod host; #[cfg(windows)] pub mod known; #[cfg(windows)] +mod samplers; +#[cfg(windows)] mod library; #[cfg(windows)] mod make; diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 2e2d0bd55..0c16dd383 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -1063,6 +1063,9 @@ fn root_signature( let blob = blob.ok_or_else(windows::core::Error::empty)?; let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + // The host first sees different static samplers in the same order + // in every launch (`super::samplers`). + super::samplers::before(device, samplers, super::library::dir()); Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) } } diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index f81db5772..b3dec78b6 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -67,6 +67,11 @@ pub(super) fn folder() -> Option<PathBuf> { DIR.get().cloned() } +/// The folder of the library and the lists beside it, if one was given. +pub(super) fn dir() -> Option<&'static std::path::Path> { + DIR.get().map(PathBuf::as_path) +} + /// Host pipelines created, loaded from the library, and title pipelines /// started at creation, since the start. pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); @@ -496,6 +501,16 @@ fn library() -> Option<&'static Library> { LIBRARY .get_or_init(|| { let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?; + // A library filled before static samplers were made in a kept + // order (`super::samplers`) holds pipelines of any order: a + // pipeline loaded from it may sample with other samplers than + // its root signature names (fxceless/victory-fork#1459). It is let go once. + if let Some(d) = DIR.get() + && super::samplers::on() + && !super::samplers::listed_at_start(d) + { + unlisted(d); + } let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d)); let library = open(&device, blob); if library.is_none() { @@ -506,6 +521,23 @@ fn library() -> Option<&'static Library> { .as_ref() } +/// Removes the library in `dir`, and one a save left beside it: they were +/// filled with no list of static samplers beside them. +fn unlisted(dir: &std::path::Path) { + for name in [LIBRARY_FILE, NEXT_FILE] { + let path = dir.join(name); + let Ok(meta) = std::fs::metadata(&path) else { continue }; + match std::fs::remove_file(&path) { + Ok(()) => tracing::info!( + file = name, + mb = meta.len() >> 20, + "the host pipeline library of before the static samplers' kept order is let go: its pipelines are made again" + ), + Err(e) => tracing::warn!(error = %e, file = name, "an old host pipeline library could not be removed; it is used as it is"), + } + } +} + /// 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: Blob) -> Option<Library> { diff --git a/crates/victory-gpu/src/pipeline/samplers.rs b/crates/victory-gpu/src/pipeline/samplers.rs new file mode 100644 index 000000000..ab15c9fec --- /dev/null +++ b/crates/victory-gpu/src/pipeline/samplers.rs @@ -0,0 +1,366 @@ +//! The order in which the host first sees the different static samplers, +//! kept the same in every launch. +//! +//! What was measured (RTX 3090 Ti, driver 616.92, the Series S profile, the +//! prologue's cell; first on fxceless/victory-fork, its issue #1459, then on +//! this tree): the title's picture depended on which launches had filled +//! the pipeline library. Here: a cache that launches of the Series S +//! profile with FSR 4 and of the Series X profile at two sizes had filled, +//! then a launch of the Series S profile with the title's own upscaler: the +//! print on the back of the prologue's shirt was missing in every +//! screenshot; the same build on a library of its own had it; and with this +//! module the first cache had it again. +//! +//! There (fxceless's tree): one more static sampler unlike +//! the title's own, in a root signature made before the title's and never +//! bound, was enough to give the main character bright yellow hair and a +//! wall lit in blocks for the whole run, 20 runs of 20, where a launch +//! without it showed dark hair and an evenly dark wall, 12 of 12. A sampler +//! equal to one of the title's in all a filter makes use of did nothing. +//! The same build with the same switches showed the wrong picture on a +//! library that launches of another configuration had filled, and the right +//! one from an empty library and from the library that launch left. +//! +//! The reading that fits all of it: the host numbers the different static +//! samplers of a device in the order they are first made, a compiled +//! pipeline names them by number, and a pipeline kept in the library keeps +//! the numbers of the launch that compiled it. A launch that makes its +//! static samplers in another order then loads pipelines that sample with +//! the wrong ones (the title's shadow lookups without their comparison, +//! for one). The library's own check passes: the descriptions are equal. +//! +//! So the order is made the same in every launch. The samplers this cache +//! has ever seen are listed in a file beside the library, in the order they +//! were first made, and before the first root signature of a launch each of +//! them is made again in that order, alone in a root signature that lives +//! for the whole run. A sampler not in the list yet goes to its end, and +//! its own root signature is made under the same lock before the one that +//! asked for it, so the file's order is the host's. +//! +//! A library filled before there was a list is not used: its pipelines may +//! carry any order (`crate::pipeline::library`). +//! +//! `VICTORY_SAMPLER_ORDER=0`: nothing of this (as before). + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; + +/// The list's file, beside the library's. +const LIST_FILE: &str = "static-samplers.txt"; + +/// A static sampler's state, without where a shader finds it (its register, +/// space and visibility): filter, three address modes, the bias's bits, +/// maximum anisotropy, comparison function, border colour, the bits of the +/// first and the last level. +type Key = [u32; 10]; + +/// Whether the order is kept (`VICTORY_SAMPLER_ORDER=0`: not). +pub(crate) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SAMPLER_ORDER").is_none_or(|v| v != "0")) +} + +/// Whether `dir` held a list when this launch first asked: a library there +/// was then filled with it. Asked once, before the list is written +/// ([`before`] asks first), so that the answer is the same whichever of +/// the library and the first root signature comes first. +pub(crate) fn listed_at_start(dir: &Path) -> bool { + static LISTED: OnceLock<bool> = OnceLock::new(); + *LISTED.get_or_init(|| dir.join(LIST_FILE).exists()) +} + +fn key(s: &D3D12_STATIC_SAMPLER_DESC) -> Key { + [ + s.Filter.0 as u32, + s.AddressU.0 as u32, + s.AddressV.0 as u32, + s.AddressW.0 as u32, + s.MipLODBias.to_bits(), + s.MaxAnisotropy, + s.ComparisonFunc.0 as u32, + s.BorderColor.0 as u32, + s.MinLOD.to_bits(), + s.MaxLOD.to_bits(), + ] +} + +fn sampler(k: &Key) -> D3D12_STATIC_SAMPLER_DESC { + D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(k[0] as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(k[1] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(k[2] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(k[3] as i32), + MipLODBias: f32::from_bits(k[4]), + MaxAnisotropy: k[5], + ComparisonFunc: D3D12_COMPARISON_FUNC(k[6] as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(k[7] as i32), + MinLOD: f32::from_bits(k[8]), + MaxLOD: f32::from_bits(k[9]), + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + } +} + +/// The list's line for a sampler: its ten words in hexadecimal. +fn line(k: &Key) -> String { + k.iter().map(|w| format!("{w:08x}")).collect::<Vec<_>>().join(" ") +} + +/// The samplers a list's text names, in its order, each once. A line that +/// is not ten hexadecimal words is left out (a file cut short). +fn parse(text: &str) -> Vec<Key> { + let mut seen = HashSet::new(); + text.lines() + .filter_map(|l| { + let words: Vec<u32> = l.split_whitespace().map(|w| u32::from_str_radix(w, 16)).collect::<Result<_, _>>().ok()?; + Key::try_from(words).ok() + }) + .filter(|k| seen.insert(*k)) + .collect() +} + +/// A root signature of nothing but the sampler. +fn alone(device: &ID3D12Device, k: &Key) -> windows::core::Result<ID3D12RootSignature> { + let samplers = [sampler(k)]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: 0, + pParameters: std::ptr::null(), + NumStaticSamplers: 1, + pStaticSamplers: samplers.as_ptr(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + let mut blob: Option<ID3DBlob> = None; + // SAFETY: the description points at the live array above; the blob + // owns its bytes. + unsafe { + 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::<u8>(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + +/// The samplers made so far, in the list's order, and the root signatures +/// that keep them made. +struct Order { + seen: HashSet<Key>, + kept: Vec<ID3D12RootSignature>, + /// The list's file, if there is a cache folder. + file: Option<PathBuf>, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Order {} + +impl Order { + /// Makes the samplers the list in `dir` names, in its order. + fn start(device: &ID3D12Device, dir: Option<&Path>) -> Order { + let file = dir.map(|d| d.join(LIST_FILE)); + let keys = file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()).map(|t| parse(&t)).unwrap_or_default(); + let mut order = Order { seen: HashSet::new(), kept: Vec::new(), file }; + for k in &keys { + order.make(device, k); + } + // The file as it is read from now on: whole lines, each sampler + // once (and a file where there was none: the library beside it is + // filled with this order). + order.save(&keys); + tracing::info!( + samplers = keys.len(), + "static samplers are made in the order of this cache's list before anything else (VICTORY_SAMPLER_ORDER=0: not)" + ); + order + } + + fn make(&mut self, device: &ID3D12Device, k: &Key) { + if !self.seen.insert(*k) { + return; + } + match alone(device, k) { + Ok(root) => self.kept.push(root), + // (Its number is then taken when the root signature that asked + // for it is made, which comes right after, under the lock.) + Err(e) => tracing::warn!(error = %e, sampler = line(k), "a static sampler could not be made alone"), + } + } + + fn save(&self, keys: &[Key]) { + let Some(file) = &self.file else { return }; + let text: String = keys.iter().map(|k| line(k) + "\n").collect(); + if let Err(e) = std::fs::write(file, text) { + tracing::warn!(error = %e, "the list of static samplers was not written: the next launch may make them in another order"); + } + } + + /// One more sampler at the list's end. + fn add(&mut self, device: &ID3D12Device, k: &Key) { + self.make(device, k); + let Some(file) = &self.file else { return }; + use std::io::Write; + let written = std::fs::OpenOptions::new() + .append(true) + .create(true) + .open(file) + .and_then(|mut f| f.write_all((line(k) + "\n").as_bytes())); + if let Err(e) = written { + tracing::warn!(error = %e, "the list of static samplers was not added to: the next launch may make them in another order"); + } + } +} + +static ORDER: Mutex<Option<Order>> = Mutex::new(None); + +/// Called before a root signature with `samplers` is made on `device` +/// (also with none: the first call of a launch makes the list's). `dir`: +/// the folder of the pipeline library, if there is one. +pub(crate) fn before(device: &ID3D12Device, samplers: &[D3D12_STATIC_SAMPLER_DESC], dir: Option<&Path>) { + if !on() { + #[cfg(feature = "diagnostics")] + extra(device, None); + return; + } + if let Some(dir) = dir { + listed_at_start(dir); + } + let mut order = ORDER.lock().unwrap_or_else(|e| e.into_inner()); + let first = order.is_none(); + let order = order.get_or_insert_with(|| Order::start(device, dir)); + #[cfg(feature = "diagnostics")] + if first { + extra(device, Some(order)); + } + #[cfg(not(feature = "diagnostics"))] + let _ = first; + for s in samplers { + let k = key(s); + if !order.seen.contains(&k) { + order.add(device, &k); + } + } +} + +/// For reproducing fxceless/victory-fork#1459 (diagnostics builds, +/// `VICTORY_EXTRA_STATIC_SAMPLER=1`): one more static sampler, unlike the +/// title's own, is made before the title's first root signature. With the +/// order kept it goes through the list like any other (`order`); without, +/// it is made alone and kept, as a pass of the layer's with a sampler of +/// its own would be. +#[cfg(feature = "diagnostics")] +fn extra(device: &ID3D12Device, order: Option<&mut Order>) { + static ASKED: OnceLock<bool> = OnceLock::new(); + static MADE: std::sync::Once = std::sync::Once::new(); + if !*ASKED.get_or_init(|| std::env::var_os("VICTORY_EXTRA_STATIC_SAMPLER").is_some_and(|v| v == "1")) { + return; + } + // Linear, clamped, and the root signature language's values for the rest. + let k = key(&D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 16, + ComparisonFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + MaxLOD: f32::MAX, + ..Default::default() + }); + match order { + Some(order) => { + if !order.seen.contains(&k) { + order.add(device, &k); + tracing::info!("one more static sampler was added to the list before the title's first root signature (VICTORY_EXTRA_STATIC_SAMPLER=1)"); + } + } + None => MADE.call_once(|| match alone(device, &k) { + Ok(root) => { + tracing::info!("one more static sampler was made before the title's first root signature, outside any list (VICTORY_EXTRA_STATIC_SAMPLER=1, VICTORY_SAMPLER_ORDER=0)"); + std::mem::forget(root); + } + Err(e) => tracing::warn!(error = %e, "the extra static sampler could not be made"), + }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn some(filter: i32, last: f32) -> D3D12_STATIC_SAMPLER_DESC { + D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(filter), + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_BORDER, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MipLODBias: -0.5, + MaxAnisotropy: 4, + ComparisonFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + MinLOD: 0.0, + MaxLOD: last, + ShaderRegister: 7, + RegisterSpace: 3, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + } + } + + /// A sampler comes back from its line as it went in, in all a key + /// holds; where a shader finds it is not part of the key. + #[test] + fn a_sampler_comes_back_from_its_line() { + let s = some(0x95, 12.0); + let k = key(&s); + assert_eq!(parse(&line(&k)), vec![k]); + let back = sampler(&k); + assert_eq!(key(&back), k); + assert_eq!((back.Filter, back.AddressV, back.MaxAnisotropy), (s.Filter, s.AddressV, s.MaxAnisotropy)); + assert_eq!((back.MipLODBias.to_bits(), back.MaxLOD.to_bits()), (s.MipLODBias.to_bits(), s.MaxLOD.to_bits())); + assert_eq!((back.ShaderRegister, back.RegisterSpace, back.ShaderVisibility), (0, 0, D3D12_SHADER_VISIBILITY_ALL)); + let mut elsewhere = s; + (elsewhere.ShaderRegister, elsewhere.RegisterSpace, elsewhere.ShaderVisibility) = (1, 0, D3D12_SHADER_VISIBILITY_VERTEX); + assert_eq!(key(&elsewhere), k); + } + + /// A list keeps its order, names each sampler once and leaves out a + /// line cut short. + #[test] + fn a_list_keeps_its_order() { + let (a, b, c) = (key(&some(0x15, 12.0)), key(&some(0x14, 12.0)), key(&some(0x15, f32::MAX))); + let text = format!("{}\n{}\n{}\n{}\n{}", line(&a), line(&b), line(&a), line(&c), &line(&b)[..40]); + assert_eq!(parse(&text), vec![a, b, c]); + assert_eq!(parse(""), Vec::<Key>::new()); + assert_eq!(parse("not a sampler\n"), Vec::<Key>::new()); + } + + /// On a device: the list's samplers are made at the first call, a new + /// one is added to the file's end, and a second start reads the same + /// order back. + #[test] + fn a_new_sampler_goes_to_the_end_of_the_file() { + let Some(host) = crate::host::host() else { + return; // no host device + }; + let dir = std::env::temp_dir().join(format!("victory-samplers-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a folder for the test"); + let (a, b, c) = (some(0x15, 12.0), some(0x14, 12.0), some(0x15, f32::MAX)); + std::fs::write(dir.join(LIST_FILE), format!("{}\n{}\n", line(&key(&a)), line(&key(&b)))).expect("a list"); + let mut order = Order::start(&host.device, Some(&dir)); + assert_eq!(order.kept.len(), 2); + assert!(order.seen.contains(&key(&a)) && order.seen.contains(&key(&b)) && !order.seen.contains(&key(&c))); + order.add(&host.device, &key(&c)); + // (A second asking adds nothing.) + if !order.seen.contains(&key(&c)) { + order.add(&host.device, &key(&c)); + } + assert_eq!(order.kept.len(), 3); + let text = std::fs::read_to_string(dir.join(LIST_FILE)).expect("the list"); + assert_eq!(parse(&text), vec![key(&a), key(&b), key(&c)]); + let again = Order::start(&host.device, Some(&dir)); + assert_eq!(again.kept.len(), 3); + let _ = std::fs::remove_dir_all(&dir); + } +} From edbc9c66a0e59810a7af90247fd358c72396b889 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 10:47:42 -0500 Subject: [PATCH 04/57] Write watch: the guards' lock can be waited for awake at first (VICTORY_GUARDS_SPIN=<microseconds>; 0, the default: asleep at once as before) The lock is held a few microseconds at a time and taken thousands of times a frame by the thread that prepares submissions and the six that share its refreshes, and by the title's threads in their write faults. A profile of the prologue's cell (RTX 3090 Ti, Series S profile, 31 fps) had the preparing thread 2.2 ms of a 32 ms frame asleep behind it, and each helper as long. Measured with VICTORY_GUARDS_SPIN=40, one run each way: - with the title's own upscaler: the preparing thread's time in its submissions 31.0 -> 28.8 ms a frame (refreshes 10.1 -> 7.8), the frame 32.2 -> 31.9 ms; the card is 96 % busy in both; - with FSR 4: 32.7 -> 32.6 ms, the frame the same. So no frame-rate gain is shown on this card. Off by default; kept for measuring where the preparing thread alone is the limit. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/watch.rs | 36 ++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 151de0903..ab2e9d763 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -1759,12 +1759,46 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { Ok(g) => g, // (Held by this, whoever panicked with it: not to be asked for again.) Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), - Err(std::sync::TryLockError::WouldBlock) => waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())), + Err(std::sync::TryLockError::WouldBlock) => waited(3, guards_awake), }; settle(&mut g); g } +/// The guards' lock, held by another thread: waited for awake at first +/// (`VICTORY_GUARDS_SPIN=<microseconds>` at most, 0: not at all, asleep at +/// once as before), then asleep. +/// +/// The lock is held a few microseconds at a time (some bits, or one change +/// of a run of blocks' protection) and taken thousands of times a frame by +/// the thread that prepares submissions and the six that share its +/// refreshes, all at once, and by the title's threads in their write +/// faults. Asleep, a thread is woken in 50 microseconds and more: a profile +/// of the prologue's cell (RTX 3090 Ti, Series S profile, 31 frames a +/// second) had the preparing thread 2.2 ms of a 32 ms frame in this wait +/// alone, and each of the six helpers as long. +fn guards_awake() -> std::sync::MutexGuard<'static, Guards> { + static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| std::env::var("VICTORY_GUARDS_SPIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + if most > 0 { + let began = std::time::Instant::now(); + loop { + for _ in 0..24 { + std::hint::spin_loop(); + } + match GUARDS.try_lock() { + Ok(g) => return g, + Err(std::sync::TryLockError::Poisoned(e)) => return e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => {} + } + if began.elapsed().as_micros() as u64 >= most { + break; + } + } + } + GUARDS.lock().unwrap_or_else(|e| e.into_inner()) +} + /// The 4 KiB pages of title memory that what shaders wrote was put into, /// and the frame it last was: in pieces made when first needed and never let /// go. Some 20,000 pages a frame are noted by the relay and the landing From 3a20b117a53a00a367cdfa87484f9d489e62835b Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 10:46:51 -0500 Subject: [PATCH 05/57] README: VIctory-Neo (what it does, measured on an RTX 3090 Ti; quick start; what it adds; what it is built on) The README of trustno1-coder/VIctory-NVIDIA, the tree this is built on, is kept as docs/README-nvidia.md with its links made to work from there. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 459 +++++++++++++++--------------------------- docs/README-nvidia.md | 312 ++++++++++++++++++++++++++++ 2 files changed, 474 insertions(+), 297 deletions(-) create mode 100644 docs/README-nvidia.md diff --git a/README.md b/README.md index d48c2e965..c9f3c4627 100644 --- a/README.md +++ b/README.md @@ -1,308 +1,173 @@ -# VIctory on NVIDIA - -## Quick start: how to run it - -**The easy way: one file, nothing to build** - -1. Download `victory.exe` from the - [latest release](https://github.com/trustno1-coder/VIctory-NVIDIA/releases/latest). -2. Put it into the folder of **your own dump** of the title's Xbox Series - build v1.0.2.1, next to `game_scarlett_master.exe`. -3. Double-click it. Windows may say the publisher is unknown (the file is not - signed): "More info", then "Run anyway". - -- The first start asks once whether to download NVIDIA's DLSS and frame - generation files (about 70 MB) from NVIDIA's own GitHub. They are NVIDIA's - and are not part of this program; say no and the game still runs, with its - own upscaling and no frame generation. -- Nothing is written into your game folder: settings, saves, caches, logs and - NVIDIA's files are kept under `%LOCALAPPDATA%\victory`. -- You need Windows 10 or 11, 32 GB of RAM or more, an SSD and an NVIDIA - GeForce RTX card with a recent driver. This repository and its releases - contain no game files. - -**In the game** - -- **F1** brings up the settings menu (arrow keys pick and change, Enter does - it): DLSS, frame generation, frame rate cap and more. -- **F3** shows the stats panel (frame rate, frame generation, draws, GPU and - memory numbers). - -**Building it yourself instead** - -Install [Rust](https://rustup.rs) and the -[Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) -with "Desktop development with C++", then in PowerShell: +# VIctory-Neo + +**The Xbox Series build of the title, running on a Windows PC from your own +files, at about 30 frames a second.** + +VIctory-Neo is a build of [VIctory](https://github.com/Marvisak/VIctory), the +compatibility layer that runs an Xbox Series title natively on Windows. The +title's own x86-64 code runs on your processor; the layer provides the +console's system calls and translates its graphics to Direct3D 12. + +> **No game files are here, and none ever will be.** You need your own legally +> obtained dump of the title's Xbox Series build v1.0.2.1. This project is not +> affiliated with or endorsed by the title's developer or publisher, nor by +> NVIDIA. See [docs/asset-policy.md](docs/asset-policy.md). + +## What it does today + +Measured on one PC: **GeForce RTX 3090 Ti 24 GB** (driver 616.92), Ryzen 9 +9950X3D, 64 GB RAM, Windows 11. Frame rates are the layer's own count (F3 +shows it), medians over the 5-second readings of a run, hands off. + +| Scene | Profile | Frames a second | +|---|---|---| +| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **31** (readings 29 to 34) | +| Opening cutscene | Series S | about 28 on average, 20 to 37 by shot | +| Prologue, the cell | Series X, scene 1920x1080, 2560x1440 out | 26 | +| Prologue, the cell | Series X, native 2560x1440 | 23 | + +- The boot screens, the account picker, the loading art and the opening + cutscene play in order, and the prologue's first room stands. +- Characters, hair, clothes and their prints, textures, sky and sun are drawn. +- No crash and no lost graphics device in the runs these numbers come from + (a dozen, 5 to 10 minutes each, standing in the cell). Longer sessions, + play with a pad or keyboard and mouse, and anything past the prologue are + **not measured here yet**; the projects this is built on have played to the + first boat mission (see [Built on](#built-on)). + +On the same PC, fxceless/victory-fork's `main` of the same day runs the same +cell at 17 to 19 frames a second. + +### What is not right yet + +- **No ray tracing.** The title traces its indirect light, reflections and + some shadows itself, and no layer runs that fast enough yet. An estimate + stands in for indirect light and reflections (foxhound's work): rooms are + lit, reflections are blurry. `VICTORY_BVH_BUILDER=1` runs the title's own + rays: a few frames a second and a broken picture. +- **Haze through windows.** Bright views through glass (the cell's window) + are smeared; cause not found yet. +- **Hitches** when the title streams a new scene in, and during the first + launches while shaders are translated and pipelines made (see below). +- **Above 30 frames a second the game runs a little fast.** The title steps + its world at least 1/30 s a frame. `--fps 30` holds it at its own rate. +- **Memory.** On this PC it takes up to 43 GB of RAM, with a 24 GB card that + it fills with textures. Close what you can. foxhound measures 20 GB in use + (28 GB committed) on a 32 GB PC with a 12 GB card. + +## Quick start + +You need: Windows 10 or 11, a Direct3D 12 card with mesh shaders and shader +model 6.6 (measured on NVIDIA RTX; AMD runs, with less attention), 32 GB of +RAM or more, an SSD, [Rust](https://rustup.rs) and the Visual Studio Build +Tools with "Desktop development with C++". ```powershell -git clone https://github.com/trustno1-coder/VIctory-NVIDIA -cd VIctory-NVIDIA -.\Get-NVIDIA-DLSS.cmd -powershell -ExecutionPolicy Bypass -File scripts\play-nvidia.ps1 -Exe 'D:\Games\MyDump\game_scarlett_master.exe' +git clone https://github.com/KyleS98/VIctory-Neo +cd VIctory-Neo +cargo build --release --locked -p victory +target\release\victory.exe play "D:\MyDump\game_scarlett_master.exe" --series-s ``` -Put the path to **your** `game_scarlett_master.exe` in the last line. The -first start builds the layer, which takes a few minutes. - -Options, requirements in full and the details are under -[How to run it](#how-to-run-it). - -A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer -that runs an Xbox Series title natively on Windows from files **you** supply, -tuned for **NVIDIA RTX** cards. - -> **This repository contains no game files, code or assets.** You need your -> own legally obtained copy of the title. It is not affiliated with or endorsed -> by the title's developer or publisher, nor by NVIDIA. See -> [docs/asset-policy.md](docs/asset-policy.md). - -## Built from many projects, and from running every one of them - -This repository did not come from one place, and the base it stands on today -is the end of a long comparison, not the start of the work. Over several weeks -we built, ran and measured many projects on the same NVIDIA PC: Leonida, -[Marvisak's VIctory](https://github.com/Marvisak/VIctory), -[fxceless's fork](https://github.com/fxceless/victory-fork), -[the 7900 XTX fork](https://github.com/avatarmanz/VIctory-7900XTX), -[Belobug's](https://github.com/Belobug/VIctory-Belobug-AMD), -[DexNom's](https://github.com/DexNom/VIctory), -[CGBJ's cool_fox](https://github.com/codec-d/cool_fox), Kelvaroq's, Neptune, -xcl (another layer for the same title) and then -[foxhound](https://github.com/readmet3xt-lab/foxhound). On each we found what -stopped it on an RTX card, fixed or worked around it, measured the result, and -carried what we learned to the next. Every pull request sent here was built -and run on the same card before it was merged. No single project got here -alone, and choosing the base that runs best was only one result of that work. - -### What this fork brings - -Not one fix but a long line of them: days of work, much of it around the clock, -across every one of those codebases, more than 300 measured runs on the same -RTX PC, and each fault chased towards its cause before the next build. In rendering, in -speed, in the picture and in simply being able to play it: - -**Rendering fixes** - -- **Draws no longer skipped on NVIDIA.** NVIDIA caps the view heap below what - the title asks for; thousands of draws a frame were dropped, the screen - rarely updated and the character jumped from place to place. The pool of - descriptor slots was reworked until almost none were. -- **Menus, loading screens and subtitles on Series S**, black until then (the - interface plane laid over the game), and **faces that move** (their network - carried through as integers): ported from fxceless's pull requests 1189 and - 927 and made to work on this card. -- **The intro video without flicker**: its frames came out of order. -- **Black blobs gone**: a single bad number from a shader, spread by blur and - the upscaler into patches on faces and in the air, is caught where it is - written. -- **White, hazy rooms explained and tamed**: the title's ray tracing was - running with its structure builder off, so every ray missed. Which passes - can be left out without filling the picture with rainbow glitter was worked - out pass by pass. -- **The ray-tracing structure builder running on NVIDIA**, on CGBJ's renderer: - the draws dropped for it went from thousands a frame to one. -- **White-outs with black holes further into the game** followed up in frames - captured in play: thousands of draws a frame were being dropped there for - that same missing structure. - -**Speed** - -- **Memory compares moved to the card**: 11 to about 22 frames a second on the - base of the time. -- **Settings measured, not guessed**: one switch at a time, on the same scene, - run after run. -- **The base itself chosen by measurement**: the same rooms went from 15-17 - frames a second to 26-30, at a higher resolution. -- **The 30 frames a second were the title's own frame interval**, not the - layer's limit: found, and lifted. - -**Picture and frames** - -- **DLSS in place of the title's upscaler**, with its model and mode to choose. -- **DLSS frame generation with up to six frames shown for each one rendered**, - switched and changed while playing, without a restart (foxhound's is 2x, set - at the start). By Streamline's own count it shows exactly 2, 4 and 6. -- **Why frame generation showed nothing on a full 12 GB card**, found and - fixed: the card's memory is now shared out so that it has room. -- **The frame rate at the top left of the picture**: frames rendered a second - and, with frame generation, frames shown (`FPS: 28.4 FG: 170.4`). - -**Playing it** - -- **The F1 settings menu**, in every build: DLSS, frame generation, frame rate - cap, console profile, picture size, the light estimates and the main speed - switches, saved to `victory-settings.txt` and applied at the next start - ("SAVE AND RESTART NOW" does that for you; lines marked LIVE change at once). -- **The F3 stats panel**, in every build: frame rate and frame time, frames - shown with frame generation, draws, how busy the GPU and the submitting - thread are, copies, RAM and VRAM. The menu switches it too. -- **Open water without dark blocks.** Two of the title's water light programs - run on 32-lane cards only in a form that left whole tiles of the sea dark - (around boats, along shores, under bridges) and cost about 15 ms of the - card a frame. They are left out there: no blocks and 30 fps instead of 25 - on the first boat ride (RTX 5070), with water that is darker and bluer. - WATER LIGHT in the menu (`VICTORY_WATER_LIGHT=1`) runs them again. -- **One command to play**: the launcher builds the layer the first time and - applies what the menu saved. -- **`Get-NVIDIA-DLSS.cmd`**: the eight NVIDIA files that are loaded, about - 70 MB, taken out of NVIDIA's 263 MB release without downloading the rest. - NVIDIA's licence does not let a repository carry them, so they come from - NVIDIA. - -**Tested, not assumed** - -- Every pull request sent here was read line by line and, where it touched the - game, built and run on this card before it was merged: ten so far. - -Where each of these is today: this fork's own code in this tree is the F1 -menu, the stats panel in every build, the water light switch, frame -generation from 2x to 6x with its live switching and memory handling, the -lifted frame rate cap, the frame rate line, the launcher and the NVIDIA file -fetcher. The foxhound line carries the descriptor slots, the -compares on the card, the interface plane and the face network in its own -form. The black-blob scrub, the graphics card picker and the ray-tracing -builder path are in this repository's history, and come over as this base -turns out to need them. - -### The base since 2026-11-26: foxhound - -On 2026-11-26 this fork moved onto -[readmet3xt-lab/foxhound](https://github.com/readmet3xt-lab/foxhound) -(`02fc18a`, GPL-3.0-or-later). On the same PC it ran the same rooms at close to -twice the frame rate of what this fork had, at a higher resolution, so its -tree is now this one's, with its history kept, and this fork's own additions -are on top. What foxhound is and how it got there is in its own README, kept as -[docs/README-foxhound.md](docs/README-foxhound.md); its measurements are in -[docs/findings.md](docs/findings.md). - -What foxhound brings: - -- the Series X profile at a native 2560x1440; -- DLSS Super Resolution and DLSS Frame Generation through NVIDIA Streamline, - loaded when the game runs (nothing of NVIDIA's is needed to build); -- an estimate of indirect light and of reflections in place of the title's ray - tracing, and fewer stalls at scene cuts. - -What this fork has on top of it is under -[What this fork brings](#what-this-fork-brings) above. - -## Where it stands - -Tested on one PC: Windows 11, Ryzen 7 9800X3D, 64 GB RAM, **GeForce RTX 5070 -12 GB**; the title's Xbox Series build v1.0.2.1, Series X profile, 2560x1440 -output, DLSS Quality. Frame rates are the layer's own count, in the opening -rooms. +Put the path of **your** `game_scarlett_master.exe` in the last line. That is +all: the settings these numbers were measured with are built in. -| | | -|---|---| -| Opening rooms | mostly 26-30 frames a second rendered (33-38 ms a frame) | -| Frame generation | 2x to 6x on top of that: by Streamline's own count, exactly 2, 4 and 6 frames shown for each one rendered | -| Device losses, crashes | none in the measured runs | -| Before this base (Series S, 720p to 1080p by DLSS) | 15-17 frames a second in the same rooms | - -foxhound's own measurements, on an RTX 4070 SUPER, are in its README. - -What is known to be wrong: - -- **No ray tracing.** The title's own is off (`VICTORY_BVH_BUILDER=1`, or the - menu's RAY TRACING, turns it on: slow and with a broken picture on this - base). An estimate stands in for indirect light and reflections. -- **Frame generation needs room in the card's memory.** The layer fills the - card with textures up to its budget; with frame generation on from the start - the launcher holds a fifth of the budget back (a little less while it is only - ready), so a few more textures can come late. Switched on from the menu on a - full 12 GB card it can still say that memory is past the budget; it then - runs, perhaps unevenly. -- **Frames are only generated while the game's window has the focus**, and - about a second passes after a change before they come. -- **The first run of every new build stutters** while the driver compiles - pipelines (foxhound's README, *Warming up*, says how to make them ahead). -- "SAVE AND RESTART NOW" can leave the old game's process behind without a - window; it goes when the PC restarts. -- What foxhound lists as wrong (the heat-haze pass left out, hitches in - cutscenes) applies here too. - -## How to run it - -You need Windows 10 or 11 (x64), a CPU with AVX2, 32 GB of RAM or more, an -SSD, an NVIDIA GeForce RTX card with a recent driver (RTX 40 or later for frame -generation, with hardware-accelerated GPU scheduling on; more than 2x needs an -RTX 50), [Rust](https://rustup.rs) (the toolchain is pinned), the Visual Studio -Build Tools with "Desktop development with C++", and **your own dump** of the -title's Xbox Series build v1.0.2.1 (the folder with -`game_scarlett_master.exe`). - -```powershell -git clone https://github.com/trustno1-coder/VIctory-NVIDIA -cd VIctory-NVIDIA -copy victory.example.toml victory.toml # then set game_dir to your dump's folder, outside this one -.\Get-NVIDIA-DLSS.cmd # once: NVIDIA's DLSS and frame generation files, about 70 MB -scripts\play-nvidia.ps1 -Exe 'D:\Games\MyDump\game_scarlett_master.exe' -``` - -The first start builds the layer (a few minutes). `Get-NVIDIA-DLSS.cmd` gets -NVIDIA's files from -[NVIDIA-RTX/Streamline](https://github.com/NVIDIA-RTX/Streamline) into -`nvidia-sdk\` (git-ignored). They are NVIDIA's, under NVIDIA's licences, which -are saved beside them; this repository does not carry them and may not. Nothing -is downloaded unless you run that file; `VICTORY_STREAMLINE_DIR` names another -folder if you have the Streamline SDK already. +- **The first launches are slow, and that is expected.** The first start + translates the title's shaders (minutes) and the driver compiles each + pipeline the first time it is drawn. A launch may even end in the title's + own watchdog while that goes on; start it again. Each launch writes down + what it needed, so it gets smoother over the first two or three. +- **The first start asks once whether to download NVIDIA's DLSS files** + (RTX cards). Answer `n` for what was measured here; with them, DLSS takes + the title's upscaling and the numbers above no longer apply. +- **F3** shows the stats panel, **F1** the settings menu (console profile, + picture size, frame rate cap, the light estimate and the main switches). +- Nothing is written into your game folder: caches, saves, settings and logs + are under `%LOCALAPPDATA%\victory`. -`scripts\play-nvidia.ps1` is `scripts\play-foxhound.ps1` under the name this -fork has always had; its options: +Other ways to run it: -| Option | What | +| | | |---|---| -| *(none)* | Series X profile, 2560x1440, DLSS Quality, no frame rate cap, frame generation ready but off | -| `-FrameGen`, `-FrameGenX 4` | frame generation on from the start, 2 to 6 frames shown for each one rendered | -| `-Dlss off` / `dlaa` / `balanced` / `performance` | the title's own upscaling, or another DLSS mode | -| `-Fps 60` | a frame rate cap (30 is the title's own) | -| `-SeriesS` | the Series S profile: 1280x720 inside, faster, softer | -| `-Res 1080to1440` / `4k` | scene at 1080p upscaled by the title / the stock 3840x2160 output | -| `-NoFrameGenReady` | frame generation only with `-FrameGen` (it is otherwise made ready at every start, so the menu can switch it) | -| `-Build diag` | the diagnostics build (slower; captures, timelines, recording time in the F3 panel) | -| `-More @{VICTORY_X='1'}` | add or override any switch | - -What the F1 menu saved (`victory-settings.txt`) goes over these at every start; -delete that file to go back to them. Full screen: start the game, then run -`.\scripts\fullscreen.ps1` in another window. Logs go to -`%LOCALAPPDATA%\victory\logs`, saves to `%LOCALAPPDATA%\victory\data`. - -## How it works, and the findings - -- [docs/README-foxhound.md](docs/README-foxhound.md): foxhound's own README - (set-up by hand, warming up, its switches). -- [docs/architecture.md](docs/architecture.md): the layer's parts. -- [docs/findings.md](docs/findings.md): measurements behind the choices. -- [docs/dlss.md](docs/dlss.md): DLSS and Frame Generation. -- [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md): the title's ray tracing - and the light estimate. -- [docs/asset-policy.md](docs/asset-policy.md): what may and may not be in this - repository. - -## Credits - -A tree of other people's work with a little on top; the history is kept. - -- **[foxhound](https://github.com/readmet3xt-lab/foxhound)** by - readmet3xt-lab: the base of this fork since 2026-11-26, and through it: -- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its - contributors: the loader, the runtime services, the Direct3D 12 back end and - the shader recompiler. -- **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)**, - **[avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX)**, - **[codec-d/cool_fox](https://github.com/codec-d/cool_fox)**, - **[DexNom/VIctory](https://github.com/DexNom/VIctory)**, - **[Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD)** - and the others foxhound's README names. -- Everyone who sent pull requests to this fork before the move; that work is - in the history, on the branch that was `main` until then. -- NVIDIA Streamline, DLSS and Reflex are NVIDIA's; they are loaded at run time - from a folder you supply. -- Much of this fork's code was written with - [Claude Code](https://claude.com/claude-code). +| `victory.exe play <exe>` | Series X profile at 2560x1440: sharper, slower (23 here) | +| `victory.exe play <exe> --res 1080to1440` | Series X, scene at 1920x1080 (26 here) | +| `victory.exe play <exe> --series-s --fps 30` | the title's own frame rate, game speed exact | +| `victory.exe play <exe> --series-s --set VICTORY_X=1` | add or override a switch | +| `scripts\play-foxhound.ps1 -Exe <exe> -SeriesS` | the same from PowerShell, with a log file | + +**DLSS** (RTX cards) and **DLSS frame generation** (RTX 40 and 50) come with +the tree this is built on: `Get-NVIDIA-DLSS.cmd` fetches NVIDIA's files from +NVIDIA (they are NVIDIA's, under NVIDIA's licence, and not part of this +repository); [docs/dlss.md](docs/dlss.md) has the details. They were **not +measured here**: the numbers above are without them. + +## What Neo adds + +Two changes on top of the tree it is built on, each measured in the game on +the PC above and sent to that project as a pull request: + +1. **The Series S profile keeps the title's own upscaler** where no DLSS is + set up. The title picks FSR 4 on a Series S; translated, that is the + dearer of the two. 28.5 to 30.9 frames a second in the cell, 88 to 38 MB + of title memory copied a frame. (With DLSS or frame generation set up the + title's FidelityFX path is left as it is: they need it.) +2. **The picture no longer depends on which launches filled the pipeline + cache.** On an NVIDIA card a pipeline loaded from the driver's library + could sample with the wrong sampler when an earlier launch had made its + static samplers in another order: a print missing from a shirt here, wrong + shadows and bright yellow hair on another tree. The order is now kept in a + small file beside the library, and the same in every launch. + ([The fault, measured](https://github.com/fxceless/victory-fork/issues/1459).) + +Also in the tree, off by default: `VICTORY_GUARDS_SPIN=<microseconds>`, a +shorter wait on the write tracker's lock. A profile had the thread that +prepares the card's work asleep behind that lock 2 ms of every 32 ms frame. +With the switch at 40 that thread's time fell by 2 ms in one pair of runs +and by nothing in another, and the frame rate did not move in either: the +graphics card is as close to its limit as that thread is. It is there for +whoever measures on a faster card. + +Found with the tree's own tools: its frame line and timing run, its sampling +profiler, and A/B switches that flip while the game runs. + +## Built on + +Neo is the newest link of a chain, and nearly all of the code is other +people's: + +- **[Marvisak/VIctory](https://github.com/Marvisak/VIctory)**: the loader, the + runtime, the Direct3D 12 back end and the shader recompiler. +- **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)** and the + people whose pull requests it carries: where most of the layer grew up. +- **[readmet3xt-lab/foxhound](https://github.com/readmet3xt-lab/foxhound)**: + the base that first held 30 frames a second: list calls translated on + eight threads, work done on the card instead of waited for, the light + estimate, fewer stalls. +- **[trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA)**: + the tree this one is taken from (its `main` of 2026-11-27): the launcher + built into the program, the F1 menu, the stats panel, DLSS and frame + generation, and the pull requests of its contributors. +- And everyone those name: avatarmanz, DexNom, Belobug, Vice-Tay and more. + Their READMEs are kept here: [VIctory on NVIDIA](docs/README-nvidia.md), + [foxhound](docs/README-foxhound.md), [fxceless](docs/README-fxceless.md), + with what each found in [docs/findings.md](docs/findings.md). + +Before 2026-11-27 `main` held an earlier snapshot of fxceless's line. It is +still in `main`'s history, and our frame-rate work on that line (20 to 22 +frames a second in the same cell, with a print missing from the picture) is +on the `integration/*` branches. + +## Reporting a problem + +Open an issue with your card, driver, processor, RAM, the command you ran +and what you saw, in words. The log of a run is under +`%LOCALAPPDATA%\victory\logs`. **Never attach anything from the game**: no +files, dumps, shader dumps or screenshots. ## License -GPL-3.0-or-later, as VIctory and foxhound. See [LICENSE](LICENSE); the one file -that is not covered is named in [docs/asset-policy.md](docs/asset-policy.md). +GPL-3.0-or-later, as VIctory. See [LICENSE](LICENSE); the one file that is +not covered is named in [docs/asset-policy.md](docs/asset-policy.md). + +Much of this code, in every link of the chain, was written with AI +assistance (here: Claude Code). diff --git a/docs/README-nvidia.md b/docs/README-nvidia.md new file mode 100644 index 000000000..371505cce --- /dev/null +++ b/docs/README-nvidia.md @@ -0,0 +1,312 @@ +# VIctory on NVIDIA + +> This is the README of [trustno1-coder/VIctory-NVIDIA](https://github.com/trustno1-coder/VIctory-NVIDIA) as of its +> `main` of 2026-11-27 (`d12eb1b`), the tree VIctory-Neo is built on, kept as it was. Its downloads and its +> measurements are that project's; what Neo measured and changed is in the [README](../README.md). + +## Quick start: how to run it + +**The easy way: one file, nothing to build** + +1. Download `victory.exe` from the + [latest release](https://github.com/trustno1-coder/VIctory-NVIDIA/releases/latest). +2. Put it into the folder of **your own dump** of the title's Xbox Series + build v1.0.2.1, next to `game_scarlett_master.exe`. +3. Double-click it. Windows may say the publisher is unknown (the file is not + signed): "More info", then "Run anyway". + +- The first start asks once whether to download NVIDIA's DLSS and frame + generation files (about 70 MB) from NVIDIA's own GitHub. They are NVIDIA's + and are not part of this program; say no and the game still runs, with its + own upscaling and no frame generation. +- Nothing is written into your game folder: settings, saves, caches, logs and + NVIDIA's files are kept under `%LOCALAPPDATA%\victory`. +- You need Windows 10 or 11, 32 GB of RAM or more, an SSD and an NVIDIA + GeForce RTX card with a recent driver. This repository and its releases + contain no game files. + +**In the game** + +- **F1** brings up the settings menu (arrow keys pick and change, Enter does + it): DLSS, frame generation, frame rate cap and more. +- **F3** shows the stats panel (frame rate, frame generation, draws, GPU and + memory numbers). + +**Building it yourself instead** + +Install [Rust](https://rustup.rs) and the +[Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) +with "Desktop development with C++", then in PowerShell: + +```powershell +git clone https://github.com/trustno1-coder/VIctory-NVIDIA +cd VIctory-NVIDIA +.\Get-NVIDIA-DLSS.cmd +powershell -ExecutionPolicy Bypass -File scripts\play-nvidia.ps1 -Exe 'D:\Games\MyDump\game_scarlett_master.exe' +``` + +Put the path to **your** `game_scarlett_master.exe` in the last line. The +first start builds the layer, which takes a few minutes. + +Options, requirements in full and the details are under +[How to run it](#how-to-run-it). + +A fork of [VIctory](https://github.com/Marvisak/VIctory), a compatibility layer +that runs an Xbox Series title natively on Windows from files **you** supply, +tuned for **NVIDIA RTX** cards. + +> **This repository contains no game files, code or assets.** You need your +> own legally obtained copy of the title. It is not affiliated with or endorsed +> by the title's developer or publisher, nor by NVIDIA. See +> [docs/asset-policy.md](asset-policy.md). + +## Built from many projects, and from running every one of them + +This repository did not come from one place, and the base it stands on today +is the end of a long comparison, not the start of the work. Over several weeks +we built, ran and measured many projects on the same NVIDIA PC: Leonida, +[Marvisak's VIctory](https://github.com/Marvisak/VIctory), +[fxceless's fork](https://github.com/fxceless/victory-fork), +[the 7900 XTX fork](https://github.com/avatarmanz/VIctory-7900XTX), +[Belobug's](https://github.com/Belobug/VIctory-Belobug-AMD), +[DexNom's](https://github.com/DexNom/VIctory), +[CGBJ's cool_fox](https://github.com/codec-d/cool_fox), Kelvaroq's, Neptune, +xcl (another layer for the same title) and then +[foxhound](https://github.com/readmet3xt-lab/foxhound). On each we found what +stopped it on an RTX card, fixed or worked around it, measured the result, and +carried what we learned to the next. Every pull request sent here was built +and run on the same card before it was merged. No single project got here +alone, and choosing the base that runs best was only one result of that work. + +### What this fork brings + +Not one fix but a long line of them: days of work, much of it around the clock, +across every one of those codebases, more than 300 measured runs on the same +RTX PC, and each fault chased towards its cause before the next build. In rendering, in +speed, in the picture and in simply being able to play it: + +**Rendering fixes** + +- **Draws no longer skipped on NVIDIA.** NVIDIA caps the view heap below what + the title asks for; thousands of draws a frame were dropped, the screen + rarely updated and the character jumped from place to place. The pool of + descriptor slots was reworked until almost none were. +- **Menus, loading screens and subtitles on Series S**, black until then (the + interface plane laid over the game), and **faces that move** (their network + carried through as integers): ported from fxceless's pull requests 1189 and + 927 and made to work on this card. +- **The intro video without flicker**: its frames came out of order. +- **Black blobs gone**: a single bad number from a shader, spread by blur and + the upscaler into patches on faces and in the air, is caught where it is + written. +- **White, hazy rooms explained and tamed**: the title's ray tracing was + running with its structure builder off, so every ray missed. Which passes + can be left out without filling the picture with rainbow glitter was worked + out pass by pass. +- **The ray-tracing structure builder running on NVIDIA**, on CGBJ's renderer: + the draws dropped for it went from thousands a frame to one. +- **White-outs with black holes further into the game** followed up in frames + captured in play: thousands of draws a frame were being dropped there for + that same missing structure. + +**Speed** + +- **Memory compares moved to the card**: 11 to about 22 frames a second on the + base of the time. +- **Settings measured, not guessed**: one switch at a time, on the same scene, + run after run. +- **The base itself chosen by measurement**: the same rooms went from 15-17 + frames a second to 26-30, at a higher resolution. +- **The 30 frames a second were the title's own frame interval**, not the + layer's limit: found, and lifted. + +**Picture and frames** + +- **DLSS in place of the title's upscaler**, with its model and mode to choose. +- **DLSS frame generation with up to six frames shown for each one rendered**, + switched and changed while playing, without a restart (foxhound's is 2x, set + at the start). By Streamline's own count it shows exactly 2, 4 and 6. +- **Why frame generation showed nothing on a full 12 GB card**, found and + fixed: the card's memory is now shared out so that it has room. +- **The frame rate at the top left of the picture**: frames rendered a second + and, with frame generation, frames shown (`FPS: 28.4 FG: 170.4`). + +**Playing it** + +- **The F1 settings menu**, in every build: DLSS, frame generation, frame rate + cap, console profile, picture size, the light estimates and the main speed + switches, saved to `victory-settings.txt` and applied at the next start + ("SAVE AND RESTART NOW" does that for you; lines marked LIVE change at once). +- **The F3 stats panel**, in every build: frame rate and frame time, frames + shown with frame generation, draws, how busy the GPU and the submitting + thread are, copies, RAM and VRAM. The menu switches it too. +- **Open water without dark blocks.** Two of the title's water light programs + run on 32-lane cards only in a form that left whole tiles of the sea dark + (around boats, along shores, under bridges) and cost about 15 ms of the + card a frame. They are left out there: no blocks and 30 fps instead of 25 + on the first boat ride (RTX 5070), with water that is darker and bluer. + WATER LIGHT in the menu (`VICTORY_WATER_LIGHT=1`) runs them again. +- **One command to play**: the launcher builds the layer the first time and + applies what the menu saved. +- **`Get-NVIDIA-DLSS.cmd`**: the eight NVIDIA files that are loaded, about + 70 MB, taken out of NVIDIA's 263 MB release without downloading the rest. + NVIDIA's licence does not let a repository carry them, so they come from + NVIDIA. + +**Tested, not assumed** + +- Every pull request sent here was read line by line and, where it touched the + game, built and run on this card before it was merged: ten so far. + +Where each of these is today: this fork's own code in this tree is the F1 +menu, the stats panel in every build, the water light switch, frame +generation from 2x to 6x with its live switching and memory handling, the +lifted frame rate cap, the frame rate line, the launcher and the NVIDIA file +fetcher. The foxhound line carries the descriptor slots, the +compares on the card, the interface plane and the face network in its own +form. The black-blob scrub, the graphics card picker and the ray-tracing +builder path are in this repository's history, and come over as this base +turns out to need them. + +### The base since 2026-11-26: foxhound + +On 2026-11-26 this fork moved onto +[readmet3xt-lab/foxhound](https://github.com/readmet3xt-lab/foxhound) +(`02fc18a`, GPL-3.0-or-later). On the same PC it ran the same rooms at close to +twice the frame rate of what this fork had, at a higher resolution, so its +tree is now this one's, with its history kept, and this fork's own additions +are on top. What foxhound is and how it got there is in its own README, kept as +[docs/README-foxhound.md](README-foxhound.md); its measurements are in +[docs/findings.md](findings.md). + +What foxhound brings: + +- the Series X profile at a native 2560x1440; +- DLSS Super Resolution and DLSS Frame Generation through NVIDIA Streamline, + loaded when the game runs (nothing of NVIDIA's is needed to build); +- an estimate of indirect light and of reflections in place of the title's ray + tracing, and fewer stalls at scene cuts. + +What this fork has on top of it is under +[What this fork brings](#what-this-fork-brings) above. + +## Where it stands + +Tested on one PC: Windows 11, Ryzen 7 9800X3D, 64 GB RAM, **GeForce RTX 5070 +12 GB**; the title's Xbox Series build v1.0.2.1, Series X profile, 2560x1440 +output, DLSS Quality. Frame rates are the layer's own count, in the opening +rooms. + +| | | +|---|---| +| Opening rooms | mostly 26-30 frames a second rendered (33-38 ms a frame) | +| Frame generation | 2x to 6x on top of that: by Streamline's own count, exactly 2, 4 and 6 frames shown for each one rendered | +| Device losses, crashes | none in the measured runs | +| Before this base (Series S, 720p to 1080p by DLSS) | 15-17 frames a second in the same rooms | + +foxhound's own measurements, on an RTX 4070 SUPER, are in its README. + +What is known to be wrong: + +- **No ray tracing.** The title's own is off (`VICTORY_BVH_BUILDER=1`, or the + menu's RAY TRACING, turns it on: slow and with a broken picture on this + base). An estimate stands in for indirect light and reflections. +- **Frame generation needs room in the card's memory.** The layer fills the + card with textures up to its budget; with frame generation on from the start + the launcher holds a fifth of the budget back (a little less while it is only + ready), so a few more textures can come late. Switched on from the menu on a + full 12 GB card it can still say that memory is past the budget; it then + runs, perhaps unevenly. +- **Frames are only generated while the game's window has the focus**, and + about a second passes after a change before they come. +- **The first run of every new build stutters** while the driver compiles + pipelines (foxhound's README, *Warming up*, says how to make them ahead). +- "SAVE AND RESTART NOW" can leave the old game's process behind without a + window; it goes when the PC restarts. +- What foxhound lists as wrong (the heat-haze pass left out, hitches in + cutscenes) applies here too. + +## How to run it + +You need Windows 10 or 11 (x64), a CPU with AVX2, 32 GB of RAM or more, an +SSD, an NVIDIA GeForce RTX card with a recent driver (RTX 40 or later for frame +generation, with hardware-accelerated GPU scheduling on; more than 2x needs an +RTX 50), [Rust](https://rustup.rs) (the toolchain is pinned), the Visual Studio +Build Tools with "Desktop development with C++", and **your own dump** of the +title's Xbox Series build v1.0.2.1 (the folder with +`game_scarlett_master.exe`). + +```powershell +git clone https://github.com/trustno1-coder/VIctory-NVIDIA +cd VIctory-NVIDIA +copy victory.example.toml victory.toml # then set game_dir to your dump's folder, outside this one +.\Get-NVIDIA-DLSS.cmd # once: NVIDIA's DLSS and frame generation files, about 70 MB +scripts\play-nvidia.ps1 -Exe 'D:\Games\MyDump\game_scarlett_master.exe' +``` + +The first start builds the layer (a few minutes). `Get-NVIDIA-DLSS.cmd` gets +NVIDIA's files from +[NVIDIA-RTX/Streamline](https://github.com/NVIDIA-RTX/Streamline) into +`nvidia-sdk\` (git-ignored). They are NVIDIA's, under NVIDIA's licences, which +are saved beside them; this repository does not carry them and may not. Nothing +is downloaded unless you run that file; `VICTORY_STREAMLINE_DIR` names another +folder if you have the Streamline SDK already. + +`scripts\play-nvidia.ps1` is `scripts\play-foxhound.ps1` under the name this +fork has always had; its options: + +| Option | What | +|---|---| +| *(none)* | Series X profile, 2560x1440, DLSS Quality, no frame rate cap, frame generation ready but off | +| `-FrameGen`, `-FrameGenX 4` | frame generation on from the start, 2 to 6 frames shown for each one rendered | +| `-Dlss off` / `dlaa` / `balanced` / `performance` | the title's own upscaling, or another DLSS mode | +| `-Fps 60` | a frame rate cap (30 is the title's own) | +| `-SeriesS` | the Series S profile: 1280x720 inside, faster, softer | +| `-Res 1080to1440` / `4k` | scene at 1080p upscaled by the title / the stock 3840x2160 output | +| `-NoFrameGenReady` | frame generation only with `-FrameGen` (it is otherwise made ready at every start, so the menu can switch it) | +| `-Build diag` | the diagnostics build (slower; captures, timelines, recording time in the F3 panel) | +| `-More @{VICTORY_X='1'}` | add or override any switch | + +What the F1 menu saved (`victory-settings.txt`) goes over these at every start; +delete that file to go back to them. Full screen: start the game, then run +`.\scripts\fullscreen.ps1` in another window. Logs go to +`%LOCALAPPDATA%\victory\logs`, saves to `%LOCALAPPDATA%\victory\data`. + +## How it works, and the findings + +- [docs/README-foxhound.md](README-foxhound.md): foxhound's own README + (set-up by hand, warming up, its switches). +- [docs/architecture.md](architecture.md): the layer's parts. +- [docs/findings.md](findings.md): measurements behind the choices. +- [docs/dlss.md](dlss.md): DLSS and Frame Generation. +- [docs/fork-ray-tracing.md](fork-ray-tracing.md): the title's ray tracing + and the light estimate. +- [docs/asset-policy.md](asset-policy.md): what may and may not be in this + repository. + +## Credits + +A tree of other people's work with a little on top; the history is kept. + +- **[foxhound](https://github.com/readmet3xt-lab/foxhound)** by + readmet3xt-lab: the base of this fork since 2026-11-26, and through it: +- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its + contributors: the loader, the runtime services, the Direct3D 12 back end and + the shader recompiler. +- **[fxceless/victory-fork](https://github.com/fxceless/victory-fork)**, + **[avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX)**, + **[codec-d/cool_fox](https://github.com/codec-d/cool_fox)**, + **[DexNom/VIctory](https://github.com/DexNom/VIctory)**, + **[Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD)** + and the others foxhound's README names. +- Everyone who sent pull requests to this fork before the move; that work is + in the history, on the branch that was `main` until then. +- NVIDIA Streamline, DLSS and Reflex are NVIDIA's; they are loaded at run time + from a folder you supply. +- Much of this fork's code was written with + [Claude Code](https://claude.com/claude-code). + +## License + +GPL-3.0-or-later, as VIctory and foxhound. See [LICENSE](../LICENSE); the one file +that is not covered is named in [docs/asset-policy.md](asset-policy.md). From a5b1335e4b0a82f072940051e6744645f5462fd7 Mon Sep 17 00:00:00 2001 From: jptorres96 <jaimepereztorres96@gmail.com> Date: Fri, 27 Nov 2026 16:53:18 +0100 Subject: [PATCH 06/57] Workspace tests pass on main again: the two budget tests pin VICTORY_INDIRECT_REST=1 (off by default since 545f890); two clippy fixes in tests (cherry picked from commit d763e9c903bf3294eb166093fbb13af93b8c4eaf) --- crates/victory-formats/src/texture.rs | 2 +- crates/victory-gpu/src/indirect.rs | 20 ++++++++++++++++---- crates/victory-loader/src/write_sites.rs | 4 ++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index e52d639ed..2128cc9ef 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -1343,7 +1343,7 @@ mod tests { let needs: Vec<u64> = (0..9).map(|mip| l.bytes_from(mip)).collect(); assert!(needs.windows(2).all(|w| w[0] >= w[1]), "{needs:?}"); assert!(needs[3] * 4 < l.size, "{needs:?}"); - let tiled: Vec<u8> = (0..l.size).map(|i| (i * 7 >> 3) as u8).collect(); + let tiled: Vec<u8> = (0..l.size).map(|i| ((i * 7) >> 3) as u8).collect(); for mip in 1..9 { let m = l.mips[mip as usize]; let pitch = m.width as usize * 8; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 467074089..031b04a88 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -2675,6 +2675,15 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { }; let _ = host.log_messages(); let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + // The clamp as with `VICTORY_INDIRECT_REST=1` (off by default since + // 545f890): a record that does not fit takes the rest of the budget, + // so what the big records spend shows in the small one after them. + let rest = make_from(&host.device, &SOURCE.replace("REST ?", "true ?")).expect("the clamp must compile"); + let bound = |src: (&ID3D12Resource, u64), spec: (u32, u32, u32)| { + let bytes = validate_layout(spec, src.1, None)?; + let (budget, dst) = (list.budget()?, list.indirect_scratch(bytes)?); + clamp_into(&list, &rest, &dst, budget, src, None, spec, false).then_some(dst) + }; const KIND_DISPATCH: u32 = 2; const STRIDE: u32 = 12; let signature = { @@ -2724,8 +2733,8 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; for round in 0..2 { // Spends the budget (clamped, not executed), then one group. - bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap(); - let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + bound((&big, 0), (KIND_DISPATCH, STRIDE, 3)).unwrap(); + let scratch = bound((&small, 0), (KIND_DISPATCH, STRIDE, 1)).unwrap(); // SAFETY: an open list; the worker's root signature and // pipeline; buffers the test holds until the list has run. unsafe { @@ -2746,7 +2755,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { } // A recording with only the small record: the budget is empty // again, so it runs. - let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + let scratch = bound((&small, 0), (KIND_DISPATCH, STRIDE, 1)).unwrap(); // SAFETY: as above. unsafe { list.list.SetComputeRootSignature(&worker.root); @@ -3153,7 +3162,10 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) { let Some(mut warp) = WarpHarness::new() else { return; }; - let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP"); + // A record that does not fit takes the rest (`VICTORY_INDIRECT_REST=1`, + // off by default since 545f890): the budget this test charges. + let source = batch::SOURCE.replace("REST ?", "true ?"); + let pass = make_from(&warp.device, &source).expect("the batched clamp must compile on WARP"); const BUDGET: u32 = 1 << 27; // 2^26 vertices each, as much as a draw is let run: two fill it. for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] { diff --git a/crates/victory-loader/src/write_sites.rs b/crates/victory-loader/src/write_sites.rs index f1167e370..7420a36c8 100644 --- a/crates/victory-loader/src/write_sites.rs +++ b/crates/victory-loader/src/write_sites.rs @@ -346,7 +346,7 @@ mod tests { let list = format!("other.dll {:x}\nT.dll 0x{at:x}\nt.dll {at:x}\nt.dll 5\nt.dll\n", at); assert_eq!(apply("t.dll", second, 0x1000, &list), 1); assert_eq!(std::ptr::read((second + at) as *const u8), 0xe9); - let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); + let (plain, changed): (F, F) = (std::mem::transmute::<usize, F>(place), std::mem::transmute::<usize, F>(second)); for was in 0..=255u8 { let mut bytes = [[0u8; 0x40]; 2]; bytes[0][0x31] = was; @@ -422,7 +422,7 @@ mod tests { if size == 0 { continue; } - let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second)); + let (plain, changed): (F, F) = (std::mem::transmute::<usize, F>(place), std::mem::transmute::<usize, F>(second)); let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; for seed in 0..200u64 { let value = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15); From d10daaad39898041a94b7f1017f8c0e7075a0484 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 14:51:01 -0500 Subject: [PATCH 07/57] README: the second change is described as what was shown (a fresh pipeline cache), not as a sampler-order fix On this tree pipelines with static samplers skip the library unless VICTORY_LIBRARY_STATIC_SAMPLERS=1, so the ordering changed nothing that was loaded in the runs the README cites (pointed out in review of trustno1-coder/VIctory-NVIDIA#69). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c9f3c4627..ba98ab839 100644 --- a/README.md +++ b/README.md @@ -111,13 +111,16 @@ the PC above and sent to that project as a pull request: dearer of the two. 28.5 to 30.9 frames a second in the cell, 88 to 38 MB of title memory copied a frame. (With DLSS or frame generation set up the title's FidelityFX path is left as it is: they need it.) -2. **The picture no longer depends on which launches filled the pipeline - cache.** On an NVIDIA card a pipeline loaded from the driver's library - could sample with the wrong sampler when an earlier launch had made its - static samplers in another order: a print missing from a shirt here, wrong - shadows and bright yellow hair on another tree. The order is now kept in a - small file beside the library, and the same in every launch. - ([The fault, measured](https://github.com/fxceless/victory-fork/issues/1459).) +2. **A pipeline cache left by other launches is dropped once.** Here a cache + filled by launches of other configurations drew a shirt without its + print, and a fresh one drew it right. Neo drops a cache it has not + written its list of static samplers beside, once; every launch then + makes those samplers in the same order. That order is what goes wrong + on fxceless's tree ([measured](https://github.com/fxceless/victory-fork/issues/1459)), + but on this tree pipelines with static samplers never come from the + cache, so **the cause of the missing print here is not known yet**: the + fresh cache is what fixed it, not the order. (Pull request in draft + until that is tested.) Also in the tree, off by default: `VICTORY_GUARDS_SPIN=<microseconds>`, a shorter wait on the write tracker's lock. A profile had the thread that From e9bb461902d27c7b37507dcfe10d8fe75e49048a Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 16:58:22 -0500 Subject: [PATCH 08/57] Shaders: the console's waterfall over a first-lane table offset is proven by its shape where the per-lane form cannot follow it The console compiler loops over a per-lane descriptor by reading the first active lane's table offset, narrowing EXEC to the lanes with the same one, loading that entry and dropping those lanes. `track` makes each lane load its own entry when `Tracer::waterfall` proves the loop. In the title's programs it mostly cannot: over all 25,760 programs it emits, 44,874 such loops were refused, 37,605 of them because the per-lane form could not show that the compares select the access's lanes and 209 because it could not show that the retry keeps the lanes still waiting. In a wave of 64 run as two host waves of 32, every pass of an unproven loop exchanges the first lane's value and the mask between the halves: four group barriers a pass. `Tracer::waterfall_shape` proves the loop by its exact shape instead, only where `waterfall` refused: one block that branches to itself, with nothing in it but the first-lane reads, `v_cmpx_eq` of each with the same lane value, the table loads, waits, accesses that only read, and `s_andn2_wrexec` of a mask T with itself. T is shown to be EXEC on every entry from the phis (a move of the loop's own entry EXEC from outside; the same retry on the back edge), and the first-lane value is read nowhere past the loop. It proves 32,106 of the refused loops. The same programs are emitted as before, and the DXIL validator gives the same results as before for all of them. Measured in the prologue's cell (RTX 3090 Ti, Series S profile, one run each way unless said): where the card is the limit the frame gets 2.5 to 4 ms shorter. With the title's own upscaler (#68), 30.8 fps before and 33.3, 32.9 and 32.0 after; with DLSS Quality and FSR 3 frame generation, 27.0 rendered before and 30.8 after. On main alone without DLSS, where the translated FSR 4 path keeps the preparing thread at 27 to 28 ms a frame, 28.5 before and 28.7 after. The costliest program of the frame, vfx_proj_decal_vbuffer:CS_ProjDecalReduceClassification_Scalarized (4.1 ms a frame in a timing run), has 27 such loops; its DXIL goes from 149 group barriers to 41. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/victory-shader/src/resource.rs | 347 +++++++++++++++++++++++++- 1 file changed, 346 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ddc03dddd..ae16c51ed 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -363,7 +363,13 @@ pub fn track( for (block, (accesses, mut reads, loads)) in offset_at { reads.sort_unstable(); reads.dedup(); - if let Ok(proof) = t.waterfall(block, &accesses, &reads) { + // Where the per-lane form cannot follow the loop, its exact shape + // still proves it ([`Tracer::waterfall_shape`]). + let proof = t + .waterfall(block, &accesses, &reads) + .ok() + .or_else(|| t.waterfall_shape(block, &accesses, &reads, &loads)); + if let Some(proof) = proof { out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); out.waterfall.loads.extend(loads); @@ -2128,6 +2134,213 @@ impl<'a> Tracer<'a> { Ok(out) } + /// The console compiler's waterfall over a first-lane table offset, by + /// its exact shape, where [`Self::waterfall`] cannot follow the lanes + /// (its per-lane form loses the relation of the two lane masks around + /// the loop in larger programs). The loop is one block that branches to + /// itself with `s_cbranch_execnz`, and holds nothing but: + /// + /// - `v_readfirstlane_b32 sX, vY` of a value set before the loop, under + /// EXEC as the loop found it; + /// - `v_cmpx_eq_u32`/`_i32 exec, sX, vY` of the same two values, without + /// modifiers: EXEC becomes the lanes whose offset is the first lane's; + /// - the table loads at those offsets (`loads`), waits and `s_nop`; + /// - the accesses that use them, which only read (`buffer_load_*`, + /// `image_load*`, `image_sample*`, `image_gather*`), under that EXEC; + /// - `s_andn2_wrexec` of a mask T with itself (EXEC and T become T and + /// not EXEC), then the branch. + /// + /// And T is EXEC on every entry to the loop: from outside, T's value is + /// a move of the very EXEC value the loop starts with; around the back + /// edge both are what that one `s_andn2_wrexec` wrote. So each pass + /// serves the waiting lanes with the first one's offset, drops exactly + /// those, and the loop ends when none waits: every lane makes its own + /// access once, with its own entry, which is what the per-lane load + /// does. + fn waterfall_shape( + &self, + b: usize, + accesses: &[usize], + reads: &[Value], + loads: &[Site], + ) -> Option<Waterfall> { + let block = &self.p.blocks[b]; + let wave64 = self.p.wave64; + let halves: &[u8] = if wave64 { &[0, 1] } else { &[0] }; + if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) + || block.preds.len() != 2 + { + return None; + } + let back = block.preds.iter().position(|&p| p == b)?; + let entry = 1 - back; + let (exit, body) = block.insts.split_last()?; + if exit.name() != "s_cbranch_execnz" { + return None; + } + let (retry, body) = body.split_last()?; + let wrexec = if wave64 { + "s_andn2_wrexec_b64" + } else { + "s_andn2_wrexec_b32" + }; + if retry.name() != wrexec { + return None; + } + // T: the mask the retry reads and writes besides EXEC. + let t = retry.writes.iter().find_map(|&(reg, _)| match reg { + Reg::S(code) if code != EXEC && code != EXEC + 1 => Some(code), + _ => None, + })?; + let t = t - t % 2 * u8::from(wave64); + let phi = |reg: u8| block.phis.iter().find(|p| p.reg == Reg::S(reg)); + let mut head_exec = Vec::new(); + for &k in halves { + let (pe, pt) = (phi(EXEC + k)?, phi(t + k)?); + // Around the back edge: both what the retry wrote, from T as the + // loop found it. + if pe.args[back] != retry.write(Reg::S(EXEC + k))? + || pt.args[back] != retry.write(Reg::S(t + k))? + || retry.read(Reg::S(t + k))? != pt.value + { + return None; + } + // From outside: T is a move of the EXEC the loop is entered with. + let (tb, ti) = self.defs[pt.args[entry].0 as usize]?; + let mov = self.inst((tb, ti)); + let moves = if wave64 { "s_mov_b64" } else { "s_mov_b32" }; + if mov.name() != moves || mov.read(Reg::S(EXEC + k))? != pe.args[entry] { + return None; + } + head_exec.push(pe.value); + } + let exec_is = |inst: &Inst, values: &[Value]| { + halves + .iter() + .zip(values) + .all(|(&k, &v)| inst.read(Reg::S(EXEC + k)) == Some(v)) + }; + let mut out = Waterfall::default(); + let mut selected: Option<Vec<Value>> = None; + // The lane value each first-lane read took, by the read's result. + let mut read_from: Vec<(Value, Value)> = Vec::new(); + for (i, inst) in body.iter().enumerate() { + let name = inst.name(); + let site = (b, i); + if name == "s_nop" || name.starts_with("s_waitcnt") { + continue; + } + if name == "v_readfirstlane_b32" { + // Before the compares, under the loop's own EXEC. + if selected.is_some() || !exec_is(inst, &head_exec) { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let Some(&Operand::Vector { reg, .. }) = f.src.first() else { + return None; + }; + let lane = inst.read(Reg::V(reg))?; + // Set before the loop: the same in every pass. + if self.phis[lane.0 as usize].is_some_and(|(pb, _)| pb == b) + || self.defs[lane.0 as usize].is_some_and(|(db, _)| db == b) + { + return None; + } + let &(_, got) = inst.writes.first()?; + read_from.push((got, lane)); + continue; + } + if name == "v_cmpx_eq_u32" || name == "v_cmpx_eq_i32" { + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 + || f.neg != 0 + || f.opsel != 0 + || f.clamp + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + // Compares narrow EXEC one after another. + let before = selected.clone().unwrap_or_else(|| head_exec.clone()); + if !exec_is(inst, &before) { + return None; + } + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + return None; + }; + let pair = |first: &Operand, own: &Operand| -> Option<Value> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = + (first, own) + else { + return None; + }; + let x = inst.read(Reg::S(code))?; + let lane = inst.read(Reg::V(reg))?; + read_from + .iter() + .any(|&(got, from)| got == x && from == lane) + .then_some(x) + }; + let x = pair(a, c).or_else(|| pair(c, a))?; + let narrowed = halves + .iter() + .map(|&k| inst.write(Reg::S(EXEC + k))) + .collect::<Option<Vec<_>>>()?; + selected = Some(narrowed); + out.compares.push(site); + if !out.reads.contains(&x) { + out.reads.push(x); + } + continue; + } + let sel = selected.as_deref()?; + if loads.contains(&site) { + continue; + } + let reads_only = name.starts_with("buffer_load") + || name.starts_with("image_load") + || name.starts_with("image_sample") + || name.starts_with("image_gather"); + if accesses.contains(&i) && reads_only && exec_is(inst, sel) { + continue; + } + return None; + } + // The retry takes T and not the EXEC the compares left. + let sel = selected?; + if !exec_is(retry, &sel) { + return None; + } + // Every offset read is one a compare made the lane's own, and every + // access was seen. + if reads.iter().any(|v| !out.reads.contains(v)) || accesses.iter().any(|&i| i >= body.len()) + { + return None; + } + // Read nowhere else: made the lane's own, a first-lane value must + // not reach code past the loop, which would see the last pass's. + for (ob, other) in self.p.blocks.iter().enumerate() { + let carried = other + .phis + .iter() + .any(|p| p.args.iter().any(|a| out.reads.contains(a))); + let read_there = ob != b + && other + .insts + .iter() + .any(|inst| inst.reads.iter().any(|(_, v)| out.reads.contains(v))); + if carried || read_there { + return None; + } + } + Some(out) + } + /// Consecutive dwords of one scalar load. fn loaded(&self, words: &[Term]) -> Option<Source> { let Term::Value(v0) = words[0] else { @@ -3382,6 +3595,138 @@ pub(crate) mod tests { assert_eq!(r.waterfall.loads, [load]); } + /// [`WATERFALL_INDEXED_WAVE32`] as a wave of 64 runs it: EXEC saved + /// and the lanes still waiting kept in SGPR pairs, the retry + /// `s_andn2_wrexec_b64`. + fn waterfall_indexed_wave64() -> Vec<u32> { + let mut w = WATERFALL_INDEXED_WAVE32.to_vec(); + for (from, to) in [ + (0xBE97_037E, 0xBE96_047E), // s_mov_b64 s[22:23], exec + (0xBE95_037E, 0xBE98_047E), // s_mov_b64 s[24:25], exec + (0xBE95_4715, 0xBE98_3A18), // s_andn2_wrexec_b64 s[24:25], s[24:25] + (0xBEFE_0317, 0xBEFE_0416), // s_mov_b64 exec, s[22:23] + ] { + let at = word_at(&w, from); + w[at] = to; + } + w + } + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_is_one_in_a_wave_of_64() { + let r = waterfall(&waterfall_indexed_wave64(), true).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Loaded { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + assert_eq!(r.waterfall.compares.len(), 1); + assert_eq!(r.waterfall.reads.len(), 1); + assert_eq!(r.waterfall.loads, [load]); + } + + /// [`Tracer::waterfall_shape`] on the one loop of `words`, with what + /// [`track`] would hand it: the loop's table loads, its first-lane reads + /// and its buffer and image accesses. + fn by_shape(words: &[u32], wave64: bool) -> Option<Waterfall> { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, wave64, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + let lanes = lanes(&p); + let t = Tracer::new(&p, &layout, HwStage::Cs, lanes.as_ref()).unwrap(); + let b = (0..p.blocks.len()) + .find(|&b| matches!(p.blocks[b].exit, Exit::Branch { taken, .. } if taken == b)) + .unwrap(); + let insts = &p.blocks[b].insts; + let loads: Vec<Site> = (0..insts.len()) + .filter(|&i| insts[i].name().starts_with("s_load_")) + .map(|i| (b, i)) + .collect(); + let reads: Vec<Value> = insts + .iter() + .filter(|i| i.name() == "v_readfirstlane_b32") + .filter_map(|i| i.writes.first().map(|w| w.1)) + .collect(); + let accesses: Vec<usize> = (0..insts.len()) + .filter(|&i| { + matches!( + insts[i].fields, + Fields::Buffer { .. } | Fields::Image { .. } + ) + }) + .collect(); + t.waterfall_shape(b, &accesses, &reads, &loads) + } + + /// [`WATERFALL_INDEXED_WAVE32`] or [`waterfall_indexed_wave64`] with + /// words replaced. + fn indexed_with(wave64: bool, changes: &[(u32, u32)]) -> Vec<u32> { + let mut w = if wave64 { + waterfall_indexed_wave64() + } else { + WATERFALL_INDEXED_WAVE32.to_vec() + }; + for &(from, to) in changes { + let at = word_at(&w, from); + w[at] = to; + } + w + } + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_holds_by_its_shape() { + for wave64 in [false, true] { + let shape = by_shape(&indexed_with(wave64, &[]), wave64) + .unwrap_or_else(|| panic!("wave64 {wave64}")); + assert_eq!(shape.compares.len(), 1, "wave64 {wave64}"); + assert_eq!(shape.reads.len(), 1, "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_loop_with_other_work_in_it_is_none_by_shape() { + for wave64 in [false, true] { + // s_waitcnt vmcnt(0) in the loop becomes v_mov_b32 v20, v7. + let words = indexed_with(wave64, &[(0xBF8C_3F70, 0x7E28_0307)]); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_comparing_another_lane_value_is_none_by_shape() { + for wave64 in [false, true] { + // v_cmpx_eq_u32 exec, s20, v0: the lane's index, not the offset + // the first lane's was read from (v7). + let words = indexed_with(wave64, &[(0x7DA4_0E14, 0x7DA4_0014)]); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_whose_lanes_to_do_are_not_exec_is_none_by_shape() { + // The mask of lanes still to do starts as every lane, not EXEC. + let words = indexed_with(false, &[(0xBE95_037E, 0xBE95_03C1)]); // s_mov_b32 s21, -1 + assert!(by_shape(&words, false).is_none()); + let words = indexed_with(true, &[(0xBE98_047E, 0xBE98_04C1)]); // s_mov_b64 s[24:25], -1 + assert!(by_shape(&words, true).is_none()); + } + + #[test] + fn a_first_lane_offset_read_after_its_loop_is_none_by_shape() { + for wave64 in [false, true] { + // The store after the loop becomes v_mov_b32 v20, s20 (the + // first lane's offset of the last pass) and s_nop. + let words = indexed_with( + wave64, + &[(0xE070_1000, 0x7E28_0214), (0x800A_0C10, 0xBF80_0000)], + ); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the From fe91b2707d2dcea3614586806f808671ea3b93c7 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 17:48:35 -0500 Subject: [PATCH 09/57] README: 32 frames a second, 62 shown with FSR 3 frame generation; the waterfall change; the FSR 3 start-up crash and its way round Measured on the RTX 3090 Ti in the prologue's cell with this build: 32.0 fps without frame generation (Series S, no DLSS), and with DLSS Quality and AMD FSR 3 frame generation 30.8 rendered and 62.2 shown (F3). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 57 ++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index ba98ab839..0ea4cb8c3 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # VIctory-Neo **The Xbox Series build of the title, running on a Windows PC from your own -files, at about 30 frames a second.** +files: about 32 frames a second, and over 60 on screen with frame generation.** VIctory-Neo is a build of [VIctory](https://github.com/Marvisak/VIctory), the compatibility layer that runs an Xbox Series title natively on Windows. The @@ -21,10 +21,11 @@ shows it), medians over the 5-second readings of a run, hands off. | Scene | Profile | Frames a second | |---|---|---| -| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **31** (readings 29 to 34) | -| Opening cutscene | Series S | about 28 on average, 20 to 37 by shot | -| Prologue, the cell | Series X, scene 1920x1080, 2560x1440 out | 26 | -| Prologue, the cell | Series X, native 2560x1440 | 23 | +| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **32** (readings 29 to 33) | +| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **31 rendered, 62 shown** (F3: `FPS: 31.1 FG: 62.2`) | +| Opening cutscene | Series S | about 28 on average, 20 to 37 by shot (before the shader change below) | +| Prologue, the cell | Series X, scene 1920x1080, 2560x1440 out | 26 (before the shader change below) | +| Prologue, the cell | Series X, native 2560x1440 | 23 (before the shader change below) | - The boot screens, the account picker, the loading art and the opening cutscene play in order, and the prologue's first room stands. @@ -51,6 +52,9 @@ cell at 17 to 19 frames a second. launches while shaders are translated and pipelines made (see below). - **Above 30 frames a second the game runs a little fast.** The title steps its world at least 1/30 s a frame. `--fps 30` holds it at its own rate. + (Frames made by frame generation do not count: 31 rendered is 31.) +- **Frame generation adds latency** (about one rendered frame), as it does + in any game, and its in-between frames can smear fast motion. - **Memory.** On this PC it takes up to 43 GB of RAM, with a 24 GB card that it fills with textures. Close what you can. foxhound measures 20 GB in use (28 GB committed) on a 32 GB PC with a 12 GB card. @@ -72,14 +76,30 @@ target\release\victory.exe play "D:\MyDump\game_scarlett_master.exe" --series-s Put the path of **your** `game_scarlett_master.exe` in the last line. That is all: the settings these numbers were measured with are built in. +**60 on screen on an RTX 20 or 30** (AMD FSR 3 frame generation, with DLSS +doing the upscaling): + +```powershell +target\release\victory.exe get-dlss # once: NVIDIA's DLSS files, from NVIDIA's GitHub +target\release\victory.exe get-fsr # once: AMD's FSR 3 files, from AMD's GitHub +target\release\victory.exe play "D:\MyDump\game_scarlett_master.exe" --series-s --dlss quality --framegen 2 --fg-type fsr +``` + +On an RTX 40 or 50, `--framegen 2` (or more, on an RTX 50) uses DLSS frame +generation instead; that was not measured here. + - **The first launches are slow, and that is expected.** The first start translates the title's shaders (minutes) and the driver compiles each pipeline the first time it is drawn. A launch may even end in the title's own watchdog while that goes on; start it again. Each launch writes down what it needed, so it gets smoother over the first two or three. - **The first start asks once whether to download NVIDIA's DLSS files** - (RTX cards). Answer `n` for what was measured here; with them, DLSS takes - the title's upscaling and the numbers above no longer apply. + (RTX cards). Either way works: in the cell DLSS Quality measured 31.4 and + Performance 31.7 against 30.9 without it, before the shader change below. + The card's time there goes to the number of commands, not to pixels. +- **Known crash, with a way round it:** with AMD's FSR 3 files fetched and + `--dlss off`, the start prepares FSR 3 and the program ends during the boot + screens ([report](https://github.com/trustno1-coder/VIctory-NVIDIA/issues/459)). Add `--no-framegen-ready`. - **F3** shows the stats panel, **F1** the settings menu (console profile, picture size, frame rate cap, the light estimate and the main switches). - Nothing is written into your game folder: caches, saves, settings and logs @@ -95,15 +115,15 @@ Other ways to run it: | `victory.exe play <exe> --series-s --set VICTORY_X=1` | add or override a switch | | `scripts\play-foxhound.ps1 -Exe <exe> -SeriesS` | the same from PowerShell, with a log file | -**DLSS** (RTX cards) and **DLSS frame generation** (RTX 40 and 50) come with -the tree this is built on: `Get-NVIDIA-DLSS.cmd` fetches NVIDIA's files from -NVIDIA (they are NVIDIA's, under NVIDIA's licence, and not part of this -repository); [docs/dlss.md](docs/dlss.md) has the details. They were **not -measured here**: the numbers above are without them. +**DLSS**, **DLSS frame generation** (RTX 40 and 50) and **AMD FSR 3 frame +generation** (any card) come with the tree this is built on. Their files are +NVIDIA's and AMD's, under their licences, fetched from their own GitHub by +`victory.exe get-dlss` and `get-fsr` and never part of this repository; +[docs/dlss.md](docs/dlss.md) has the details. ## What Neo adds -Two changes on top of the tree it is built on, each measured in the game on +Three changes on top of the tree it is built on, each measured in the game on the PC above and sent to that project as a pull request: 1. **The Series S profile keeps the title's own upscaler** where no DLSS is @@ -121,6 +141,17 @@ the PC above and sent to that project as a pull request: cache, so **the cause of the missing print here is not known yet**: the fresh cache is what fixed it, not the order. (Pull request in draft until that is tested.) +3. **The console's per-lane descriptor loops run once instead of once per + distinct value.** The console's compiler loops over a per-lane descriptor + (read the first lane's table offset, serve the lanes with the same one, + repeat). The translator turns such a loop into one per-lane load only when + it can prove it, and in the title's shaders it mostly could not: 44,874 + loops were refused. Run on a card whose waves are half as wide as the + console's, each pass of such a loop costs four group barriers. A check of + the loop's exact shape now proves 32,106 of them. The costliest shader of + the frame (a decal pass, 4 ms of the card's time) went from 149 barriers + to 41, and the cell from 30.8 to 32 to 33 frames a second + ([pull request](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/458)). Also in the tree, off by default: `VICTORY_GUARDS_SPIN=<microseconds>`, a shorter wait on the write tracker's lock. A profile had the thread that From 159f3796a0032c577355e8cda4bfef2205bd9127 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 18:00:04 -0500 Subject: [PATCH 10/57] Revert the waterfall-by-shape change: with it, a wall in the prologue's cell shows a dark patch with tile-aligned edges in 3 runs of 5 Measured as the mean brightness of that wall in the last 12 screenshots of each run: about 40 in three of the five runs with the change, about 64 in all seven runs without it. Whether the change is wrong or only exposes a missing wait elsewhere is not known yet; until it is, Neo goes without it. This reverts commit e9bb461. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/victory-shader/src/resource.rs | 347 +------------------------- 1 file changed, 1 insertion(+), 346 deletions(-) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ae16c51ed..ddc03dddd 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -363,13 +363,7 @@ pub fn track( for (block, (accesses, mut reads, loads)) in offset_at { reads.sort_unstable(); reads.dedup(); - // Where the per-lane form cannot follow the loop, its exact shape - // still proves it ([`Tracer::waterfall_shape`]). - let proof = t - .waterfall(block, &accesses, &reads) - .ok() - .or_else(|| t.waterfall_shape(block, &accesses, &reads, &loads)); - if let Some(proof) = proof { + if let Ok(proof) = t.waterfall(block, &accesses, &reads) { out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); out.waterfall.loads.extend(loads); @@ -2134,213 +2128,6 @@ impl<'a> Tracer<'a> { Ok(out) } - /// The console compiler's waterfall over a first-lane table offset, by - /// its exact shape, where [`Self::waterfall`] cannot follow the lanes - /// (its per-lane form loses the relation of the two lane masks around - /// the loop in larger programs). The loop is one block that branches to - /// itself with `s_cbranch_execnz`, and holds nothing but: - /// - /// - `v_readfirstlane_b32 sX, vY` of a value set before the loop, under - /// EXEC as the loop found it; - /// - `v_cmpx_eq_u32`/`_i32 exec, sX, vY` of the same two values, without - /// modifiers: EXEC becomes the lanes whose offset is the first lane's; - /// - the table loads at those offsets (`loads`), waits and `s_nop`; - /// - the accesses that use them, which only read (`buffer_load_*`, - /// `image_load*`, `image_sample*`, `image_gather*`), under that EXEC; - /// - `s_andn2_wrexec` of a mask T with itself (EXEC and T become T and - /// not EXEC), then the branch. - /// - /// And T is EXEC on every entry to the loop: from outside, T's value is - /// a move of the very EXEC value the loop starts with; around the back - /// edge both are what that one `s_andn2_wrexec` wrote. So each pass - /// serves the waiting lanes with the first one's offset, drops exactly - /// those, and the loop ends when none waits: every lane makes its own - /// access once, with its own entry, which is what the per-lane load - /// does. - fn waterfall_shape( - &self, - b: usize, - accesses: &[usize], - reads: &[Value], - loads: &[Site], - ) -> Option<Waterfall> { - let block = &self.p.blocks[b]; - let wave64 = self.p.wave64; - let halves: &[u8] = if wave64 { &[0, 1] } else { &[0] }; - if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) - || block.preds.len() != 2 - { - return None; - } - let back = block.preds.iter().position(|&p| p == b)?; - let entry = 1 - back; - let (exit, body) = block.insts.split_last()?; - if exit.name() != "s_cbranch_execnz" { - return None; - } - let (retry, body) = body.split_last()?; - let wrexec = if wave64 { - "s_andn2_wrexec_b64" - } else { - "s_andn2_wrexec_b32" - }; - if retry.name() != wrexec { - return None; - } - // T: the mask the retry reads and writes besides EXEC. - let t = retry.writes.iter().find_map(|&(reg, _)| match reg { - Reg::S(code) if code != EXEC && code != EXEC + 1 => Some(code), - _ => None, - })?; - let t = t - t % 2 * u8::from(wave64); - let phi = |reg: u8| block.phis.iter().find(|p| p.reg == Reg::S(reg)); - let mut head_exec = Vec::new(); - for &k in halves { - let (pe, pt) = (phi(EXEC + k)?, phi(t + k)?); - // Around the back edge: both what the retry wrote, from T as the - // loop found it. - if pe.args[back] != retry.write(Reg::S(EXEC + k))? - || pt.args[back] != retry.write(Reg::S(t + k))? - || retry.read(Reg::S(t + k))? != pt.value - { - return None; - } - // From outside: T is a move of the EXEC the loop is entered with. - let (tb, ti) = self.defs[pt.args[entry].0 as usize]?; - let mov = self.inst((tb, ti)); - let moves = if wave64 { "s_mov_b64" } else { "s_mov_b32" }; - if mov.name() != moves || mov.read(Reg::S(EXEC + k))? != pe.args[entry] { - return None; - } - head_exec.push(pe.value); - } - let exec_is = |inst: &Inst, values: &[Value]| { - halves - .iter() - .zip(values) - .all(|(&k, &v)| inst.read(Reg::S(EXEC + k)) == Some(v)) - }; - let mut out = Waterfall::default(); - let mut selected: Option<Vec<Value>> = None; - // The lane value each first-lane read took, by the read's result. - let mut read_from: Vec<(Value, Value)> = Vec::new(); - for (i, inst) in body.iter().enumerate() { - let name = inst.name(); - let site = (b, i); - if name == "s_nop" || name.starts_with("s_waitcnt") { - continue; - } - if name == "v_readfirstlane_b32" { - // Before the compares, under the loop's own EXEC. - if selected.is_some() || !exec_is(inst, &head_exec) { - return None; - } - let Fields::Valu(f) = &inst.fields else { - return None; - }; - let Some(&Operand::Vector { reg, .. }) = f.src.first() else { - return None; - }; - let lane = inst.read(Reg::V(reg))?; - // Set before the loop: the same in every pass. - if self.phis[lane.0 as usize].is_some_and(|(pb, _)| pb == b) - || self.defs[lane.0 as usize].is_some_and(|(db, _)| db == b) - { - return None; - } - let &(_, got) = inst.writes.first()?; - read_from.push((got, lane)); - continue; - } - if name == "v_cmpx_eq_u32" || name == "v_cmpx_eq_i32" { - let Fields::Valu(f) = &inst.fields else { - return None; - }; - if f.abs != 0 - || f.neg != 0 - || f.opsel != 0 - || f.clamp - || f.sdwa.is_some() - || f.dpp.is_some() - { - return None; - } - // Compares narrow EXEC one after another. - let before = selected.clone().unwrap_or_else(|| head_exec.clone()); - if !exec_is(inst, &before) { - return None; - } - let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { - return None; - }; - let pair = |first: &Operand, own: &Operand| -> Option<Value> { - let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = - (first, own) - else { - return None; - }; - let x = inst.read(Reg::S(code))?; - let lane = inst.read(Reg::V(reg))?; - read_from - .iter() - .any(|&(got, from)| got == x && from == lane) - .then_some(x) - }; - let x = pair(a, c).or_else(|| pair(c, a))?; - let narrowed = halves - .iter() - .map(|&k| inst.write(Reg::S(EXEC + k))) - .collect::<Option<Vec<_>>>()?; - selected = Some(narrowed); - out.compares.push(site); - if !out.reads.contains(&x) { - out.reads.push(x); - } - continue; - } - let sel = selected.as_deref()?; - if loads.contains(&site) { - continue; - } - let reads_only = name.starts_with("buffer_load") - || name.starts_with("image_load") - || name.starts_with("image_sample") - || name.starts_with("image_gather"); - if accesses.contains(&i) && reads_only && exec_is(inst, sel) { - continue; - } - return None; - } - // The retry takes T and not the EXEC the compares left. - let sel = selected?; - if !exec_is(retry, &sel) { - return None; - } - // Every offset read is one a compare made the lane's own, and every - // access was seen. - if reads.iter().any(|v| !out.reads.contains(v)) || accesses.iter().any(|&i| i >= body.len()) - { - return None; - } - // Read nowhere else: made the lane's own, a first-lane value must - // not reach code past the loop, which would see the last pass's. - for (ob, other) in self.p.blocks.iter().enumerate() { - let carried = other - .phis - .iter() - .any(|p| p.args.iter().any(|a| out.reads.contains(a))); - let read_there = ob != b - && other - .insts - .iter() - .any(|inst| inst.reads.iter().any(|(_, v)| out.reads.contains(v))); - if carried || read_there { - return None; - } - } - Some(out) - } - /// Consecutive dwords of one scalar load. fn loaded(&self, words: &[Term]) -> Option<Source> { let Term::Value(v0) = words[0] else { @@ -3595,138 +3382,6 @@ pub(crate) mod tests { assert_eq!(r.waterfall.loads, [load]); } - /// [`WATERFALL_INDEXED_WAVE32`] as a wave of 64 runs it: EXEC saved - /// and the lanes still waiting kept in SGPR pairs, the retry - /// `s_andn2_wrexec_b64`. - fn waterfall_indexed_wave64() -> Vec<u32> { - let mut w = WATERFALL_INDEXED_WAVE32.to_vec(); - for (from, to) in [ - (0xBE97_037E, 0xBE96_047E), // s_mov_b64 s[22:23], exec - (0xBE95_037E, 0xBE98_047E), // s_mov_b64 s[24:25], exec - (0xBE95_4715, 0xBE98_3A18), // s_andn2_wrexec_b64 s[24:25], s[24:25] - (0xBEFE_0317, 0xBEFE_0416), // s_mov_b64 exec, s[22:23] - ] { - let at = word_at(&w, from); - w[at] = to; - } - w - } - - #[test] - fn the_console_waterfall_over_a_first_lane_offset_is_one_in_a_wave_of_64() { - let r = waterfall(&waterfall_indexed_wave64(), true).unwrap(); - let image = r - .descriptors - .iter() - .find(|d| d.role == Role::Resource) - .unwrap(); - let Source::Loaded { load, first: 0 } = image.source else { - panic!("{:?}", image.source) - }; - assert_eq!(r.waterfall.compares.len(), 1); - assert_eq!(r.waterfall.reads.len(), 1); - assert_eq!(r.waterfall.loads, [load]); - } - - /// [`Tracer::waterfall_shape`] on the one loop of `words`, with what - /// [`track`] would hand it: the loop's table loads, its first-lane reads - /// and its buffer and image accesses. - fn by_shape(words: &[u32], wave64: bool) -> Option<Waterfall> { - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let p = crate::ir::build(&code, wave64, 256).unwrap(); - let layout = [param(Table, 0, 1), param(Table, 1, 1)]; - let lanes = lanes(&p); - let t = Tracer::new(&p, &layout, HwStage::Cs, lanes.as_ref()).unwrap(); - let b = (0..p.blocks.len()) - .find(|&b| matches!(p.blocks[b].exit, Exit::Branch { taken, .. } if taken == b)) - .unwrap(); - let insts = &p.blocks[b].insts; - let loads: Vec<Site> = (0..insts.len()) - .filter(|&i| insts[i].name().starts_with("s_load_")) - .map(|i| (b, i)) - .collect(); - let reads: Vec<Value> = insts - .iter() - .filter(|i| i.name() == "v_readfirstlane_b32") - .filter_map(|i| i.writes.first().map(|w| w.1)) - .collect(); - let accesses: Vec<usize> = (0..insts.len()) - .filter(|&i| { - matches!( - insts[i].fields, - Fields::Buffer { .. } | Fields::Image { .. } - ) - }) - .collect(); - t.waterfall_shape(b, &accesses, &reads, &loads) - } - - /// [`WATERFALL_INDEXED_WAVE32`] or [`waterfall_indexed_wave64`] with - /// words replaced. - fn indexed_with(wave64: bool, changes: &[(u32, u32)]) -> Vec<u32> { - let mut w = if wave64 { - waterfall_indexed_wave64() - } else { - WATERFALL_INDEXED_WAVE32.to_vec() - }; - for &(from, to) in changes { - let at = word_at(&w, from); - w[at] = to; - } - w - } - - #[test] - fn the_console_waterfall_over_a_first_lane_offset_holds_by_its_shape() { - for wave64 in [false, true] { - let shape = by_shape(&indexed_with(wave64, &[]), wave64) - .unwrap_or_else(|| panic!("wave64 {wave64}")); - assert_eq!(shape.compares.len(), 1, "wave64 {wave64}"); - assert_eq!(shape.reads.len(), 1, "wave64 {wave64}"); - } - } - - #[test] - fn a_waterfall_loop_with_other_work_in_it_is_none_by_shape() { - for wave64 in [false, true] { - // s_waitcnt vmcnt(0) in the loop becomes v_mov_b32 v20, v7. - let words = indexed_with(wave64, &[(0xBF8C_3F70, 0x7E28_0307)]); - assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); - } - } - - #[test] - fn a_waterfall_comparing_another_lane_value_is_none_by_shape() { - for wave64 in [false, true] { - // v_cmpx_eq_u32 exec, s20, v0: the lane's index, not the offset - // the first lane's was read from (v7). - let words = indexed_with(wave64, &[(0x7DA4_0E14, 0x7DA4_0014)]); - assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); - } - } - - #[test] - fn a_waterfall_whose_lanes_to_do_are_not_exec_is_none_by_shape() { - // The mask of lanes still to do starts as every lane, not EXEC. - let words = indexed_with(false, &[(0xBE95_037E, 0xBE95_03C1)]); // s_mov_b32 s21, -1 - assert!(by_shape(&words, false).is_none()); - let words = indexed_with(true, &[(0xBE98_047E, 0xBE98_04C1)]); // s_mov_b64 s[24:25], -1 - assert!(by_shape(&words, true).is_none()); - } - - #[test] - fn a_first_lane_offset_read_after_its_loop_is_none_by_shape() { - for wave64 in [false, true] { - // The store after the loop becomes v_mov_b32 v20, s20 (the - // first lane's offset of the last pass) and s_nop. - let words = indexed_with( - wave64, - &[(0xE070_1000, 0x7E28_0214), (0x800A_0C10, 0xBF80_0000)], - ); - assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); - } - } - /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the From fb39630838500e3eedfd682d8965a1f66ec429c2 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 18:00:25 -0500 Subject: [PATCH 11/57] README: back to the numbers without the reverted waterfall change (31 fps, 53 shown with FSR 3 frame generation); that change described as in progress and why Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 0ea4cb8c3..a3e2320ee 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # VIctory-Neo **The Xbox Series build of the title, running on a Windows PC from your own -files: about 32 frames a second, and over 60 on screen with frame generation.** +files: about 31 frames a second, and about 53 on screen with frame generation.** VIctory-Neo is a build of [VIctory](https://github.com/Marvisak/VIctory), the compatibility layer that runs an Xbox Series title natively on Windows. The @@ -21,11 +21,11 @@ shows it), medians over the 5-second readings of a run, hands off. | Scene | Profile | Frames a second | |---|---|---| -| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **32** (readings 29 to 33) | -| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **31 rendered, 62 shown** (F3: `FPS: 31.1 FG: 62.2`) | -| Opening cutscene | Series S | about 28 on average, 20 to 37 by shot (before the shader change below) | -| Prologue, the cell | Series X, scene 1920x1080, 2560x1440 out | 26 (before the shader change below) | -| Prologue, the cell | Series X, native 2560x1440 | 23 (before the shader change below) | +| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **31** (readings 27 to 33) | +| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **27 rendered, 53 shown** (F3: `FPS: 26.4 FG: 52.8`) | +| Opening cutscene | Series S | about 28 on average, 20 to 37 by shot | +| Prologue, the cell | Series X, scene 1920x1080, 2560x1440 out | 26 | +| Prologue, the cell | Series X, native 2560x1440 | 23 | - The boot screens, the account picker, the loading art and the opening cutscene play in order, and the prologue's first room stands. @@ -52,7 +52,7 @@ cell at 17 to 19 frames a second. launches while shaders are translated and pipelines made (see below). - **Above 30 frames a second the game runs a little fast.** The title steps its world at least 1/30 s a frame. `--fps 30` holds it at its own rate. - (Frames made by frame generation do not count: 31 rendered is 31.) + (Frames made by frame generation do not count: 27 rendered is 27.) - **Frame generation adds latency** (about one rendered frame), as it does in any game, and its in-between frames can smear fast motion. - **Memory.** On this PC it takes up to 43 GB of RAM, with a 24 GB card that @@ -76,8 +76,8 @@ target\release\victory.exe play "D:\MyDump\game_scarlett_master.exe" --series-s Put the path of **your** `game_scarlett_master.exe` in the last line. That is all: the settings these numbers were measured with are built in. -**60 on screen on an RTX 20 or 30** (AMD FSR 3 frame generation, with DLSS -doing the upscaling): +**More on screen on an RTX 20 or 30** (AMD FSR 3 frame generation, with DLSS +doing the upscaling; 53 shown here): ```powershell target\release\victory.exe get-dlss # once: NVIDIA's DLSS files, from NVIDIA's GitHub @@ -95,7 +95,7 @@ generation instead; that was not measured here. what it needed, so it gets smoother over the first two or three. - **The first start asks once whether to download NVIDIA's DLSS files** (RTX cards). Either way works: in the cell DLSS Quality measured 31.4 and - Performance 31.7 against 30.9 without it, before the shader change below. + Performance 31.7 against 30.9 without it. The card's time there goes to the number of commands, not to pixels. - **Known crash, with a way round it:** with AMD's FSR 3 files fetched and `--dlss off`, the start prepares FSR 3 and the program ends during the boot @@ -123,7 +123,7 @@ NVIDIA's and AMD's, under their licences, fetched from their own GitHub by ## What Neo adds -Three changes on top of the tree it is built on, each measured in the game on +Two changes on top of the tree it is built on, each measured in the game on the PC above and sent to that project as a pull request: 1. **The Series S profile keeps the title's own upscaler** where no DLSS is @@ -141,17 +141,15 @@ the PC above and sent to that project as a pull request: cache, so **the cause of the missing print here is not known yet**: the fresh cache is what fixed it, not the order. (Pull request in draft until that is tested.) -3. **The console's per-lane descriptor loops run once instead of once per - distinct value.** The console's compiler loops over a per-lane descriptor - (read the first lane's table offset, serve the lanes with the same one, - repeat). The translator turns such a loop into one per-lane load only when - it can prove it, and in the title's shaders it mostly could not: 44,874 - loops were refused. Run on a card whose waves are half as wide as the - console's, each pass of such a loop costs four group barriers. A check of - the loop's exact shape now proves 32,106 of them. The costliest shader of - the frame (a decal pass, 4 ms of the card's time) went from 149 barriers - to 41, and the cell from 30.8 to 32 to 33 frames a second - ([pull request](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/458)). +In progress, not in the build: **the console's per-lane descriptor loops run +once instead of once per distinct value** (a [pull request](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/458), +now in draft). The translator proves only some of these loops and runs the +rest as loops that cost four group barriers a pass on a card whose waves are +half as wide as the console's. A check of the loop's shape proved 32,106 +more of them, and the cell went from 31 to 32 to 33 frames a second (62 shown +with frame generation). But in 3 runs of 5 a wall in the cell then showed a +dark patch with tile-aligned edges, which it never shows without the change, +so it was taken out again until the cause is found. Also in the tree, off by default: `VICTORY_GUARDS_SPIN=<microseconds>`, a shorter wait on the write tracker's lock. A profile had the thread that From 2516a4b5ae0e71a4a05e5836d5a07646f6769a7a Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 18:36:02 -0500 Subject: [PATCH 12/57] README: DLSS frame generation on RTX 20/30 through MFG Unlocker (2x to 6x: 48 to 132 shown), its trade-off; the wall patch is an older fault seen without the waterfall change too Measured on the RTX 3090 Ti in the prologue's cell with this build, Series S, DLSS Quality, --set VICTORY_MFG_UNLOCKER=1, one run each: 2x 23.8 rendered / 48 shown, 3x 23.0 / 72, 4x 22.5 / 92, 6x 21.8 / 132 (frames shown per present exactly 2.00, 3.00, 4.00, 6.00; status 0x0). The 6x run, without the waterfall change, showed the dark wall patch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a3e2320ee..2d79851b9 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # VIctory-Neo **The Xbox Series build of the title, running on a Windows PC from your own -files: about 31 frames a second, and about 53 on screen with frame generation.** +files: about 31 frames a second, and 53 to 132 on screen with frame generation.** VIctory-Neo is a build of [VIctory](https://github.com/Marvisak/VIctory), the compatibility layer that runs an Xbox Series title natively on Windows. The @@ -23,6 +23,7 @@ shows it), medians over the 5-second readings of a run, hands off. |---|---|---| | Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **31** (readings 27 to 33) | | the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **27 rendered, 53 shown** (F3: `FPS: 26.4 FG: 52.8`) | +| the same | Series S, DLSS Quality and DLSS frame generation through MFG Unlocker (a mod, below), 2x / 3x / 4x / 6x | 24 / 23 / 22.5 / 22 rendered; **48 / 72 / 92 / 132 shown** (F3 at 6x: `FPS: 21.5 FG: 129.0`) | | Opening cutscene | Series S | about 28 on average, 20 to 37 by shot | | Prologue, the cell | Series X, scene 1920x1080, 2560x1440 out | 26 | | Prologue, the cell | Series X, native 2560x1440 | 23 | @@ -48,6 +49,9 @@ cell at 17 to 19 frames a second. rays: a few frames a second and a broken picture. - **Haze through windows.** Bright views through glass (the cell's window) are smeared; cause not found yet. +- **A dark patch on a wall, in some runs.** In about one run in ten, the + wall to the left of the character in the cell shows a dark patch with + blocky edges for the whole run; cause not found yet. - **Hitches** when the title streams a new scene in, and during the first launches while shaders are translated and pipelines made (see below). - **Above 30 frames a second the game runs a little fast.** The title steps @@ -88,6 +92,28 @@ target\release\victory.exe play "D:\MyDump\game_scarlett_master.exe" --series-s On an RTX 40 or 50, `--framegen 2` (or more, on an RTX 50) uses DLSS frame generation instead; that was not measured here. +**Up to 132 on screen on an RTX 20 or 30, with a mod.** +[MFG Unlocker](https://github.com/dashdogy/MFG-Unlocker) is someone else's +mod (MIT licence, not signed): it lets DLSS frame generation, and more than +one generated frame per real one, run on RTX 20 and 30 cards. The launcher +fetches the release it was written for and checks it against its published +SHA-256 (`get-mfg`); it is loaded into `victory.exe` only when you turn it on: + +```powershell +target\release\victory.exe get-dlss +target\release\victory.exe get-mfg +target\release\victory.exe play "D:\MyDump\game_scarlett_master.exe" --series-s --dlss quality --framegen 4 --fg-type dlss --set VICTORY_MFG_UNLOCKER=1 +``` + +`--framegen` takes 2 to 6; F1, MFG UNLOCKER switches it on and off later. +Backspace opens the mod's own menu, which also opens by itself on its first +start. **The trade-off:** DLSS frame generation costs this card more than +FSR 3 does (22 to 24 real frames a second instead of 27), and frame +generation never makes the game answer faster: at 4x you see 92 frames a +second, but the game still reacts at about 22. For the quickest response +use FSR 3 at 2x, or no frame generation (31). Keep the shown rate under your +monitor's refresh rate. + - **The first launches are slow, and that is expected.** The first start translates the title's shaders (minutes) and the driver compiles each pipeline the first time it is drawn. A launch may even end in the title's @@ -147,9 +173,10 @@ now in draft). The translator proves only some of these loops and runs the rest as loops that cost four group barriers a pass on a card whose waves are half as wide as the console's. A check of the loop's shape proved 32,106 more of them, and the cell went from 31 to 32 to 33 frames a second (62 shown -with frame generation). But in 3 runs of 5 a wall in the cell then showed a -dark patch with tile-aligned edges, which it never shows without the change, -so it was taken out again until the cause is found. +with frame generation). It was taken out again because a wall in the cell +then showed a dark patch in 3 runs of 5. The same patch later turned up +without the change too (1 run of 10), so it is an older fault; whether the +change makes it more likely is being measured before it goes back in. Also in the tree, off by default: `VICTORY_GUARDS_SPIN=<microseconds>`, a shorter wait on the write tracker's lock. A profile had the thread that From 018d54fed45716e689ab592d63fdca5349fa4cb3 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 04:30:20 +0000 Subject: [PATCH 13/57] Two-die Ryzens and 8 GB cards: frame threads on one die, target reserve sized to the card, a native build - cores.rs: where all cores are alike but share more than one L3 (Ryzen 9 9900X/9950X/7900X: two CCDs), the threads a frame waits for and their helpers are kept on the die of the preferred cores, so their hand-overs stay in one L3 (VICTORY_ONE_CCD=0: not). List translators and the title's threads keep both dies; hybrid Intel and single-die Ryzens as before. - resource.rs: the room the texture queue keeps for render targets not made yet is 3,072 MiB or three tenths of the card's budget, whichever is less (VICTORY_CARD_ROOM_FOR_TARGETS_MB still wins). Unchanged on 12 GB cards; on 8 GB cards the flat 3,072 left the scene black while textures waited for room. - Cargo.toml [profile.native] (fat LTO, one codegen unit) and play-foxhound.ps1 -Build native (RUSTFLAGS=-C target-cpu=native). - docs/ryzen-9900x-rtx-3070ti.md: settings to start from on such a PC. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- Cargo.toml | 12 +++ README.md | 3 + crates/victory-gpu/src/cores.rs | 117 ++++++++++++++++++++++++----- crates/victory-gpu/src/resource.rs | 54 +++++++++++-- docs/ryzen-9900x-rtx-3070ti.md | 67 +++++++++++++++++ scripts/play-foxhound.ps1 | 10 ++- 6 files changed, 235 insertions(+), 28 deletions(-) create mode 100644 docs/ryzen-9900x-rtx-3070ti.md diff --git a/Cargo.toml b/Cargo.toml index 4e21b692d..554633edb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,3 +77,15 @@ debug = "line-tables-only" # kept in its own folder so it does not evict the plain release build. [profile.diag] inherits = "release" + +# A build for the PC it is built on: release plus whole-program optimisation +# (`lto`, one code generation unit). Built with the CPU's own instructions +# (`scripts\play-foxhound.ps1 -Build native` sets RUSTFLAGS=-C target-cpu=native: +# AVX-512 on a Ryzen 9000), so the exe may not start on another processor. +# Into target\native, beside the release build, not in its place. Slower to +# build (several minutes more); helps the CPU side (the shader translator, +# hashing, copies), not the card. +[profile.native] +inherits = "release" +lto = "fat" +codegen-units = 1 diff --git a/README.md b/README.md index e6bd64b3b..2cd523719 100644 --- a/README.md +++ b/README.md @@ -354,6 +354,9 @@ to check memory on systems with 32 GB of RAM or GPUs with 8 GB of VRAM. - [docs/architecture.md](docs/architecture.md): the layer's parts. - [docs/findings.md](docs/findings.md): measurements behind the choices. - [docs/dlss.md](docs/dlss.md): DLSS and Frame Generation. +- [docs/ryzen-9900x-rtx-3070ti.md](docs/ryzen-9900x-rtx-3070ti.md): a + two-die Ryzen with an 8 GB card: what the layer does for it and the + settings to start from. - [docs/linux-proton.md](docs/linux-proton.md): building on Linux and first runs under Proton (experimental). - [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md): the title's ray tracing diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs index b0a6e1396..262a5808a 100644 --- a/crates/victory-gpu/src/cores.rs +++ b/crates/victory-gpu/src/cores.rs @@ -1,10 +1,24 @@ //! Which processors our own threads run on, where a processor has two kinds -//! of cores. `cpu_sets` and `keep_on_fast_cores` are fxceless/victory-fork's -//! (`framelog.rs`, commit 0b0074e0, GPL-3.0-or-later, as this). +//! of cores, or its cores in more than one group around a cache of their own +//! (a Ryzen of two dies: 9900X, 9950X, 7900X, 5900X ...). `cpu_sets` and +//! `keep_on_fast_cores` are fxceless/victory-fork's (`framelog.rs`, commit +//! 0b0074e0, GPL-3.0-or-later, as this). -/// The system's processor sets of group 0: each one's id and its efficiency -/// class (higher is faster). -fn cpu_sets() -> Vec<(u32, u8)> { +/// One of the system's processor sets of group 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Set { + id: u32, + /// Efficiency class: higher is faster. + class: u8, + /// The last-level cache it shares (a Ryzen's die: its L3). + cache: u8, + /// The system's ranking of it for single threads (CPPC's preferred + /// cores; 0 where Windows does not say). + rank: u8, +} + +/// The system's processor sets of group 0. +fn cpu_sets() -> Vec<Set> { use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut bytes = 0u32; @@ -24,7 +38,9 @@ fn cpu_sets() -> Vec<(u32, u8)> { // SAFETY: the record's type is CpuSet (the only one there is). let set = unsafe { &info.Anonymous.CpuSet }; if set.Group == 0 { - sets.push((set.Id, set.EfficiencyClass)); + // SAFETY: a byte of the union's four, zero where it is reserved. + let rank = unsafe { set.Anonymous2.SchedulingClass }; + sets.push(Set { id: set.Id, class: set.EfficiencyClass, cache: set.LastLevelCacheIndex, rank }); } at += info.Size as usize; } @@ -32,12 +48,44 @@ fn cpu_sets() -> Vec<(u32, u8)> { } /// The sets of the fastest class, if there are slower ones too. -fn fast_of(sets: &[(u32, u8)]) -> Vec<u32> { - let best = sets.iter().map(|c| c.1).max().unwrap_or(0); - let fast: Vec<u32> = sets.iter().filter(|c| c.1 == best).map(|c| c.0).collect(); +fn fast_of(sets: &[Set]) -> Vec<u32> { + let best = sets.iter().map(|c| c.class).max().unwrap_or(0); + let fast: Vec<u32> = sets.iter().filter(|c| c.class == best).map(|c| c.id).collect(); if fast.len() == sets.len() { Vec::new() } else { fast } } +/// Where all cores are of one kind but share more than one last-level +/// cache (a Ryzen 9 9900X: two dies of six cores, 32 MB of L3 each): the +/// sets of one cache, that of the best-ranked core (the system's preferred +/// cores; a tie: the first cache, a Ryzen's first die). Otherwise none. +/// +/// The threads a frame waits for hand their work to each other (the +/// submitting thread, the threads that spread its refreshes, those that +/// land copies, the one that makes the heaps' records): on one die what +/// one wrote is in the cache the next reads; across the two it goes over +/// the link between them, at several times the latency (on Zen 4 and 5 +/// about 70-100 ns against 10-15). The title's own threads are not asked +/// for and keep both dies. +fn one_cache_of(sets: &[Set]) -> Vec<u32> { + let Some(first) = sets.first() else { return Vec::new() }; + if sets.iter().any(|s| s.class != first.class) || sets.iter().all(|s| s.cache == first.cache) { + return Vec::new(); + } + let best = sets.iter().max_by(|a, b| a.rank.cmp(&b.rank).then(b.cache.cmp(&a.cache))).map_or(first.cache, |s| s.cache); + sets.iter().filter(|s| s.cache == best).map(|s| s.id).collect() +} + +/// `VICTORY_ONE_CCD`: on a processor whose cores are alike but in groups +/// around caches of their own, the threads `VICTORY_FAST_CORES` 1 and 2 +/// name (those a frame waits for, and those they share their work with) +/// are kept on one group ([`one_cache_of`]); 0: not (as before). Those of +/// 3 (the many that translate lists) are left to every core either way: +/// with the helpers they would be more threads than one die runs at once. +fn one_ccd() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_ONE_CCD").map_or(true, |v| v.trim() != "0")) +} + /// `VICTORY_FAST_CORES`: 0: no thread asks; 1: the threads a frame waits for /// one by one; 2 (the default): the threads they share their work with too; /// 3: those that work beside the rest as well (lists translated, descriptors @@ -93,21 +141,31 @@ fn ask(what: &str, from: u32) { if stage() < from { return; } - static FAST: std::sync::OnceLock<(Vec<u32>, usize)> = std::sync::OnceLock::new(); - let (fast, of) = FAST.get_or_init(|| { + static FAST: std::sync::OnceLock<(Vec<u32>, Vec<u32>, usize)> = std::sync::OnceLock::new(); + let (fast, one_cache, of) = FAST.get_or_init(|| { let sets = cpu_sets(); - (fast_of(&sets), sets.len()) + (fast_of(&sets), one_cache_of(&sets), sets.len()) }); - // All alike (or nothing known): nothing to ask for. - if fast.is_empty() { + if !fast.is_empty() { + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + if ok == 0 { + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + } else { + tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + } + return; + } + // All alike: on one die of two, if there are two, for the threads a frame waits for. + if one_cache.is_empty() || from > 2 || !one_ccd() { return; } // SAFETY: our own thread and a list of the system's own set ids. - let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), one_cache.as_ptr(), one_cache.len() as u32) }; if ok == 0 { - tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on one die"); } else { - tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + tracing::info!(what, sets = one_cache.len(), of, "the thread is kept on one die, beside its cache (VICTORY_ONE_CCD=0: not)"); } } @@ -163,12 +221,33 @@ impl Priority { mod tests { use super::*; + fn set(id: u32, class: u8, cache: u8, rank: u8) -> Set { + Set { id, class, cache, rank } + } + #[test] fn the_fast_cores_are_those_of_the_best_class_if_there_is_a_worse_one() { - assert_eq!(fast_of(&[(256, 1), (257, 1), (258, 0)]), [256, 257]); - assert!(fast_of(&[(256, 0), (257, 0)]).is_empty()); + assert_eq!(fast_of(&[set(256, 1, 0, 0), set(257, 1, 0, 0), set(258, 0, 0, 0)]), [256, 257]); + assert!(fast_of(&[set(256, 0, 0, 0), set(257, 0, 0, 0)]).is_empty()); assert!(fast_of(&[]).is_empty()); assert!(!cpu_sets().is_empty()); std::thread::spawn(|| keep_on_fast_cores("test")).join().unwrap(); } + + #[test] + fn two_dies_of_alike_cores_keep_one_die() { + // A 9900X: 24 sets, 12 on each die's cache; no ranking given: the first die. + let two: Vec<Set> = (0..24).map(|i| set(256 + i, 0, (i / 12) as u8 * 12, 0)).collect(); + assert_eq!(one_cache_of(&two), (256..268).collect::<Vec<u32>>()); + // The system's preferred cores on the second die: that one. + let mut ranked = two.clone(); + ranked[15].rank = 9; + assert_eq!(one_cache_of(&ranked), (268..280).collect::<Vec<u32>>()); + // One die (a 9800X3D), or two kinds of cores (left to `fast_of`): none. + let one: Vec<Set> = (0..16).map(|i| set(256 + i, 0, 0, 0)).collect(); + assert!(one_cache_of(&one).is_empty()); + let hybrid = [set(256, 1, 0, 0), set(257, 0, 1, 0)]; + assert!(one_cache_of(&hybrid).is_empty()); + assert!(one_cache_of(&[]).is_empty()); + } } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 597ede594..75f4860d1 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1886,7 +1886,7 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { // world makes in its first frame ([`targets_room_kept`]) counts as // used. Some([budget, used, ..]) => { - used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept() + used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept(budget) < room_line(budget) } None => filled < WITHOUT_BUDGET, @@ -1895,7 +1895,8 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { /// The bytes of the card's memory the texture queue leaves free for /// render targets and other host copies the host itself writes that are -/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as +/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (not given: 3,072, or +/// three tenths of a smaller card's `budget`, [`targets_most`]; 0: none, as /// before) less what such copies hold now. /// /// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255 @@ -1921,15 +1922,16 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { /// for targets against a line of 9,527 MB). The reserve comes back when /// the targets grow by 64 MiB again (a new scene's), for as long again. #[cfg(windows)] -pub(crate) fn targets_room_kept() -> u64 { +pub(crate) fn targets_room_kept(budget: u64) -> u64 { use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; - static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); - let most = *MOST.get_or_init(|| { + static ASKED: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); + let asked = *ASKED.get_or_init(|| { std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB") .ok() .and_then(|v| v.trim().parse::<u64>().ok()) - .map_or(3072 << 20, |mb| mb.min(8192) << 20) + .map(|mb| mb.min(8192) << 20) }); + let most = targets_most(asked, budget); static SETTLE: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); let settle = *SETTLE.get_or_init(|| { std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS") @@ -1950,6 +1952,29 @@ pub(crate) fn targets_room_kept() -> u64 { targets_kept(most, targets, now.saturating_sub(since), settle) } +/// The most [`targets_room_kept`] keeps: `asked` (`VICTORY_CARD_ROOM_FOR_TARGETS_MB`) +/// if given, else 3,072 MiB, but no more than three tenths of the card's +/// `budget` (0: not known, the 3,072). +/// +/// The 3,072 were measured on 12 GB cards at 1440p (budgets of 10.2 to +/// 10.6 GB, where three tenths are more than that, so nothing changes +/// there). On an 8 GB card (RTX 3060 Ti, 3070, 3070 Ti: budgets of 4.9 to +/// 7.3 GB, docs/windows-memory.md) a flat 3,072 kept 40 to 60 % of the +/// budget from the texture queue: the scene stayed black with the queue +/// "waiting for room", and a reserve of 1,536 MB brought it back. Three +/// tenths give 1,470 MB of a 4.9 GB budget and 2,190 MB of 7.3 GB, which +/// still holds the targets of the Series S profile (1080p out) and most of +/// 1440p's first frame; past it the targets only take room as they come. +#[cfg(any(windows, test))] +fn targets_most(asked: Option<u64>, budget: u64) -> u64 { + const MOST: u64 = 3072 << 20; + match asked { + Some(asked) => asked, + None if budget == 0 => MOST, + None => MOST.min(budget / 10 * 3), + } +} + /// [`targets_room_kept`]'s record of the targets' bytes (`last`) and of /// when they last grew by 64 MiB (`since`, ms), with `targets` now: a fall /// of 64 MiB lowers the record (so that growing back counts as growth), a @@ -1995,7 +2020,7 @@ pub(crate) fn room_terms(memory: Option<[u64; 4]>) -> Option<[u64; 6]> { used, crate::pool::texture_room(), crate::shadow::card_room_kept(), - targets_room_kept(), + targets_room_kept(budget), room_line(budget), ] .map(|bytes| bytes >> 20), @@ -2332,7 +2357,7 @@ pub(crate) fn let_go_idle() { Some([budget, used, ..]) if keep => { let used = used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() - + targets_room_kept(); + + targets_room_kept(budget); crate::host::vram_keep_below(budget, used, room_line(budget)) } _ => (crate::host::vram_idle_ms(memory), u64::MAX), @@ -5227,6 +5252,19 @@ float4 lit() : SV_Target { return 1.0; } // `VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS=0`: kept as before. assert_eq!(targets_kept(most, 2432 * MIB, 600_000, 0), 640 * MIB); + // The most kept: 3,072 MiB on big cards, three tenths of an 8 GB + // card's budget, and what the switch says whatever the card. + const GIB: u64 = 1 << 30; + assert_eq!(targets_most(None, 0), most); + assert_eq!(targets_most(None, 10_600 * MIB), most); + assert_eq!(targets_most(None, 15 * GIB), most); + assert_eq!(targets_most(None, 7_256 * MIB), 7_256 * MIB / 10 * 3); + assert!((2_100 * MIB..2_200 * MIB).contains(&targets_most(None, 7_256 * MIB))); + assert!((1_450 * MIB..1_500 * MIB).contains(&targets_most(None, 4_923 * MIB))); + assert_eq!(targets_most(Some(1536 * MIB), 7 * GIB), 1536 * MIB); + assert_eq!(targets_most(Some(0), 7 * GIB), 0); + assert_eq!(targets_most(Some(3072 * MIB), 5 * GIB), most); + // Growth of 64 MiB restarts the clock; less does not. assert_eq!(targets_seen(2000 * MIB, 1_000, 2050 * MIB, 9_000), (2000 * MIB, 1_000)); assert_eq!(targets_seen(2000 * MIB, 1_000, 2064 * MIB, 9_000), (2064 * MIB, 9_000)); diff --git a/docs/ryzen-9900x-rtx-3070ti.md b/docs/ryzen-9900x-rtx-3070ti.md new file mode 100644 index 000000000..ba949c03a --- /dev/null +++ b/docs/ryzen-9900x-rtx-3070ti.md @@ -0,0 +1,67 @@ +# Ryzen 9 9900X, RTX 3070 Ti 8 GB, 32 GB DDR5 + +What the layer does for this kind of PC on its own, and the settings to +start from. Not measured on this exact PC yet: compare with a log of each run +(F3 shows frame rate, VRAM and RAM) and report what you find. + +## What the code does by itself + +- **The layer's frame threads stay on one die of the 9900X.** Its twelve + cores sit on two dies (CCDs) of six, each with its own 32 MB L3. The + threads a frame waits for hand their work to each other; across the two + dies every hand-over goes over the link between them, at several times the + latency. They are now kept on the die of the system's preferred cores + (`crates/victory-gpu/src/cores.rs`, `one_cache_of`). The title's own + threads and the list translators keep both dies. `VICTORY_ONE_CCD=0` + turns it off, to compare. Single-die Ryzens (9700X, 9800X3D) and Intel's + hybrid cores are not affected. +- **8 GB cards keep less room for render targets.** The texture queue held + back a flat 3,072 MB for render targets not made yet, measured on 12 GB + cards. On an 8 GB card that is 40-60 % of the budget, and the picture + stayed black while textures waited for room (docs/windows-memory.md). It + is now at most three tenths of the budget (about 2.1 GB of a 7.2 GB + budget); 12 GB cards and up are unchanged. + `VICTORY_CARD_ROOM_FOR_TARGETS_MB=<n>` still sets it by hand. +- **32 GB of RAM counts as limited**, so 8 pipeline workers at most and + smaller idle caches (already so before). + +## Settings to start from + +| | | +|---|---| +| Console profile | **Series S** (F1, CONSOLE). Series X at 1440p needs more than 8 GB of VRAM for its targets and textures together | +| DLSS | **Quality** (720p inside, 1080p out); Performance (540p) if the GPU is the limit | +| Frame generation | **FSR 3, 2x** (DLSS frame generation needs an RTX 40). It takes 1.5-2 GB of VRAM: off if textures come late or the F3 panel shows VRAM over the budget | +| Frame rate cap | 60, or your monitor's rate with frame generation | +| Build | `-Build native` (below) | + +```powershell +.\scripts\play-nvidia.ps1 -Exe 'D:\Games\MyDump\game_scarlett_master.exe' -SeriesS -Dlss quality -Build native +``` + +`victory.exe` alone: `victory.exe play --series-s --dlss quality --fps 60`. + +## A build for this CPU + +`-Build native` builds `target\native\victory.exe` with the CPU's own +instructions (`-C target-cpu=native`: AVX-512 on Zen 5) and one optimisation +over the whole program (`[profile.native]` in `Cargo.toml`: fat LTO, one code +generation unit). It takes several minutes more to build and runs only on a +CPU with the same instructions. It helps the CPU side (shader translation, +hashing, copies), not the GPU. By hand: + +```powershell +$env:RUSTFLAGS = '-C target-cpu=native'; cargo build --locked --profile native -p victory +``` + +## Windows + +- **A page file**, managed by Windows. With 32 GB of RAM and none, the first + scene load ran out of commit (docs/windows-memory.md). +- **AMD chipset driver** installed: it tells Windows which cores are + preferred, and so which die the layer's threads keep. +- **Resizable BAR** on in the BIOS (an RTX 30 supports it) and + **hardware-accelerated GPU scheduling** on (needed for frame generation). +- **EXPO** on for the DDR5, so it runs at its rated speed. +- Close programs that hold VRAM (browsers with video, overlays): every MB of + the 8 GB counts. diff --git a/scripts/play-foxhound.ps1 b/scripts/play-foxhound.ps1 index 2d3ed3e64..23232f6a2 100644 --- a/scripts/play-foxhound.ps1 +++ b/scripts/play-foxhound.ps1 @@ -6,6 +6,8 @@ # .\scripts\play-foxhound.ps1 -Exe ... -Dlss balanced -FrameGen # .\scripts\play-foxhound.ps1 -Exe ... -SeriesS Series S profile (1280x720 inside, faster, softer) # .\scripts\play-foxhound.ps1 -Exe ... -Build diag diagnostics build (slower; captures, timelines) +# .\scripts\play-foxhound.ps1 -Exe ... -Build native built for this PC's own CPU (AVX-512 on a Ryzen 9000), +# whole-program optimised; runs only on such a CPU # .\scripts\play-foxhound.ps1 -Exe ... -More @{VICTORY_AMBIENT_SPECULAR='0'} add or override switches # # In the game, F1 opens a settings menu (arrow keys pick and change, Enter does it). What it saves goes to @@ -16,7 +18,7 @@ # %LOCALAPPDATA%\victory\logs. Every VICTORY_... switch is described in a comment where the code reads it. param( [Parameter(Mandatory)][string]$Exe, - [ValidateSet('diag', 'release')][string]$Build = 'release', + [ValidateSet('diag', 'release', 'native')][string]$Build = 'release', [switch]$SeriesS, # 1440: output and scene 2560x1440 (Series X, the image is patched); 1080to1440: scene 1920x1080 upscaled by # the title; 4k: the stock Series X output (3840x2160). @@ -165,6 +167,12 @@ if (-not (Test-Path $victory)) { Push-Location $repo try { if ($Build -eq 'diag') { cargo build --locked --profile diag -p victory --features diagnostics } + elseif ($Build -eq 'native') { + # This CPU's own instructions (Zen 5: AVX-512) and one optimisation over the whole program. + $rustflags = $env:RUSTFLAGS + $env:RUSTFLAGS = (@($rustflags, '-C target-cpu=native') | Where-Object { $_ }) -join ' ' + try { cargo build --locked --profile native -p victory } finally { $env:RUSTFLAGS = $rustflags } + } else { cargo build --release --locked -p victory } } finally { Pop-Location } if (-not (Test-Path $victory)) { Write-Host "The build did not make $victory."; return } From 271ff7d9e4701413590d2fd3ff72a070dd36855d Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 05:40:53 +0000 Subject: [PATCH 14/57] Render target reserve settles once targets hold 1 GiB (Series S never reached half of 3,072) On an RTX 3070 Ti, Series S, five minutes in the world: targets levelled off at about 1,420 MB, under half of the 3,072 MB reserve, so 1,650 MB stayed kept for the whole run while about 2,000 textures waited for room. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/resource.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 75f4860d1..d10bde7fd 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1992,11 +1992,18 @@ fn targets_seen(last: u64, since: u64, targets: u64, now: u64) -> (u64, u64) { } /// What [`targets_room_kept`] keeps of `most`: what the targets do not -/// hold yet, or nothing once they hold half of it or more and have not -/// grown for `settle` ms (`still_ms`; `settle` 0: always kept). +/// hold yet, or nothing once they hold half of it, or 1 GiB, or more and +/// have not grown for `settle` ms (`still_ms`; `settle` 0: always kept). +/// +/// (Half alone was never reached on the Series S profile: its world's +/// targets level off at about 1,420 MB, under half of 3,072, so 1,650 MB +/// stayed kept for the whole run while 2,000 textures waited "no room" +/// (RTX 3070 Ti, 2026-11-28, five minutes in the world). Before the world +/// they are some 650 MB, under either.) #[cfg(any(windows, test))] fn targets_kept(most: u64, targets: u64, still_ms: u64, settle: u64) -> u64 { - if settle > 0 && targets >= most / 2 && still_ms >= settle { + const ENOUGH: u64 = 1 << 30; + if settle > 0 && targets >= (most / 2).min(ENOUGH) && still_ms >= settle { 0 } else { most.saturating_sub(targets) @@ -5251,6 +5258,11 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(targets_kept(most, 2432 * MIB, 20_000, 20_000), 0); // `VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS=0`: kept as before. assert_eq!(targets_kept(most, 2432 * MIB, 600_000, 0), 640 * MIB); + // Series S: its world's targets level off at 1,420 MB, under half + // the most, and still settle (1 GiB is enough); a menu's do not. + assert_eq!(targets_kept(most, 1420 * MIB, 20_000, 20_000), 0); + assert_eq!(targets_kept(most, 1420 * MIB, 5_000, 20_000), 1652 * MIB); + assert_eq!(targets_kept(most, 652 * MIB, 600_000, 20_000), 2420 * MIB); // The most kept: 3,072 MiB on big cards, three tenths of an 8 GB // card's budget, and what the switch says whatever the card. From eb439f92c7dda6bcfd41d3f839fb65afba114012 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 07:01:39 +0000 Subject: [PATCH 15/57] TEMPORARY: diagnostics build by default, for one measurement of the card's time by command VILauncher only builds the plain release; this lets it measure with VICTORY_GPU_TIMING=1 and VICTORY_D3D12_DRED=1. To be reverted after it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- apps/victory/Cargo.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index efaa1091e..515adfd04 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -22,6 +22,11 @@ clap.workspace = true walkdir.workspace = true [features] +# TEMPORARY (2026-11-28): the diagnostics build by default, so that a launcher +# that only builds the plain release (VILauncher) can measure the card's time +# by command (VICTORY_GPU_TIMING=1 with VICTORY_D3D12_DRED=1). To be taken out +# again after that one measurement. +default = ["diagnostics"] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diagnostics = [ From 28483ba40326ec6c92de24f66ffb79da6e41c0dd Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 07:14:36 +0000 Subject: [PATCH 16/57] Revert the temporary diagnostics build by default Back to the plain release build after the measurement of the card's time by command (2026-11-28). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- apps/victory/Cargo.toml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index 515adfd04..efaa1091e 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -22,11 +22,6 @@ clap.workspace = true walkdir.workspace = true [features] -# TEMPORARY (2026-11-28): the diagnostics build by default, so that a launcher -# that only builds the plain release (VILauncher) can measure the card's time -# by command (VICTORY_GPU_TIMING=1 with VICTORY_D3D12_DRED=1). To be taken out -# again after that one measurement. -default = ["diagnostics"] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diagnostics = [ From 4e91f84865792f5acc82c5f606704e2eb1c9db03 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 07:22:24 +0000 Subject: [PATCH 17/57] Barrier groups that order no write left without a wait (VICTORY_SELECTIVE_BARRIERS=1, off by default) Every title barrier group became a wait for every earlier shader write: about 750 a frame on an RTX 3070 Ti, whose timing run showed 9,000 commands of 4 microseconds on average with the card at 100 % of its time and half its power. With the switch, a group is read as D3D12's barrier groups and left without the wait when every barrier goes from reads to reads or has nothing before; anything else, or anything that does not look like that layout, keeps it. The log counts both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/list.rs | 150 +++++++++++++++++++++++++++- crates/victory-gpu/src/list/thin.rs | 5 +- 2 files changed, 152 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index d2baec252..338072bfa 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -2260,12 +2260,106 @@ extern "system" fn wait_value64(this: This, address: u64, comparison: u32, refer wait_for(this, address, comparison, reference, true); } +/// Whether a title's barrier groups that order no write are left without +/// the wait for every earlier shader write ([`groups_need_wait`]; +/// `VICTORY_SELECTIVE_BARRIERS=1`; off by default). +/// +/// Every barrier group of the title became one such wait: about 750 a frame +/// in the first gameplay area on an RTX 3070 Ti (2026-11-28, timing run: +/// 9,000 commands of 4 microseconds each on average, the card at 100 % of +/// its time and half of its power). A group whose barriers all go from +/// reads to reads, or from no access, orders nothing a wait would. +pub(crate) fn selective_barriers() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_SELECTIVE_BARRIERS").is_some_and(|v| v == "1"); + if on { + tracing::info!("barrier groups that order no write are left without a wait (VICTORY_SELECTIVE_BARRIERS=1)"); + } + on + }) +} + +/// The title's barrier groups seen with [`selective_barriers`] on, and of +/// those left without a wait. +static SELECTIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether the barrier groups `(count, groups)` of the title (the layout of +/// `D3D12_BARRIER_GROUP`: type, barrier count, pointer to the barriers, +/// each of which starts with its sync and access before and after) need a +/// wait for earlier shader writes: yes unless every barrier in them has +/// nothing to wait for (sync before none, or access before none) or goes +/// from reads to reads (neither access common, which is any). Anything +/// that does not look like that layout needs the wait. +pub(crate) fn groups_need_wait(count: u32, groups: *const u8) -> bool { + let need = groups_need_wait_in(count, groups); + let seen = SELECTIVE[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let left = SELECTIVE[1].fetch_add(u64::from(!need), std::sync::atomic::Ordering::Relaxed) + u64::from(!need); + if seen.is_power_of_two() || seen.is_multiple_of(100_000) { + tracing::info!(seen, left, "the title's barrier groups, and of those left without a wait (VICTORY_SELECTIVE_BARRIERS)"); + } + need +} + +fn groups_need_wait_in(count: u32, groups: *const u8) -> bool { + const GROUP: usize = 16; + if groups.is_null() || count == 0 || count > 64 || !(groups as usize).is_multiple_of(8) { + return true; + } + for g in 0..count as usize { + // SAFETY: the title's array of `count` groups, 16 bytes each. + let (kind, n, barriers) = unsafe { + let at = groups.add(g * GROUP); + (at.cast::<u32>().read(), at.add(4).cast::<u32>().read(), at.add(8).cast::<*const u8>().read()) + }; + let stride = match kind { + 0 => 16, // global + 1 => 64, // texture + 2 => 40, // buffer + _ => return true, + }; + if n == 0 { + continue; + } + if n > 4096 || barriers.is_null() || !(barriers as usize).is_multiple_of(8) { + return true; + } + for b in 0..n as usize { + // SAFETY: the group's array of `n` barriers of `stride` bytes, + // each starting with four 32-bit words. + let [sync_before, _, before, after] = + unsafe { barriers.add(b * stride).cast::<[u32; 4]>().read_unaligned() }; + if barrier_needs_wait(sync_before, before, after) { + return true; + } + } + } + false +} + +/// One barrier's sync before and access before and after: whether it needs +/// the wait for earlier writes ([`groups_need_wait`]). +fn barrier_needs_wait(sync_before: u32, before: u32, after: u32) -> bool { + const COMMON: u32 = 0; + const NO_ACCESS: u32 = 0x8000_0000; + // Render target, unordered access, depth write, stream output, copy and + // resolve destinations, acceleration structure, video writes. + const WRITES: u32 = 0x8 | 0x10 | 0x20 | 0x100 | 0x400 | 0x1000 | 0x8000 | 0x40000 | 0x100000 | 0x400000; + if sync_before == 0 || before == NO_ACCESS { + return false; + } + let reads = |access: u32| access != COMMON && (access == NO_ACCESS || access & WRITES == 0); + !(reads(before) && reads(after)) +} + /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a /// title texture (clears, copies) moves its host copy to the state it needs /// 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) { +/// write (the title's buffer barriers order compute passes). With +/// [`selective_barriers`], none for groups that order no write. +extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { + let count = if !groups.is_null() && selective_barriers() && !groups_need_wait(count, groups) { 0 } else { count }; // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`. #[cfg(all(windows, feature = "diagnostics"))] if count > 0 { @@ -2588,3 +2682,55 @@ mod tests { } } } + +#[cfg(test)] +mod selective_barrier_tests { + use super::{barrier_needs_wait, groups_need_wait_in}; + + const SRV: u32 = 0x80; + const UAV: u32 = 0x10; + const RT: u32 = 0x8; + const NO_ACCESS: u32 = 0x8000_0000; + const ALL: u32 = 1; + + #[test] + fn only_barriers_that_order_no_write_go_without_a_wait() { + // Reads to reads, or nothing before: no wait. + assert!(!barrier_needs_wait(ALL, SRV, SRV | 0x2)); + assert!(!barrier_needs_wait(ALL, NO_ACCESS, UAV)); + assert!(!barrier_needs_wait(0, NO_ACCESS, RT)); + // A write before or after, or common (any access): the wait. + assert!(barrier_needs_wait(ALL, UAV, SRV)); + assert!(barrier_needs_wait(ALL, SRV, UAV)); + assert!(barrier_needs_wait(ALL, RT, SRV)); + assert!(barrier_needs_wait(ALL, 0, SRV)); + assert!(barrier_needs_wait(ALL, SRV, 0)); + } + + #[test] + fn groups_are_read_as_the_d3d12_layout_and_anything_else_waits() { + // One buffer group of two barriers (40 bytes each), one texture group (64). + let mut buffers = [0u64; 10]; + let words = |b: &mut [u64], at: usize, w: [u32; 4]| { + b[at] = u64::from(w[0]) | u64::from(w[1]) << 32; + b[at + 1] = u64::from(w[2]) | u64::from(w[3]) << 32; + }; + words(&mut buffers, 0, [ALL, ALL, SRV, SRV]); + words(&mut buffers, 5, [ALL, ALL, NO_ACCESS, UAV]); + let mut textures = [0u64; 8]; + words(&mut textures, 0, [ALL, ALL, SRV, 0x40]); + let group = |kind: u32, n: u32, at: *const u64| [u64::from(kind) | u64::from(n) << 32, at as u64]; + let [a, b] = group(2, 2, buffers.as_ptr()); + let [c, d] = group(1, 1, textures.as_ptr()); + let groups = [a, b, c, d]; + assert!(!groups_need_wait_in(2, groups.as_ptr().cast())); + // A write in one barrier: the wait. + words(&mut textures, 0, [ALL, ALL, UAV, SRV]); + assert!(groups_need_wait_in(2, groups.as_ptr().cast())); + // An unknown group type, a null pointer, no groups: the wait. + let odd = [u64::from(7u32) | 1 << 32, buffers.as_ptr() as u64]; + assert!(groups_need_wait_in(1, odd.as_ptr().cast())); + assert!(groups_need_wait_in(1, std::ptr::null())); + assert!(groups_need_wait_in(0, groups.as_ptr().cast())); + } +} diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index eb7e115c2..a5f451f21 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -563,7 +563,10 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> } 0 } -extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { +extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { + // Read here, on the title's thread, while its groups are there: only + // whether a wait is needed goes on (`super::selective_barriers`). + let count = if !groups.is_null() && super::selective_barriers() && !super::groups_need_wait(count, groups) { 0 } else { count }; front(this).put(BARRIER_GROUPS, &[u64::from(count)]); } extern "system" fn viewports(this: This, count: u32, items: *const D3D12_VIEWPORT) { From 02e2345effa07b20e12b91a9c2c8b7b1b5407283 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 07:34:24 +0000 Subject: [PATCH 18/57] Revert selective barrier groups (VICTORY_SELECTIVE_BARRIERS) Measured on an RTX 3070 Ti: only about 4 % of the title's barrier groups order no write (5,186 of 131,072), and with those left without a wait the title stopped submitting for most of each frame (3.5 fps, the card idle 85 % of the time, frames of 280-500 ms). The waits stay as they were. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/list.rs | 150 +--------------------------- crates/victory-gpu/src/list/thin.rs | 5 +- 2 files changed, 3 insertions(+), 152 deletions(-) diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 338072bfa..d2baec252 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -2260,106 +2260,12 @@ extern "system" fn wait_value64(this: This, address: u64, comparison: u32, refer wait_for(this, address, comparison, reference, true); } -/// Whether a title's barrier groups that order no write are left without -/// the wait for every earlier shader write ([`groups_need_wait`]; -/// `VICTORY_SELECTIVE_BARRIERS=1`; off by default). -/// -/// Every barrier group of the title became one such wait: about 750 a frame -/// in the first gameplay area on an RTX 3070 Ti (2026-11-28, timing run: -/// 9,000 commands of 4 microseconds each on average, the card at 100 % of -/// its time and half of its power). A group whose barriers all go from -/// reads to reads, or from no access, orders nothing a wait would. -pub(crate) fn selective_barriers() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - let on = std::env::var_os("VICTORY_SELECTIVE_BARRIERS").is_some_and(|v| v == "1"); - if on { - tracing::info!("barrier groups that order no write are left without a wait (VICTORY_SELECTIVE_BARRIERS=1)"); - } - on - }) -} - -/// The title's barrier groups seen with [`selective_barriers`] on, and of -/// those left without a wait. -static SELECTIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; - -/// Whether the barrier groups `(count, groups)` of the title (the layout of -/// `D3D12_BARRIER_GROUP`: type, barrier count, pointer to the barriers, -/// each of which starts with its sync and access before and after) need a -/// wait for earlier shader writes: yes unless every barrier in them has -/// nothing to wait for (sync before none, or access before none) or goes -/// from reads to reads (neither access common, which is any). Anything -/// that does not look like that layout needs the wait. -pub(crate) fn groups_need_wait(count: u32, groups: *const u8) -> bool { - let need = groups_need_wait_in(count, groups); - let seen = SELECTIVE[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; - let left = SELECTIVE[1].fetch_add(u64::from(!need), std::sync::atomic::Ordering::Relaxed) + u64::from(!need); - if seen.is_power_of_two() || seen.is_multiple_of(100_000) { - tracing::info!(seen, left, "the title's barrier groups, and of those left without a wait (VICTORY_SELECTIVE_BARRIERS)"); - } - need -} - -fn groups_need_wait_in(count: u32, groups: *const u8) -> bool { - const GROUP: usize = 16; - if groups.is_null() || count == 0 || count > 64 || !(groups as usize).is_multiple_of(8) { - return true; - } - for g in 0..count as usize { - // SAFETY: the title's array of `count` groups, 16 bytes each. - let (kind, n, barriers) = unsafe { - let at = groups.add(g * GROUP); - (at.cast::<u32>().read(), at.add(4).cast::<u32>().read(), at.add(8).cast::<*const u8>().read()) - }; - let stride = match kind { - 0 => 16, // global - 1 => 64, // texture - 2 => 40, // buffer - _ => return true, - }; - if n == 0 { - continue; - } - if n > 4096 || barriers.is_null() || !(barriers as usize).is_multiple_of(8) { - return true; - } - for b in 0..n as usize { - // SAFETY: the group's array of `n` barriers of `stride` bytes, - // each starting with four 32-bit words. - let [sync_before, _, before, after] = - unsafe { barriers.add(b * stride).cast::<[u32; 4]>().read_unaligned() }; - if barrier_needs_wait(sync_before, before, after) { - return true; - } - } - } - false -} - -/// One barrier's sync before and access before and after: whether it needs -/// the wait for earlier writes ([`groups_need_wait`]). -fn barrier_needs_wait(sync_before: u32, before: u32, after: u32) -> bool { - const COMMON: u32 = 0; - const NO_ACCESS: u32 = 0x8000_0000; - // Render target, unordered access, depth write, stream output, copy and - // resolve destinations, acceleration structure, video writes. - const WRITES: u32 = 0x8 | 0x10 | 0x20 | 0x100 | 0x400 | 0x1000 | 0x8000 | 0x40000 | 0x100000 | 0x400000; - if sync_before == 0 || before == NO_ACCESS { - return false; - } - let reads = |access: u32| access != COMMON && (access == NO_ACCESS || access & WRITES == 0); - !(reads(before) && reads(after)) -} - /// The enhanced barriers `(group count, groups)`: buffer, texture and /// global barriers with layouts instead of states. Every host use of a /// title texture (clears, copies) moves its host copy to the state it needs /// first, so only their ordering matters: one barrier on every shader -/// write (the title's buffer barriers order compute passes). With -/// [`selective_barriers`], none for groups that order no write. -extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { - let count = if !groups.is_null() && selective_barriers() && !groups_need_wait(count, groups) { 0 } else { count }; +/// 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 { @@ -2682,55 +2588,3 @@ mod tests { } } } - -#[cfg(test)] -mod selective_barrier_tests { - use super::{barrier_needs_wait, groups_need_wait_in}; - - const SRV: u32 = 0x80; - const UAV: u32 = 0x10; - const RT: u32 = 0x8; - const NO_ACCESS: u32 = 0x8000_0000; - const ALL: u32 = 1; - - #[test] - fn only_barriers_that_order_no_write_go_without_a_wait() { - // Reads to reads, or nothing before: no wait. - assert!(!barrier_needs_wait(ALL, SRV, SRV | 0x2)); - assert!(!barrier_needs_wait(ALL, NO_ACCESS, UAV)); - assert!(!barrier_needs_wait(0, NO_ACCESS, RT)); - // A write before or after, or common (any access): the wait. - assert!(barrier_needs_wait(ALL, UAV, SRV)); - assert!(barrier_needs_wait(ALL, SRV, UAV)); - assert!(barrier_needs_wait(ALL, RT, SRV)); - assert!(barrier_needs_wait(ALL, 0, SRV)); - assert!(barrier_needs_wait(ALL, SRV, 0)); - } - - #[test] - fn groups_are_read_as_the_d3d12_layout_and_anything_else_waits() { - // One buffer group of two barriers (40 bytes each), one texture group (64). - let mut buffers = [0u64; 10]; - let words = |b: &mut [u64], at: usize, w: [u32; 4]| { - b[at] = u64::from(w[0]) | u64::from(w[1]) << 32; - b[at + 1] = u64::from(w[2]) | u64::from(w[3]) << 32; - }; - words(&mut buffers, 0, [ALL, ALL, SRV, SRV]); - words(&mut buffers, 5, [ALL, ALL, NO_ACCESS, UAV]); - let mut textures = [0u64; 8]; - words(&mut textures, 0, [ALL, ALL, SRV, 0x40]); - let group = |kind: u32, n: u32, at: *const u64| [u64::from(kind) | u64::from(n) << 32, at as u64]; - let [a, b] = group(2, 2, buffers.as_ptr()); - let [c, d] = group(1, 1, textures.as_ptr()); - let groups = [a, b, c, d]; - assert!(!groups_need_wait_in(2, groups.as_ptr().cast())); - // A write in one barrier: the wait. - words(&mut textures, 0, [ALL, ALL, UAV, SRV]); - assert!(groups_need_wait_in(2, groups.as_ptr().cast())); - // An unknown group type, a null pointer, no groups: the wait. - let odd = [u64::from(7u32) | 1 << 32, buffers.as_ptr() as u64]; - assert!(groups_need_wait_in(1, odd.as_ptr().cast())); - assert!(groups_need_wait_in(1, std::ptr::null())); - assert!(groups_need_wait_in(0, groups.as_ptr().cast())); - } -} diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index a5f451f21..eb7e115c2 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -563,10 +563,7 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> } 0 } -extern "system" fn barrier_groups(this: This, count: u32, groups: *const u8) { - // Read here, on the title's thread, while its groups are there: only - // whether a wait is needed goes on (`super::selective_barriers`). - let count = if !groups.is_null() && super::selective_barriers() && !super::groups_need_wait(count, groups) { 0 } else { count }; +extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { front(this).put(BARRIER_GROUPS, &[u64::from(count)]); } extern "system" fn viewports(this: This, count: u32, items: *const D3D12_VIEWPORT) { From 59330bdbf432c507e69b0e9d48709ebe03dfeafc Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 07:39:32 +0000 Subject: [PATCH 19/57] No wait after the clamp of one indirect command (VICTORY_INDIRECT_ONE_WAIT=1, off by default) The scratch buffer's move to indirect arguments already orders the clamp's writes before the execution reads them; the budget only clamps change, atomically. 169 commands a frame were clamped between two waits for every earlier shader write on an RTX 3070 Ti (timing run). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/indirect.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 2f1beef00..bbc10ab1a 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -532,6 +532,9 @@ fn record_clamp_as( ), ]; let skip = usize::from(!waits); + // `VICTORY_INDIRECT_ONE_WAIT=1`: the wait after the clamp is left out + // ([`one_wait`]); the move of `dst` to indirect arguments stays. + let after = if one_wait() { 1 } else { skip }; unsafe { // Earlier shader writes (the title's argument and count passes) first. l.ResourceBarrier(&first[skip..]); @@ -545,11 +548,33 @@ fn record_clamp_as( l.SetComputeRootUnorderedAccessView(4, budget); l.Dispatch(records.div_ceil(64), 1, 1); } - l.ResourceBarrier(&second[skip..]); + l.ResourceBarrier(&second[after..]); } true } +/// Whether the clamp of one indirect command is followed by its move of +/// the scratch buffer to indirect arguments alone, without a wait for every +/// earlier shader write (`VICTORY_INDIRECT_ONE_WAIT=1`; off by default). +/// +/// What the clamp writes is the scratch buffer, whose move out of unordered +/// access already has the card finish those writes before the execution +/// reads them, and the list's budget, which only clamps change, each with +/// atomic adds. The wait before the clamp (the title's argument passes +/// first) stays. On an RTX 3070 Ti 169 commands a frame were clamped this +/// way, each between two such waits (2026-11-28, timing run), in frames of +/// 9,000 commands where the card ran at half its power. +fn one_wait() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_INDIRECT_ONE_WAIT").is_some_and(|v| v == "1"); + if on { + tracing::info!("indirect commands clamped one at a time: no wait after the clamp (VICTORY_INDIRECT_ONE_WAIT=1)"); + } + on + }) +} + /// The batched clamp's pipeline ([`batch`]). fn batch_clamp() -> Option<&'static Clamp> { static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new(); From 08b5ed52030b0385d63a497e30651f6bd8ec4294 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 08:05:02 +0000 Subject: [PATCH 20/57] Log the build's commit and the VICTORY_ switches at the start of a run A launcher that builds and starts the layer by itself showed neither, and a switch that never reached the layer looked like one that changed nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- apps/victory/build.rs | 16 ++++++++++++++++ apps/victory/src/run.rs | 10 ++++++++++ crates/victory-hle/src/lib.rs | 6 ++++++ 3 files changed, 32 insertions(+) diff --git a/apps/victory/build.rs b/apps/victory/build.rs index 1fe647dd4..4c443dffe 100644 --- a/apps/victory/build.rs +++ b/apps/victory/build.rs @@ -8,6 +8,22 @@ //! the `D3D12` folder (or Windows' own, without one) came too late and every //! start asked for 614. Loaded on its first use instead, it reads that version. fn main() { + // The commit this build is of, for the log's first lines (a launcher that + // builds the repository by itself says nothing of which one it built). + let commit = std::process::Command::new("git") + .args(["rev-parse", "--short=10", "HEAD"]) + .output() + .ok() + .filter(|o| o.status.success()) + .and_then(|o| String::from_utf8(o.stdout).ok()) + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "unknown".to_owned()); + println!("cargo:rustc-env=VICTORY_COMMIT={commit}"); + for git in ["../../.git/HEAD", "../../.git/refs/heads", "../../.git/packed-refs"] { + println!("cargo:rerun-if-changed={git}"); + } + println!("cargo:rerun-if-changed=build.rs"); if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { println!("cargo:rustc-link-arg-bins=/EXPORT:D3D12SDKVersion,DATA"); println!("cargo:rustc-link-arg-bins=/EXPORT:D3D12SDKPath,DATA"); diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index b27a6953a..0601a62d9 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -117,6 +117,16 @@ pub fn run( if execute { check_cpu_features()?; } + // Which build, and with which switches: a launcher that builds and starts + // the layer by itself (VILauncher) shows neither, and a switch that never + // reached the layer looked like one that changed nothing. + let mut switches: Vec<String> = std::env::vars() + .filter(|(k, _)| k.starts_with("VICTORY_")) + .map(|(k, v)| format!("{k}={v}")) + .collect(); + switches.sort(); + println!("build commit {}", env!("VICTORY_COMMIT")); + victory_hle::log_build(env!("VICTORY_COMMIT"), &switches.join(" ")); // A title that relaunched itself: the old process must be gone first. victory_hle::modules::lifecycle::wait_for_previous(); let cfg = victory_core::Config::load()?; diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index acd059294..c00d5363d 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -163,3 +163,9 @@ mod tests { assert_eq!(r.classify("rpcrt4.dll", &name("RpcServerRegisterIf")), None); } } + +/// The log's line of which build this is and with which switches +/// (`victory run` says it first thing). +pub fn log_build(commit: &str, switches: &str) { + tracing::info!(commit, switches, "victory build and switches"); +} From f304112be1a18c61b167704aff0c5cf801cafb71 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 08:14:32 +0000 Subject: [PATCH 21/57] Revert VICTORY_INDIRECT_ONE_WAIT In the release build with the play settings no indirect command is clamped one at a time (the switch's line never came in a run that had it on, 2026-11-28): the wait it left out is not on the frame's path there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/indirect.rs | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index bbc10ab1a..2f1beef00 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -532,9 +532,6 @@ fn record_clamp_as( ), ]; let skip = usize::from(!waits); - // `VICTORY_INDIRECT_ONE_WAIT=1`: the wait after the clamp is left out - // ([`one_wait`]); the move of `dst` to indirect arguments stays. - let after = if one_wait() { 1 } else { skip }; unsafe { // Earlier shader writes (the title's argument and count passes) first. l.ResourceBarrier(&first[skip..]); @@ -548,33 +545,11 @@ fn record_clamp_as( l.SetComputeRootUnorderedAccessView(4, budget); l.Dispatch(records.div_ceil(64), 1, 1); } - l.ResourceBarrier(&second[after..]); + l.ResourceBarrier(&second[skip..]); } true } -/// Whether the clamp of one indirect command is followed by its move of -/// the scratch buffer to indirect arguments alone, without a wait for every -/// earlier shader write (`VICTORY_INDIRECT_ONE_WAIT=1`; off by default). -/// -/// What the clamp writes is the scratch buffer, whose move out of unordered -/// access already has the card finish those writes before the execution -/// reads them, and the list's budget, which only clamps change, each with -/// atomic adds. The wait before the clamp (the title's argument passes -/// first) stays. On an RTX 3070 Ti 169 commands a frame were clamped this -/// way, each between two such waits (2026-11-28, timing run), in frames of -/// 9,000 commands where the card ran at half its power. -fn one_wait() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - let on = std::env::var_os("VICTORY_INDIRECT_ONE_WAIT").is_some_and(|v| v == "1"); - if on { - tracing::info!("indirect commands clamped one at a time: no wait after the clamp (VICTORY_INDIRECT_ONE_WAIT=1)"); - } - on - }) -} - /// The batched clamp's pipeline ([`batch`]). fn batch_clamp() -> Option<&'static Clamp> { static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new(); From 8afdf42af4877ca7289129162b55f3ce83e4cc9d Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 21:44:15 -0500 Subject: [PATCH 22/57] Input: the captured mouse turns the camera, and a start can give the keyboard's pad its keys The title takes its camera from a pad's right stick and from nothing else: with the pointer captured (F1's MOUSE CAPTURE, `VICTORY_MOUSE_CAPTURE=1`) and 2,700 pixels of motion delivered as the GameInput mouse device, the camera stood still, and it turned at once with the stand-in pad's stick (the prologue's cell, Series S profile). The captured mouse is now the stand-in pad's right stick and triggers as well (`VICTORY_MOUSE_LOOK=0`: the mouse device alone, as before). A stick is a speed and a mouse a distance, so the pixels the hand has moved are owed and paid off: `VICTORY_MOUSE_LOOK_SPEED` pixels a second (2400) are the whole stick, any motion starts past the title's dead zone (`VICTORY_MOUSE_LOOK_DEADZONE`, 20 percent), and a flick faster than the stick can turn is kept and turned after (`VICTORY_MOUSE_LOOK_BANK`, 350 ms of full stick at most). `VICTORY_MOUSE_LOOK_CURVE` and `VICTORY_MOUSE_LOOK_VERTICAL` (percent; negative: the other way up) shape it. The left button is the right trigger, the right button the left one, the middle button a press of the right stick. The pointer is put back to the middle after each sample where its motion is the stick (`VICTORY_MOUSE_WARP=1` or `0` asks for either): left alone it stops at the window's edge, and the stick with it. `VICTORY_PAD_KEYS=<key>=<button>,...` gives the keyboard's stand-in pad keys of the start's own; `pc` is a layout for keyboard and mouse (Left Shift A, Space X, F Y, R B, Tab LB, Q RB, Left Ctrl L3, C R3, V View; W/A/S/D, Enter, Backspace, Esc and the arrows stay what they were), and more can follow it. A key named there is that button alone. Checked in the game (2026-11-28; a shared save in the first house, Series S profile, RTX 3090 Ti) with the pointer moved by a script: 700 pixels a second to the right for 2.5 s and to the left for 5 s turned the picture to the right and to the left (screenshots before and after each), and W made the character get up and walk. The feel (dead zone, speed) has not been tuned by a hand on the mouse. 32 tests of the module pass, seven of them new. AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-hle/src/modules/gameinput.rs | 461 +++++++++++++++++++- crates/victory-hle/src/modules/lifecycle.rs | 6 +- 2 files changed, 462 insertions(+), 5 deletions(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 85b60195d..7b99168a9 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -167,15 +167,123 @@ trait Source: Send { fn rumble(&mut self, slot: usize, low: u16, high: u16); } +/// What a key of the stand-in pad is, where a start says so. +#[derive(Clone, Copy, Debug, PartialEq)] +enum PadKey { + Button(u32), + LeftTrigger, + RightTrigger, +} + +/// `VICTORY_PAD_KEYS=pc`: the keyboard as third-person games on a PC have +/// it, on the pad layout that is usual for them (A run, X jump, Y into a +/// vehicle, B reload, the left bumper the weapons, the right one cover, a +/// press of the left stick crouch, of the right one a look back). With the +/// mouse ([`Look`]): W/A/S/D walk, the mouse looks, its buttons shoot and +/// aim. +const PC_KEYS: &str = "LShift=A,Space=X,F=Y,R=B,Tab=LB,Q=RB,LCtrl=L3,C=R3,V=View"; + +/// The keys a start gives the stand-in pad (`VICTORY_PAD_KEYS=<key>=<button>,...`, +/// or `pc` for [`PC_KEYS`], or `pc` and more after it). A key named here is +/// that button alone: what [`FALLBACK_BUTTONS`], the sticks' letters and the +/// triggers' say of it no longer holds. Keys: a letter, a digit, `Space`, +/// `Enter`, `Tab`, `Esc`, `Back`, `Up`, `Down`, `Left`, `Right`, `CapsLock`, +/// `LShift`, `RShift`, `LCtrl`, `RCtrl`, `LAlt`, `RAlt`. Buttons: `A`, `B`, +/// `X`, `Y`, `LB`, `RB`, `LT`, `RT`, `L3`, `R3`, `Menu`, `View`, `Up`, +/// `Down`, `Left`, `Right`. What is not understood is said and left out. +fn parse_pad_keys(text: &str) -> Vec<(u8, PadKey)> { + let key = |name: &str| -> Option<u8> { + Some(match name.to_ascii_lowercase().as_str() { + "space" => 0x20, + "enter" => 0x0D, + "tab" => 0x09, + "esc" => 0x1B, + "back" => 0x08, + "up" => 0x26, + "down" => 0x28, + "left" => 0x25, + "right" => 0x27, + "capslock" => 0x14, + "lshift" | "shift" => 0xA0, + "rshift" => 0xA1, + "lctrl" | "ctrl" => 0xA2, + "rctrl" => 0xA3, + "lalt" | "alt" => 0xA4, + "ralt" => 0xA5, + k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => k.as_bytes()[0].to_ascii_uppercase(), + _ => return None, + }) + }; + let button = |name: &str| -> Option<PadKey> { + Some(match name.to_ascii_lowercase().as_str() { + "a" => PadKey::Button(A), + "b" => PadKey::Button(B), + "x" => PadKey::Button(X), + "y" => PadKey::Button(Y), + "lb" => PadKey::Button(LEFT_SHOULDER), + "rb" => PadKey::Button(RIGHT_SHOULDER), + "l3" => PadKey::Button(LEFT_STICK), + "r3" => PadKey::Button(RIGHT_STICK), + "menu" => PadKey::Button(MENU), + "view" => PadKey::Button(VIEW), + "up" => PadKey::Button(UP), + "down" => PadKey::Button(DOWN), + "left" => PadKey::Button(LEFT), + "right" => PadKey::Button(RIGHT), + "lt" => PadKey::LeftTrigger, + "rt" => PadKey::RightTrigger, + _ => return None, + }) + }; + let mut keys: Vec<(u8, PadKey)> = Vec::new(); + for part in text.split(',').map(str::trim).filter(|p| !p.is_empty()) { + if part.eq_ignore_ascii_case("pc") { + for (k, b) in parse_pad_keys(PC_KEYS) { + keys.retain(|(known, _)| *known != k); + keys.push((k, b)); + } + continue; + } + match part.split_once('=').and_then(|(k, b)| Some((key(k.trim())?, button(b.trim())?))) { + Some((k, b)) => { + // The last word on a key holds. + keys.retain(|(known, _)| *known != k); + keys.push((k, b)); + } + None => tracing::warn!(part, "VICTORY_PAD_KEYS: not a key and a button, left out"), + } + } + keys +} + +fn pad_keys() -> &'static [(u8, PadKey)] { + static KEYS: LazyLock<Vec<(u8, PadKey)>> = LazyLock::new(|| { + let keys = parse_pad_keys(&std::env::var("VICTORY_PAD_KEYS").unwrap_or_default()); + if !keys.is_empty() { + tracing::info!(keys = keys.len(), "the keyboard's stand-in pad has keys of the start's (VICTORY_PAD_KEYS)"); + } + keys + }); + &KEYS +} + fn fallback(keys: &[KeyState]) -> PadState { + fallback_with(keys, pad_keys()) +} + +/// The stand-in pad for the keys held, `given` being the start's own keys +/// ([`parse_pad_keys`]). +fn fallback_with(keys: &[KeyState], given: &[(u8, PadKey)]) -> PadState { + let held = |vk: u8| keys.iter().any(|k| k.virtual_key == vk); + // A key the start gave a button is no longer what the tables say. let on = |vk: u8| { - if keys.iter().any(|k| k.virtual_key == vk) { + if held(vk) && !given.iter().any(|(k, _)| *k == vk) { 1.0 } else { 0.0 } }; - PadState { + let mut pad = PadState { buttons: FALLBACK_BUTTONS .iter() .filter(|(vk, _)| on(*vk) != 0.0) @@ -186,7 +294,15 @@ fn fallback(keys: &[KeyState]) -> PadState { left_y: on(b'W') - on(b'S'), right_x: on(b'L') - on(b'J'), right_y: on(b'I') - on(b'K'), + }; + for (_, key) in given.iter().filter(|(vk, _)| held(*vk)) { + match key { + PadKey::Button(bit) => pad.buttons |= bit, + PadKey::LeftTrigger => pad.left_trigger = 1.0, + PadKey::RightTrigger => pad.right_trigger = 1.0, + } } + pad } /// Two pads as one: buttons of both, and of each axis and trigger the one @@ -204,6 +320,158 @@ fn merged(a: PadState, b: PadState) -> PadState { } } +/// The captured mouse as the stand-in pad's right stick and triggers +/// (`VICTORY_MOUSE_LOOK`, on wherever the mouse is captured; `0`: the mouse +/// is the GameInput mouse device alone, as before). The title turns its +/// camera with a pad's right stick and with nothing else: with the pointer +/// captured and 2,700 pixels of motion delivered as the mouse device the +/// camera stood still, and it turned at once with the stand-in pad's stick +/// (the prologue's cell, Series S profile, 2026-11-27). +/// +/// A stick is a speed and a mouse a distance. What the pointer has moved is +/// owed to the camera, and the stick is pushed to pay it within +/// [`LOOK_PAY`]: a slow hand holds the stick as far as its speed is of +/// `speed` pixels a second, and what a fast hand asks beyond the whole stick +/// is kept (up to `bank` seconds of the whole stick) and turned after it, +/// not lost. Any motion starts past the title's dead zone. The left button +/// is the right trigger, the right button the left one, the middle button a +/// press of the right stick. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Look { + /// Pixels a second that push the stick all the way + /// (`VICTORY_MOUSE_LOOK_SPEED`). + speed: f32, + /// Where the stick stands as soon as the pointer moves, 0 to 1 + /// (`VICTORY_MOUSE_LOOK_DEADZONE`, in percent). + dead_zone: f32, + /// The stick's way past the dead zone is the speed's share to this + /// power (`VICTORY_MOUSE_LOOK_CURVE`, in percent; 100: in proportion). + curve: f32, + /// Up and down against left and right (`VICTORY_MOUSE_LOOK_VERTICAL`, + /// in percent; negative: the other way up). + vertical: f32, + /// How much of a fast hand's motion is kept to be turned after it, in + /// seconds of the whole stick (`VICTORY_MOUSE_LOOK_BANK`, in + /// milliseconds; 0: none, the stick follows the pointer's speed alone). + bank: f32, +} + +/// The seconds within which the stick pays what the pointer has moved: a +/// frame and a half of the title at 30 a second, so each of its frames reads +/// what the pointer did during the one before, and the stick does not flicker +/// between the pointer's steps. +const LOOK_PAY: f32 = 0.05; + +impl Look { + const DEFAULT: Look = Look { speed: 2400.0, dead_zone: 0.2, curve: 1.0, vertical: 1.0, bank: 0.35 }; + + /// What `get` (the environment) asks for; `None`: no mapping. + fn from(get: impl Fn(&str) -> Option<String>) -> Option<Look> { + if get("VICTORY_MOUSE_LOOK").is_some_and(|v| v.trim() == "0") { + return None; + } + let number = |name: &str| get(name).and_then(|v| v.trim().parse::<f32>().ok()).filter(|v| v.is_finite()); + let d = Look::DEFAULT; + Some(Look { + speed: number("VICTORY_MOUSE_LOOK_SPEED").map_or(d.speed, |v| v.clamp(100.0, 100_000.0)), + dead_zone: number("VICTORY_MOUSE_LOOK_DEADZONE").map_or(d.dead_zone, |v| (v / 100.0).clamp(0.0, 0.9)), + curve: number("VICTORY_MOUSE_LOOK_CURVE").map_or(d.curve, |v| (v / 100.0).clamp(0.2, 4.0)), + vertical: number("VICTORY_MOUSE_LOOK_VERTICAL").map_or(d.vertical, |v| (v / 100.0).clamp(-4.0, 4.0)), + bank: number("VICTORY_MOUSE_LOOK_BANK").map_or(d.bank, |v| (v / 1000.0).clamp(0.0, 3.0)), + }) + } + + /// The stick for `share` (0 to 1) of the whole speed towards the unit + /// vector (`x`, `y`), up positive. + fn stick(&self, share: f32, x: f32, y: f32) -> (f32, f32) { + let reach = self.dead_zone + (1.0 - self.dead_zone) * share.clamp(0.0, 1.0).powf(self.curve); + (x * reach, y * reach) + } +} + +/// See [`Look`]; whether the pointer is put back to the middle after each +/// sample follows it (`lifecycle::captured_mouse_delta`). +pub(crate) fn mouse_look() -> bool { + look().is_some() +} + +fn look() -> Option<Look> { + static LOOK: LazyLock<Option<Look>> = LazyLock::new(|| { + let look = Look::from(|name| std::env::var(name).ok()); + if let Some(l) = look + && super::lifecycle::enabled("VICTORY_MOUSE_CAPTURE") + { + tracing::info!( + speed = l.speed, + dead_zone = l.dead_zone, + curve = l.curve, + vertical = l.vertical, + bank = l.bank, + "the captured mouse is the stand-in pad's right stick and triggers (VICTORY_MOUSE_LOOK=0: the mouse device alone)" + ); + } + look + }); + *LOOK +} + +/// What the camera still owes the pointer. +#[derive(Default)] +struct MouseLook { + /// Time and cumulative position of the sample before. + last: Option<(u64, i64, i64)>, + /// Pixels the pointer has moved that the stick has not turned yet, up + /// positive. + owed: (f32, f32), +} + +impl MouseLook { + /// What the mouse adds to the stand-in pad at `now` (microseconds). + fn pad(&mut self, look: &Look, mouse: Option<&MouseState>, now: u64) -> PadState { + let Some(mouse) = mouse else { + *self = MouseLook::default(); + return PadState::default(); + }; + // Since the sample before: the stick is taken to stand as long again + // (a long gap is not one long push). + let (seconds, dx, dy) = match self.last { + Some((t, x, y)) => ( + (now.saturating_sub(t) as f32 / 1e6).clamp(0.002, 0.032), + (mouse.position_x - x) as f32, + (mouse.position_y - y) as f32, + ), + None => (POLL.as_secs_f32(), 0.0, 0.0), + }; + self.last = Some((now, mouse.position_x, mouse.position_y)); + let (mut x, mut y) = (self.owed.0 + dx, self.owed.1 - dy * look.vertical); + let mut owed = x.hypot(y); + // No more is kept than the whole stick turns in `bank` seconds. + let most = look.speed * look.bank.max(LOOK_PAY); + if owed > most { + (x, y) = (x * most / owed, y * most / owed); + owed = most; + } + let (right_x, right_y) = if owed < 0.05 { + self.owed = (0.0, 0.0); + (0.0, 0.0) + } else { + let share = (owed / (LOOK_PAY * look.speed)).min(1.0); + let left = 1.0 - (share * look.speed * seconds).min(owed) / owed; + self.owed = (x * left, y * left); + look.stick(share, x / owed, y / owed) + }; + let held = |bit: u32| if mouse.buttons & bit != 0 { 1.0 } else { 0.0 }; + PadState { + buttons: if mouse.buttons & 0x4 != 0 { RIGHT_STICK } else { 0 }, + left_trigger: held(0x2), + right_trigger: held(0x1), + right_x, + right_y, + ..PadState::default() + } + } +} + /// Whether the title sees one pad that is always there, fed by the keyboard /// and by every host pad (on by default; `VICTORY_ONE_PAD=0` shows each host /// pad as a device of its own, and the stand-in only while there is none). @@ -406,6 +674,8 @@ struct State { pending: Vec<Event>, /// Device callbacks running now: token and thread. running: Vec<(u64, ThreadId)>, + /// The mouse as the stand-in pad's stick ([`Look`]). + look: MouseLook, } pub struct Hub { @@ -453,6 +723,7 @@ impl Hub { callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), + look: MouseLook::default(), }), returned: Condvar::new(), })); @@ -540,9 +811,10 @@ impl State { ) -> Vec<Event> { let now = now(); let mut events = std::mem::take(&mut self.pending); + let looked = look().map_or_else(PadState::default, |l| self.look.pad(&l, mouse.as_ref(), now)); self.update(devices, MOUSE, mouse.map(Value::Mouse), now, &mut events); if one_pad { - let pad = pads.into_iter().flatten().fold(fallback(&keys), merged); + let pad = pads.into_iter().flatten().fold(merged(fallback(&keys), looked), merged); self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events); self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); return events; @@ -551,7 +823,7 @@ impl State { for (slot, pad) in pads.into_iter().enumerate() { self.update(devices, slot, pad.map(Value::Pad), now, &mut events); } - let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys))); + let fallback = (!any_pad).then(|| Value::Pad(merged(fallback(&keys), looked))); self.update(devices, FALLBACK, fallback, now, &mut events); self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); events @@ -1725,6 +1997,187 @@ mod tests { assert_eq!(resumed, MouseState { position_x: 15, position_y: -1, buttons: 0b10, ..Default::default() }); } + fn mouse_at(x: i64, y: i64) -> MouseState { + MouseState { position_x: x, position_y: y, ..Default::default() } + } + + /// A slow hand holds the stick as far as its speed is of `speed`, past + /// the dead zone as soon as it moves, and the stick is at rest again + /// soon after the pointer is. + #[test] + fn the_captured_mouse_is_the_right_stick() { + let look = Look { speed: 2000.0, dead_zone: 0.25, curve: 1.0, vertical: 1.0, bank: 0.5 }; + let mut m = MouseLook::default(); + assert_eq!(m.pad(&look, Some(&mouse_at(0, 0)), 0), PadState::default()); + // 8 pixels every 8 ms to the right: 1,000 pixels a second, half the way past the dead zone. + let mut pad = PadState::default(); + for i in 1..=60 { + pad = m.pad(&look, Some(&mouse_at(8 * i, 0)), 8_000 * i as u64); + } + assert!((pad.right_x - 0.625).abs() < 0.005 && pad.right_y == 0.0, "{pad:?}"); + assert_eq!((pad.buttons, pad.left_trigger, pad.right_trigger, pad.left_x, pad.left_y), (0, 0.0, 0.0, 0.0, 0.0)); + // The first step is past the dead zone at once, and not a jump to the whole stick. + let mut first = MouseLook::default(); + first.pad(&look, Some(&mouse_at(0, 0)), 0); + let step = first.pad(&look, Some(&mouse_at(8, 0)), 8_000); + assert!(step.right_x > 0.25 && step.right_x < 0.4, "{step:?}"); + // The pointer stands still: the stick falls back and is at rest within half a second. + for i in 61..=120 { + pad = m.pad(&look, Some(&mouse_at(480, 0)), 8_000 * i as u64); + } + assert_eq!(pad, PadState::default()); + // No mouse (not captured, or the window not in front): nothing, and nothing kept. + m.pad(&look, Some(&mouse_at(880, 0)), 8_000 * 121); + assert_eq!(m.pad(&look, None, 8_000 * 122), PadState::default()); + assert_eq!(m.pad(&look, Some(&mouse_at(9_000, 0)), 8_000 * 123), PadState::default()); + } + + /// What a fast hand asks beyond the whole stick is turned after it: the + /// stick's pushes add up to the pointer's way, up to the bank. + #[test] + fn a_fast_hand_is_turned_after_and_not_lost() { + let look = Look { speed: 2000.0, dead_zone: 0.25, curve: 1.0, vertical: 1.0, bank: 0.5 }; + // The pixels a pad's stick turns in one 8 ms sample, from its reach. + let turned = |pad: &PadState| { + let reach = pad.right_x.hypot(pad.right_y); + if reach == 0.0 { 0.0 } else { (reach - 0.25) / 0.75 * 2000.0 * 0.008 } + }; + let mut m = MouseLook::default(); + m.pad(&look, Some(&mouse_at(0, 0)), 0); + // 600 pixels in 80 ms (7,500 a second, nearly four times the whole stick), then rest. + let (mut sum, mut full) = (0.0, 0); + for i in 1..=200_i64 { + let pad = m.pad(&look, Some(&mouse_at(60 * i.min(10), 0)), 8_000 * i as u64); + assert!(pad.right_x >= 0.0 && pad.right_x <= 1.0 && pad.right_y == 0.0, "{pad:?}"); + full += i64::from(pad.right_x == 1.0); + sum += turned(&pad); + } + assert!((sum - 600.0).abs() < 2.0, "{sum}"); + // The whole stick for about (600 - 100) / 16 samples, a quarter of a second, and at rest after. + assert!((28..=36).contains(&full), "{full}"); + assert_eq!(m.pad(&look, Some(&mouse_at(600, 0)), 8_000 * 201), PadState::default()); + // More than the bank holds (half a second of the whole stick: 1,000 pixels) is let go. + let mut m = MouseLook::default(); + m.pad(&look, Some(&mouse_at(0, 0)), 0); + let mut sum = turned(&m.pad(&look, Some(&mouse_at(5_000, 0)), 8_000)); + for i in 2..=300 { + sum += turned(&m.pad(&look, Some(&mouse_at(5_000, 0)), 8_000 * i)); + } + assert!((sum - 1000.0).abs() < 2.0, "{sum}"); + // With no bank the stick follows the pointer's speed alone: at rest 0.2 s after the same fast move. + let none = Look { bank: 0.0, ..look }; + let mut m = MouseLook::default(); + m.pad(&none, Some(&mouse_at(0, 0)), 0); + let mut pad = PadState::default(); + for i in 1..=35_i64 { + pad = m.pad(&none, Some(&mouse_at(60 * i.min(10), 0)), 8_000 * i as u64); + } + assert!(pad.right_x < 0.3, "{pad:?}"); + } + + /// Up on the mouse is up on the stick (the pointer's y grows downwards), + /// the direction is kept, and the settings turn and scale it. + #[test] + fn the_mouse_stick_keeps_the_direction() { + let look = Look { speed: 1000.0, dead_zone: 0.0, curve: 1.0, vertical: 1.0, bank: 0.5 }; + // 3 left and 4 up every 8 ms, steadily: 625 pixels a second, three parts left to four up. + let steady = |look: &Look, dx: i64, dy: i64| { + let mut m = MouseLook::default(); + m.pad(look, Some(&mouse_at(0, 0)), 0); + let mut pad = PadState::default(); + for i in 1..=80_i64 { + pad = m.pad(look, Some(&mouse_at(dx * i, dy * i)), 8_000 * i as u64); + } + (pad.right_x, pad.right_y) + }; + let (x, y) = steady(&look, -3, -4); + assert!((x + 0.375).abs() < 0.005 && (y - 0.5).abs() < 0.005, "{x} {y}"); + let inverted = Look { vertical: -1.0, ..look }; + let (x, y) = steady(&inverted, 0, -4); + assert!(x == 0.0 && (y + 0.5).abs() < 0.005, "{x} {y}"); + let half = Look { vertical: 0.5, ..look }; + assert!((steady(&half, 0, -4).1 - 0.25).abs() < 0.005); + // A curve below 1 lifts slow motion, the dead zone is where it starts. + let curved = Look { curve: 0.5, dead_zone: 0.2, ..look }; + let (x, y) = curved.stick(0.25, 1.0, 0.0); + assert!((x - (0.2 + 0.8 * 0.5)).abs() < 1e-4 && y == 0.0, "{x} {y}"); + } + + /// Left button: right trigger; right button: left trigger; middle: the + /// right stick's press. + #[test] + fn the_mouse_buttons_are_the_triggers() { + let mut m = MouseLook::default(); + let held = |buttons| MouseState { buttons, ..Default::default() }; + let pad = m.pad(&Look::DEFAULT, Some(&held(0b001)), 0); + assert_eq!((pad.right_trigger, pad.left_trigger, pad.buttons), (1.0, 0.0, 0)); + let pad = m.pad(&Look::DEFAULT, Some(&held(0b110)), 8_000); + assert_eq!((pad.right_trigger, pad.left_trigger, pad.buttons), (0.0, 1.0, RIGHT_STICK)); + } + + /// The mapping is there unless `VICTORY_MOUSE_LOOK=0`, with its numbers + /// from the environment, kept within sense. + #[test] + fn the_mouse_look_settings() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned()) + }; + assert_eq!(Look::from(env(&[])), Some(Look::DEFAULT)); + assert_eq!(Look::from(env(&[("VICTORY_MOUSE_LOOK", "0")])), None); + assert_eq!(Look::from(env(&[("VICTORY_MOUSE_LOOK", "1")])), Some(Look::DEFAULT)); + let set = Look::from(env(&[ + ("VICTORY_MOUSE_LOOK_SPEED", "4500"), + ("VICTORY_MOUSE_LOOK_DEADZONE", "15"), + ("VICTORY_MOUSE_LOOK_CURVE", "60"), + ("VICTORY_MOUSE_LOOK_VERTICAL", "-80"), + ("VICTORY_MOUSE_LOOK_BANK", "250"), + ])); + assert_eq!(set, Some(Look { speed: 4500.0, dead_zone: 0.15, curve: 0.6, vertical: -0.8, bank: 0.25 })); + let wild = Look::from(env(&[("VICTORY_MOUSE_LOOK_SPEED", "1"), ("VICTORY_MOUSE_LOOK_DEADZONE", "x")])).unwrap(); + assert_eq!((wild.speed, wild.dead_zone), (100.0, Look::DEFAULT.dead_zone)); + } + + /// `VICTORY_PAD_KEYS`: a key given a button is that button alone, the + /// other keys stay what the tables say, `pc` is the PC layout, and the + /// last word on a key holds. + #[test] + fn the_start_can_give_the_stand_in_pad_its_keys() { + let down = |vks: &[u8]| -> Vec<KeyState> { + vks.iter().map(|&vk| KeyState { virtual_key: vk, ..Default::default() }).collect() + }; + // Nothing given: as the tables say (C the right trigger, F the left stick's press). + let pad = fallback_with(&down(&[b'C', b'F', b'W']), &[]); + assert_eq!((pad.right_trigger, pad.buttons, pad.left_y), (1.0, LEFT_STICK, 1.0)); + let pc = parse_pad_keys("pc"); + assert_eq!(pc.len(), 9); + // The PC layout: C looks back and is no trigger, F is Y, Shift runs, Space jumps. + let pad = fallback_with(&down(&[b'C', b'F', 0xA0, 0x20, b'W']), &pc); + assert_eq!((pad.right_trigger, pad.left_y), (0.0, 1.0)); + assert_eq!(pad.buttons, RIGHT_STICK | Y | A | X); + // Keys it does not name stay: Enter is A, E the right bumper, Z the left trigger. + let pad = fallback_with(&down(&[0x0D, b'E', b'Z']), &pc); + assert_eq!((pad.buttons, pad.left_trigger), (A | RIGHT_SHOULDER, 1.0)); + // Triggers can be given, a later word replaces an earlier one, nonsense is left out. + let keys = parse_pad_keys("pc, G=RT ,f=lt, nonsense, Q=, 7=Up, F=Down"); + assert_eq!(keys.iter().filter(|(k, _)| *k == b'F').copied().collect::<Vec<_>>(), [(b'F', PadKey::Button(DOWN))]); + let pad = fallback_with(&down(&[b'G', b'7', b'F']), &keys); + assert_eq!((pad.right_trigger, pad.buttons), (1.0, UP | DOWN)); + assert!(parse_pad_keys("").is_empty()); + } + + /// The stand-in pad carries the mouse's stick beside the keyboard's keys. + #[test] + fn the_stand_in_pad_takes_the_mouse_and_the_keys() { + let keys = [KeyState { virtual_key: b'W', ..Default::default() }]; + let mut m = MouseLook::default(); + let look = Look { speed: 1000.0, dead_zone: 0.0, curve: 1.0, vertical: 1.0, bank: 0.5 }; + m.pad(&look, Some(&mouse_at(0, 0)), 0); + let mouse = m.pad(&look, Some(&MouseState { buttons: 1, ..mouse_at(25, 0) }), 8_000); + let pad = merged(fallback_with(&keys, &[]), mouse); + assert_eq!((pad.left_y, pad.right_trigger), (1.0, 1.0)); + assert!((pad.right_x - 0.5).abs() < 0.01, "{pad:?}"); + } + #[test] fn pads_connect_report_and_disconnect() { let (hub, host) = fake(); diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 31ecf7811..22e9f00b8 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -192,7 +192,11 @@ pub(super) fn captured_mouse_delta() -> Option<(i64, i64)> { let mut point = POINT::default(); if wm::GetCursorPos(&mut point) == 0 { state.reference = None; return None; } let point = (point.x, point.y); - let warp = std::env::var_os("VICTORY_MOUSE_WARP").is_some_and(|v| v == "1"); + // Put back to the middle after each sample where the motion is a pad's stick + // (`gameinput::mouse_look`): left alone, the pointer stops at the window's edge + // and the stick with it. `VICTORY_MOUSE_WARP=1` or `0` asks for either. + let warp = std::env::var_os("VICTORY_MOUSE_WARP") + .map_or_else(crate::modules::gameinput::mouse_look, |v| v == "1"); let warped = (warp && wm::SetCursorPos(state.center.0, state.center.1) != 0) .then_some(state.center); Some(mouse_motion(&mut state.reference, point, warped)) From c800cb2c4f479b23b9836a40aa0601f05253ec33 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 04:36:45 -0500 Subject: [PATCH 23/57] Build: thin LTO, one codegen unit, x86-64-v3; the layer's own allocations through mimalloc The release profile inlines across crates (thin LTO, one codegen unit a crate) and the compiler may use AVX2, BMI and FMA (x86-64-v3; the title's own code needs AVX2 already). The layer's own allocations come from mimalloc, which keeps blocks per thread, where they came from the process heap that the title's threads and the drivers share (feature `mimalloc` of victory-gpu, on by default for the `victory` program; `--no-default-features` builds as before). The allocator that counts blocks stays in front of it. Measured together with the next commit (prologue's cell, Series S profile, DLSS off, RTX 3090 Ti, Ryzen 9 9950X3D, medians of five-second readings over four minutes): 31.7 -> 31.9 frames a second, the thread that prepares submissions 29.3 -> 28.7 ms a frame. Small here; trustno1-coder/VIctory-NVIDIA #537 (hqjake) and #11 (Dastano) proposed the same and measured more on slower processors. AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .cargo/config.toml | 5 +++++ Cargo.lock | 19 +++++++++++++++++++ Cargo.toml | 6 ++++++ apps/victory/Cargo.toml | 4 ++++ crates/victory-gpu/Cargo.toml | 4 ++++ crates/victory-gpu/src/copystat.rs | 26 ++++++++++++++++++-------- crates/victory-hle/Cargo.toml | 2 ++ 7 files changed, 58 insertions(+), 8 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 9741f113e..2cfd6b230 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,7 @@ [alias] xtask = "run --quiet --package xtask --" + +# AVX2, BMI and FMA wherever the compiler finds a use for them (the title's +# own code needs AVX2 already: the consoles' processors have it). +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-cpu=x86-64-v3"] diff --git a/Cargo.lock b/Cargo.lock index 9a656d8bf..f1095b10e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -248,6 +248,15 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -275,6 +284,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -676,6 +694,7 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", + "mimalloc", "tempfile", "tracing", "victory-formats", diff --git a/Cargo.toml b/Cargo.toml index 4e21b692d..413dc51d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ license = "GPL-3.0-or-later" publish = false [workspace.dependencies] +mimalloc = { version = "0.1", default-features = false } # Internal crates victory-core = { path = "crates/victory-core" } victory-pe = { path = "crates/victory-pe" } @@ -71,6 +72,11 @@ opt-level = 2 [profile.release] debug = "line-tables-only" +# One unit a crate and inlining across crates: the thread that prepares +# submissions spends its frame in small calls from victory-gpu into +# victory-hle and victory-shader and back. +lto = "thin" +codegen-units = 1 # The development build: release code generation plus the `diagnostics` # feature (`cargo build --profile diag -p victory --features diagnostics`), diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index efaa1091e..0641b505a 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -22,6 +22,10 @@ clap.workspace = true walkdir.workspace = true [features] +default = ["mimalloc"] +# Our own allocations through mimalloc (`--no-default-features`: the process +# heap, as before). +mimalloc = ["victory-hle/mimalloc"] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diagnostics = [ diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 2b4c5b007..52b0abc89 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true publish.workspace = true [dependencies] +mimalloc = { workspace = true, optional = true } blake3.workspace = true zlib-rs.workspace = true tracing.workspace = true @@ -25,6 +26,9 @@ tempfile.workspace = true [features] # Debugging switches (frame capture, the host debug layer, per-draw data). diagnostics = [] +# Our own allocations come from mimalloc (a cache of blocks per thread), not +# from the process heap that the title's threads and the drivers use too. +mimalloc = ["dep:mimalloc"] [lints] workspace = true diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 948da3265..333256f16 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -402,16 +402,26 @@ fn big_blocks() -> String { 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). +/// The allocator with every block counted in [`OWN`] (two atomic additions +/// per allocation and per release). The blocks are the system's, or with the +/// `mimalloc` feature mimalloc's ([`INNER`]). struct Counting; -// SAFETY: every call goes to the system's allocator unchanged; only -// counters are kept beside it. +/// Where [`Counting`] gets its blocks. The process heap is one heap for our +/// threads, the title's and the drivers', taken with its lock; the thread +/// that prepares submissions and its helpers make and grow vectors +/// thousands of times a frame. +#[cfg(not(feature = "mimalloc"))] +const INNER: std::alloc::System = std::alloc::System; +#[cfg(feature = "mimalloc")] +const INNER: mimalloc::MiMalloc = mimalloc::MiMalloc; + +// SAFETY: every call goes to the allocator beneath unchanged; only counters +// are kept beside it. unsafe impl std::alloc::GlobalAlloc for Counting { unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let at = unsafe { std::alloc::System.alloc(layout) }; + let at = unsafe { INNER.alloc(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); @@ -421,7 +431,7 @@ unsafe impl std::alloc::GlobalAlloc for Counting { unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let at = unsafe { std::alloc::System.alloc_zeroed(layout) }; + let at = unsafe { INNER.alloc_zeroed(layout) }; if !at.is_null() { own(layout.size(), true); big(at, layout.size(), true); @@ -433,12 +443,12 @@ unsafe impl std::alloc::GlobalAlloc for Counting { own(layout.size(), false); big(at, layout.size(), false); // SAFETY: the caller's contract, passed on. - unsafe { std::alloc::System.dealloc(at, layout) }; + unsafe { INNER.dealloc(at, layout) }; } unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { // SAFETY: the caller's contract, passed on. - let moved = unsafe { std::alloc::System.realloc(at, layout, size) }; + let moved = unsafe { INNER.realloc(at, layout, size) }; if !moved.is_null() { own(layout.size(), false); own(size, true); diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 8f4eb0898..1a7a6563d 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -56,6 +56,8 @@ tempfile.workspace = true [features] # Debugging switches (scripted keys and the like). diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"] +# See victory-gpu's feature of the same name. +mimalloc = ["victory-gpu/mimalloc"] [lints] workspace = true From 3a6b62e5e986206cbefde1cd7b884aaa8fb365aa Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 04:36:45 -0500 Subject: [PATCH 24/57] Refreshes: the vectorised compare at the two places that still compared word by word `put_changed` and the refresh of a copy's stale pages found their changed runs with `dword_runs`; `word_runs` gives the same runs (its test says so) 32 bytes at a time where the processor has AVX2. The change is trustno1-coder/VIctory-NVIDIA#145 by lido772, who measured 2.61-2.63 -> 2.40-2.41 microseconds a span there. Here it is within the noise of a run (measured together with the build change before it). AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/shadow.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 0020ed52a..591ee17ce 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2615,7 +2615,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { } return merged.len(); } - let mut runs = dword_runs(at, title, merged, 0); + let mut runs = word_runs(at, title, merged); if runs.len() > 64 { runs = dword_runs(at, title, merged, 32); PUT[3].fetch_add(1, Ordering::Relaxed); @@ -4484,7 +4484,7 @@ impl Shadow { // refresh lie apart. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; let was = crate::host::upcheck::on().then(|| held.to_vec()); - let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) }; + let runs = if whole { vec![(0, n)] } else { word_runs(at, held, title) }; for &(a, len) in &runs { held[a..a + len].copy_from_slice(&title[a..a + len]); self.changed(at - start + a, at - start + a + len); From 9165dd03eb85432d691594d76df8a157fa960149 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 04:36:45 -0500 Subject: [PATCH 25/57] Retired objects: a queue to each thread Host objects the title lets go of while a submission may still use them wait in a queue until that submission has finished. There was one queue under one lock, and the eight threads that record the title's lists each let go of thousands of descriptor slots' resources a frame (some 20,000 in all): a push of nanoseconds each, but a thread that finds the lock taken sleeps and is woken 50 microseconds later or more. A profile of the prologue's cell (RTX 3090 Ti, Ryzen 9 9950X3D, Series S profile) had each of those threads 3.3 of the 22 ms a frame it works in that wait, and the thread that prepares submissions 0.7 ms. Now each thread that retires takes one of 32 queues in turn; what finishes a submission looks through all of them. In one run with switches changed by turns the build with this and the two commits before it ran the same scene at 30.47 ms a frame where the build without them had 32.60 (both with VICTORY_CARD_AWAKE=0, diagnostics builds). AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/host.rs | 45 +++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 169acdc1f..45d9689fa 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -75,7 +75,28 @@ unsafe impl Sync for Host {} /// releases reach the host at once, from its own threads, while the host /// runs a submission: freeing there is a GPU page fault on the freed /// texture (a device hang). -static RETIRED: Mutex<std::collections::VecDeque<(u64, Retired)>> = Mutex::new(std::collections::VecDeque::new()); +/// +/// A queue to each thread that retires, of [`RETIRED_QUEUES`] taken in turn +/// ([`retired`]), each in the order its thread retired. One queue under one +/// lock was what the threads that record the title's lists waited for: eight +/// of them let go of some 20,000 slots' resources a frame, each a push of a +/// few nanoseconds, but a thread that finds the lock taken sleeps and is +/// woken 50 microseconds later or more. 3.3 of the 22 ms a frame each of +/// them was at work, and 0.7 ms of the submitting thread's frame (a profile +/// of the prologue's cell, RTX 3090 Ti, Ryzen 9 9950X3D, Series S profile). +static RETIRED: [Mutex<std::collections::VecDeque<(u64, Retired)>>; RETIRED_QUEUES] = + [const { Mutex::new(std::collections::VecDeque::new()) }; RETIRED_QUEUES]; +const RETIRED_QUEUES: usize = 32; + +/// This thread's queue of [`RETIRED`]. +fn retired() -> &'static Mutex<std::collections::VecDeque<(u64, Retired)>> { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + thread_local! { + static MINE: usize = NEXT.fetch_add(1, Ordering::Relaxed) % RETIRED_QUEUES; + } + // (A thread that is ending has none any more: the first.) + &RETIRED[MINE.try_with(|mine| *mine).unwrap_or(0)] +} /// 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); @@ -480,7 +501,7 @@ pub(crate) fn retire<T: 'static>(object: T) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED + retired() .lock() .unwrap_or_else(|e| e.into_inner()) .push_back((started, Retired::Any(Box::new(object)))); @@ -496,7 +517,7 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { return; } RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); - RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); + retired().lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); } /// How many submissions later than it could (the last one that may use it @@ -514,18 +535,20 @@ fn bury_lag() -> u64 { } /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The -/// numbers come in order, but for threads that overtake each other: one of -/// those is dropped a little later than it could be. +/// numbers of a queue come in order, but for a submission begun between a +/// thread's two looks ([`retire`]): what follows such a one is dropped a +/// little later than it could be. fn bury(finished: u64) { let finished = finished.saturating_sub(bury_lag()); - let done: Vec<(u64, Retired)> = { - let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + let mut done: Vec<(u64, Retired)> = Vec::new(); + for queue in &RETIRED { + let mut retired = queue.lock().unwrap_or_else(|e| e.into_inner()); let n = retired.iter().take_while(|(at, _)| *at <= finished).count(); - if n == 0 { - return; + if n != 0 { + done.extend(retired.drain(..n)); } - retired.drain(..n).collect() - }; + } + // (Dropped with no queue's lock held: a release each.) drop(done); } From b50184c6872180e2312b46bde03fa51198339cad Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 04:37:05 -0500 Subject: [PATCH 26/57] Cores: on a processor of two dies the layer's own threads keep to the die the title does not use (VICTORY_OWN_CPUS) The title gives each of its threads an affinity of its own, to the console's sixteen processors: here the first sixteen, which on a Ryzen of two dies is one die. The layer's threads have none and ran on all 32: a timeline of the prologue's cell (Ryzen 9 9950X3D, RTX 3090 Ti) had the title's threads on processors 0 to 15 alone and the thread that prepares submissions 48 % of its time there, beside them, its memory and its locks crossing between the dies the other half. `VICTORY_OWN_CPUS=<first>-<last>`, or `auto` (the processors of every last-level cache but the one processor 0 has, where there is more than one), is asked for as the process's default processor sets: it holds for every thread that has neither an affinity nor sets of its own, so for ours and the drivers' and not for the title's. The many threads whose work is ahead of what a frame waits for (lists translated, records made) run on every processor all the same (`VICTORY_OWN_CPUS_MANY=0`: on ours too): with them our die had more threads than it runs at a time. `VICTORY_OWN_CPUS_ON=0` leaves everything as it was, and `VICTORY_AB` can flip it while the title runs. `VICTORY_THREAD_CPUS=<name>=<first>-<last>;...` gives the threads whose name begins so processors of their own, for experiments. Not given, nothing changes. Measured by turns in one run each (the same scene, 12 seconds a turn; Series S profile, DLSS off, 16-31 asked for): - every thread of ours on the other die: the usual frame 26.5 ms where it was 29.1, but one frame in ten 41 ms where it was 34 (mean 29.24 against 29.93); - the many threads on every processor, as it is now: mean 28.23 ms against 29.87 (35.4 against 33.5 frames a second), nine frames in ten under 32.0 ms against 33.7. The thread that prepares submissions on a core of its own beside that (16-17, the rest 18-31) gave 0.3 frames a second more, within what two runs differ by: not done. AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/cores.rs | 162 ++++++++++++++++++++++++++++++++ crates/victory-gpu/src/host.rs | 1 + 2 files changed, 163 insertions(+) diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs index b0a6e1396..414380db6 100644 --- a/crates/victory-gpu/src/cores.rs +++ b/crates/victory-gpu/src/cores.rs @@ -31,6 +31,119 @@ fn cpu_sets() -> Vec<(u32, u8)> { sets } +/// One of the system's processors (group 0): its set's id, its number, and the +/// last-level cache it shares. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Cpu { + id: u32, + logical: u8, + cache: u8, +} + +fn cpus() -> Vec<Cpu> { + use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut bytes = 0u32; + // SAFETY: a size query, then the call into a buffer of that size. + unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; + // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. + let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) }; + let mut all = Vec::new(); + let mut at = 0usize; + while ok != 0 && at + size_of::<SYSTEM_CPU_SET_INFORMATION>() <= bytes as usize { + // SAFETY: a record inside the buffer; each says its own size. + let info = unsafe { &*(buffer.as_ptr().cast::<u8>().add(at).cast::<SYSTEM_CPU_SET_INFORMATION>()) }; + if info.Size == 0 { + break; + } + // SAFETY: the record's type is CpuSet (the only one there is). + let set = unsafe { &info.Anonymous.CpuSet }; + if set.Group == 0 { + all.push(Cpu { id: set.Id, logical: set.LogicalProcessorIndex, cache: set.LastLevelCacheIndex }); + } + at += info.Size as usize; + } + all +} + +/// The processors `asked` names among `all`: `<first>-<last>` by their +/// numbers; `auto`, those of every last-level cache but the one processor 0 +/// has, if there is more than one (a processor of two dies). `None`: not +/// understood, or none. +fn own_of(asked: &str, all: &[Cpu]) -> Option<Vec<u32>> { + let asked = asked.trim(); + let chosen: Vec<u32> = if asked.eq_ignore_ascii_case("auto") { + let first = all.iter().find(|c| c.logical == 0)?.cache; + all.iter().filter(|c| c.cache != first).map(|c| c.id).collect() + } else { + let (from, to) = asked.split_once('-')?; + let (from, to) = (from.trim().parse::<u8>().ok()?, to.trim().parse::<u8>().ok()?); + all.iter().filter(|c| (from..=to).contains(&c.logical)).map(|c| c.id).collect() + }; + (!chosen.is_empty() && chosen.len() < all.len()).then_some(chosen) +} + +/// Whether the many threads whose work is ahead of what a frame waits for +/// (lists translated, records made) run on every processor while the others +/// of ours keep to their own ([`keep_own_threads`]). +fn roaming() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_OWN_CPUS").is_some() && std::env::var_os("VICTORY_OWN_CPUS_MANY").is_none_or(|v| v != "0")) +} + +/// The processors our own threads run on, where a start names them +/// (`VICTORY_OWN_CPUS=<first>-<last>`, or `auto`: on a processor of two dies, +/// the die the title does not use; not given: any, as before). +/// +/// The title gives each of its threads an affinity of its own, to the +/// console's sixteen processors: here the first sixteen, on a Ryzen of two +/// dies one die. Our threads have none and ran on all of them: the thread +/// that prepares submissions half its time on the title's die, beside the +/// title's threads on their cores' second halves, and the other half on the +/// other die, its memory and its locks crossing between the two (a timeline +/// of the prologue's cell, Ryzen 9 9950X3D: the title's threads on processors +/// 0 to 15 alone, the preparing thread 48 % there). Asked for as the +/// process's default sets, the choice holds for every thread that has neither +/// an affinity nor sets of its own: ours, the drivers', and not the title's. +/// +/// `VICTORY_OWN_CPUS_ON=0` leaves them as they were (and `VICTORY_AB` can +/// flip it while the title runs). +pub(crate) fn keep_own_threads() { + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, SetProcessDefaultCpuSets}; + static OWN: std::sync::OnceLock<Option<Vec<u32>>> = std::sync::OnceLock::new(); + let Some(own) = OWN.get_or_init(|| { + let asked = std::env::var("VICTORY_OWN_CPUS").ok()?; + let all = cpus(); + let own = own_of(&asked, &all); + match &own { + Some(own) => tracing::info!(asked, processors = own.len(), of = all.len(), "our own threads are kept on these processors (VICTORY_OWN_CPUS)"), + None => tracing::warn!(asked, of = all.len(), "VICTORY_OWN_CPUS: no processors of that name, or all of them: left as it is"), + } + own + }) else { + return; + }; + // 0: not asked yet; 1: kept; 2: let go. + static APPLIED: AtomicU8 = AtomicU8::new(0); + let want = if crate::toggled!("VICTORY_OWN_CPUS_ON") { 1 } else { 2 }; + if APPLIED.swap(want, Relaxed) == want { + return; + } + // SAFETY: our own process, and a list of the system's own set ids (or none: the default again). + let ok = unsafe { + if want == 1 { + SetProcessDefaultCpuSets(GetCurrentProcess(), own.as_ptr(), own.len() as u32) + } else { + SetProcessDefaultCpuSets(GetCurrentProcess(), std::ptr::null(), 0) + } + }; + if ok == 0 { + tracing::warn!(error = %std::io::Error::last_os_error(), "the process's default processor sets could not be set (VICTORY_OWN_CPUS)"); + } +} + /// The sets of the fastest class, if there are slower ones too. fn fast_of(sets: &[(u32, u8)]) -> Vec<u32> { let best = sets.iter().map(|c| c.1).max().unwrap_or(0); @@ -90,6 +203,40 @@ fn ask(what: &str, from: u32) { let set = unsafe { SetThreadPriority(GetCurrentThread(), priority) } != 0; tracing::debug!(what, priority, set, "the thread's priority (VICTORY_HELPER_PRIORITY)"); } + // With processors of our own (`keep_own_threads`): the many threads whose + // work is ahead of what a frame waits for run on any (`VICTORY_OWN_CPUS_MANY=0`: + // on ours too). They are most of our work, and with them our processors + // were more threads than they run at a time: the usual frame 26.5 ms + // where it was 29.1, and one frame in ten 41 ms where it was 34. + if from == 3 && roaming() { + static ALL: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new(); + let all = ALL.get_or_init(|| cpus().iter().map(|c| c.id).collect()); + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), all.as_ptr(), all.len() as u32) }; + tracing::debug!(what, ok, "the thread runs on any processor (VICTORY_OWN_CPUS_MANY)"); + } + // An experiment's own word on this kind of thread + // (`VICTORY_THREAD_CPUS=<name>=<first>-<last>;<name>=...`, the name a + // beginning of the thread's): those processors, whatever the rest says. + static BY_NAME: std::sync::OnceLock<Vec<(String, Vec<u32>)>> = std::sync::OnceLock::new(); + let by_name = BY_NAME.get_or_init(|| { + let asked = std::env::var("VICTORY_THREAD_CPUS").unwrap_or_default(); + let all = cpus(); + asked + .split(';') + .filter_map(|part| { + let (name, range) = part.split_once('=')?; + let own = own_of(range, &all).or_else(|| (range.trim() == "all").then(|| all.iter().map(|c| c.id).collect()))?; + tracing::info!(name, processors = own.len(), "threads of this name run on these processors (VICTORY_THREAD_CPUS)"); + Some((name.trim().to_owned(), own)) + }) + .collect() + }); + if let Some((_, own)) = by_name.iter().find(|(name, _)| what.starts_with(name.as_str())) { + // SAFETY: our own thread and a list of the system's own set ids. + unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), own.as_ptr(), own.len() as u32) }; + return; + } if stage() < from { return; } @@ -163,6 +310,21 @@ impl Priority { mod tests { use super::*; + #[test] + fn our_own_processors_are_a_range_or_the_other_caches() { + let all: Vec<Cpu> = (0..8u8).map(|n| Cpu { id: 256 + u32::from(n), logical: n, cache: n / 4 }).collect(); + assert_eq!(own_of("4-7", &all), Some(vec![260, 261, 262, 263])); + assert_eq!(own_of(" 6 - 9 ", &all), Some(vec![262, 263])); + assert_eq!(own_of("auto", &all), Some(vec![260, 261, 262, 263])); + // All of them, none of them, one cache, nonsense: nothing asked for. + assert_eq!(own_of("0-7", &all), None); + assert_eq!(own_of("9-12", &all), None); + let one: Vec<Cpu> = (0..8u8).map(|n| Cpu { id: 256 + u32::from(n), logical: n, cache: 0 }).collect(); + assert_eq!(own_of("auto", &one), None); + assert_eq!(own_of("fast", &all), None); + assert!(!cpus().is_empty()); + } + #[test] fn the_fast_cores_are_those_of_the_best_class_if_there_is_a_worse_one() { assert_eq!(fast_of(&[(256, 1), (257, 1), (258, 0)]), [256, 257]); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 45d9689fa..9162a92f3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -5994,6 +5994,7 @@ impl Host { crate::streamline::hudless_submitted(id); } } + crate::cores::keep_own_threads(); let was_working = working(true); submitting(1, runs.len()); // The round of the heaps' records asked for when the title submitted From 37b0acebc4368e5e6603c0c5dad370a28ae55e36 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Fri, 27 Nov 2026 16:58:22 -0500 Subject: [PATCH 27/57] Shaders: the console's waterfall over a first-lane table offset is proven by its shape where the per-lane form cannot follow it The console compiler loops over a per-lane descriptor by reading the first active lane's table offset, narrowing EXEC to the lanes with the same one, loading that entry and dropping those lanes. `track` makes each lane load its own entry when `Tracer::waterfall` proves the loop. In the title's programs it mostly cannot: over all 25,760 programs it emits, 44,874 such loops were refused, 37,605 of them because the per-lane form could not show that the compares select the access's lanes and 209 because it could not show that the retry keeps the lanes still waiting. In a wave of 64 run as two host waves of 32, every pass of an unproven loop exchanges the first lane's value and the mask between the halves: four group barriers a pass. `Tracer::waterfall_shape` proves the loop by its exact shape instead, only where `waterfall` refused: one block that branches to itself, with nothing in it but the first-lane reads, `v_cmpx_eq` of each with the same lane value, the table loads, waits, accesses that only read, and `s_andn2_wrexec` of a mask T with itself. T is shown to be EXEC on every entry from the phis (a move of the loop's own entry EXEC from outside; the same retry on the back edge), and the first-lane value is read nowhere past the loop. It proves 32,106 of the refused loops. The same programs are emitted as before, and the DXIL validator gives the same results as before for all of them. Measured in the prologue's cell (RTX 3090 Ti, Series S profile, one run each way unless said): where the card is the limit the frame gets 2.5 to 4 ms shorter. With the title's own upscaler (#68), 30.8 fps before and 33.3, 32.9 and 32.0 after; with DLSS Quality and FSR 3 frame generation, 27.0 rendered before and 30.8 after. On main alone without DLSS, where the translated FSR 4 path keeps the preparing thread at 27 to 28 ms a frame, 28.5 before and 28.7 after. The costliest program of the frame, vfx_proj_decal_vbuffer:CS_ProjDecalReduceClassification_Scalarized (4.1 ms a frame in a timing run), has 27 such loops; its DXIL goes from 149 group barriers to 41. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/victory-shader/src/resource.rs | 347 +++++++++++++++++++++++++- 1 file changed, 346 insertions(+), 1 deletion(-) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ddc03dddd..ae16c51ed 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -363,7 +363,13 @@ pub fn track( for (block, (accesses, mut reads, loads)) in offset_at { reads.sort_unstable(); reads.dedup(); - if let Ok(proof) = t.waterfall(block, &accesses, &reads) { + // Where the per-lane form cannot follow the loop, its exact shape + // still proves it ([`Tracer::waterfall_shape`]). + let proof = t + .waterfall(block, &accesses, &reads) + .ok() + .or_else(|| t.waterfall_shape(block, &accesses, &reads, &loads)); + if let Some(proof) = proof { out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); out.waterfall.loads.extend(loads); @@ -2128,6 +2134,213 @@ impl<'a> Tracer<'a> { Ok(out) } + /// The console compiler's waterfall over a first-lane table offset, by + /// its exact shape, where [`Self::waterfall`] cannot follow the lanes + /// (its per-lane form loses the relation of the two lane masks around + /// the loop in larger programs). The loop is one block that branches to + /// itself with `s_cbranch_execnz`, and holds nothing but: + /// + /// - `v_readfirstlane_b32 sX, vY` of a value set before the loop, under + /// EXEC as the loop found it; + /// - `v_cmpx_eq_u32`/`_i32 exec, sX, vY` of the same two values, without + /// modifiers: EXEC becomes the lanes whose offset is the first lane's; + /// - the table loads at those offsets (`loads`), waits and `s_nop`; + /// - the accesses that use them, which only read (`buffer_load_*`, + /// `image_load*`, `image_sample*`, `image_gather*`), under that EXEC; + /// - `s_andn2_wrexec` of a mask T with itself (EXEC and T become T and + /// not EXEC), then the branch. + /// + /// And T is EXEC on every entry to the loop: from outside, T's value is + /// a move of the very EXEC value the loop starts with; around the back + /// edge both are what that one `s_andn2_wrexec` wrote. So each pass + /// serves the waiting lanes with the first one's offset, drops exactly + /// those, and the loop ends when none waits: every lane makes its own + /// access once, with its own entry, which is what the per-lane load + /// does. + fn waterfall_shape( + &self, + b: usize, + accesses: &[usize], + reads: &[Value], + loads: &[Site], + ) -> Option<Waterfall> { + let block = &self.p.blocks[b]; + let wave64 = self.p.wave64; + let halves: &[u8] = if wave64 { &[0, 1] } else { &[0] }; + if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) + || block.preds.len() != 2 + { + return None; + } + let back = block.preds.iter().position(|&p| p == b)?; + let entry = 1 - back; + let (exit, body) = block.insts.split_last()?; + if exit.name() != "s_cbranch_execnz" { + return None; + } + let (retry, body) = body.split_last()?; + let wrexec = if wave64 { + "s_andn2_wrexec_b64" + } else { + "s_andn2_wrexec_b32" + }; + if retry.name() != wrexec { + return None; + } + // T: the mask the retry reads and writes besides EXEC. + let t = retry.writes.iter().find_map(|&(reg, _)| match reg { + Reg::S(code) if code != EXEC && code != EXEC + 1 => Some(code), + _ => None, + })?; + let t = t - t % 2 * u8::from(wave64); + let phi = |reg: u8| block.phis.iter().find(|p| p.reg == Reg::S(reg)); + let mut head_exec = Vec::new(); + for &k in halves { + let (pe, pt) = (phi(EXEC + k)?, phi(t + k)?); + // Around the back edge: both what the retry wrote, from T as the + // loop found it. + if pe.args[back] != retry.write(Reg::S(EXEC + k))? + || pt.args[back] != retry.write(Reg::S(t + k))? + || retry.read(Reg::S(t + k))? != pt.value + { + return None; + } + // From outside: T is a move of the EXEC the loop is entered with. + let (tb, ti) = self.defs[pt.args[entry].0 as usize]?; + let mov = self.inst((tb, ti)); + let moves = if wave64 { "s_mov_b64" } else { "s_mov_b32" }; + if mov.name() != moves || mov.read(Reg::S(EXEC + k))? != pe.args[entry] { + return None; + } + head_exec.push(pe.value); + } + let exec_is = |inst: &Inst, values: &[Value]| { + halves + .iter() + .zip(values) + .all(|(&k, &v)| inst.read(Reg::S(EXEC + k)) == Some(v)) + }; + let mut out = Waterfall::default(); + let mut selected: Option<Vec<Value>> = None; + // The lane value each first-lane read took, by the read's result. + let mut read_from: Vec<(Value, Value)> = Vec::new(); + for (i, inst) in body.iter().enumerate() { + let name = inst.name(); + let site = (b, i); + if name == "s_nop" || name.starts_with("s_waitcnt") { + continue; + } + if name == "v_readfirstlane_b32" { + // Before the compares, under the loop's own EXEC. + if selected.is_some() || !exec_is(inst, &head_exec) { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let Some(&Operand::Vector { reg, .. }) = f.src.first() else { + return None; + }; + let lane = inst.read(Reg::V(reg))?; + // Set before the loop: the same in every pass. + if self.phis[lane.0 as usize].is_some_and(|(pb, _)| pb == b) + || self.defs[lane.0 as usize].is_some_and(|(db, _)| db == b) + { + return None; + } + let &(_, got) = inst.writes.first()?; + read_from.push((got, lane)); + continue; + } + if name == "v_cmpx_eq_u32" || name == "v_cmpx_eq_i32" { + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 + || f.neg != 0 + || f.opsel != 0 + || f.clamp + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + // Compares narrow EXEC one after another. + let before = selected.clone().unwrap_or_else(|| head_exec.clone()); + if !exec_is(inst, &before) { + return None; + } + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + return None; + }; + let pair = |first: &Operand, own: &Operand| -> Option<Value> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = + (first, own) + else { + return None; + }; + let x = inst.read(Reg::S(code))?; + let lane = inst.read(Reg::V(reg))?; + read_from + .iter() + .any(|&(got, from)| got == x && from == lane) + .then_some(x) + }; + let x = pair(a, c).or_else(|| pair(c, a))?; + let narrowed = halves + .iter() + .map(|&k| inst.write(Reg::S(EXEC + k))) + .collect::<Option<Vec<_>>>()?; + selected = Some(narrowed); + out.compares.push(site); + if !out.reads.contains(&x) { + out.reads.push(x); + } + continue; + } + let sel = selected.as_deref()?; + if loads.contains(&site) { + continue; + } + let reads_only = name.starts_with("buffer_load") + || name.starts_with("image_load") + || name.starts_with("image_sample") + || name.starts_with("image_gather"); + if accesses.contains(&i) && reads_only && exec_is(inst, sel) { + continue; + } + return None; + } + // The retry takes T and not the EXEC the compares left. + let sel = selected?; + if !exec_is(retry, &sel) { + return None; + } + // Every offset read is one a compare made the lane's own, and every + // access was seen. + if reads.iter().any(|v| !out.reads.contains(v)) || accesses.iter().any(|&i| i >= body.len()) + { + return None; + } + // Read nowhere else: made the lane's own, a first-lane value must + // not reach code past the loop, which would see the last pass's. + for (ob, other) in self.p.blocks.iter().enumerate() { + let carried = other + .phis + .iter() + .any(|p| p.args.iter().any(|a| out.reads.contains(a))); + let read_there = ob != b + && other + .insts + .iter() + .any(|inst| inst.reads.iter().any(|(_, v)| out.reads.contains(v))); + if carried || read_there { + return None; + } + } + Some(out) + } + /// Consecutive dwords of one scalar load. fn loaded(&self, words: &[Term]) -> Option<Source> { let Term::Value(v0) = words[0] else { @@ -3382,6 +3595,138 @@ pub(crate) mod tests { assert_eq!(r.waterfall.loads, [load]); } + /// [`WATERFALL_INDEXED_WAVE32`] as a wave of 64 runs it: EXEC saved + /// and the lanes still waiting kept in SGPR pairs, the retry + /// `s_andn2_wrexec_b64`. + fn waterfall_indexed_wave64() -> Vec<u32> { + let mut w = WATERFALL_INDEXED_WAVE32.to_vec(); + for (from, to) in [ + (0xBE97_037E, 0xBE96_047E), // s_mov_b64 s[22:23], exec + (0xBE95_037E, 0xBE98_047E), // s_mov_b64 s[24:25], exec + (0xBE95_4715, 0xBE98_3A18), // s_andn2_wrexec_b64 s[24:25], s[24:25] + (0xBEFE_0317, 0xBEFE_0416), // s_mov_b64 exec, s[22:23] + ] { + let at = word_at(&w, from); + w[at] = to; + } + w + } + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_is_one_in_a_wave_of_64() { + let r = waterfall(&waterfall_indexed_wave64(), true).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Loaded { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + assert_eq!(r.waterfall.compares.len(), 1); + assert_eq!(r.waterfall.reads.len(), 1); + assert_eq!(r.waterfall.loads, [load]); + } + + /// [`Tracer::waterfall_shape`] on the one loop of `words`, with what + /// [`track`] would hand it: the loop's table loads, its first-lane reads + /// and its buffer and image accesses. + fn by_shape(words: &[u32], wave64: bool) -> Option<Waterfall> { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, wave64, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + let lanes = lanes(&p); + let t = Tracer::new(&p, &layout, HwStage::Cs, lanes.as_ref()).unwrap(); + let b = (0..p.blocks.len()) + .find(|&b| matches!(p.blocks[b].exit, Exit::Branch { taken, .. } if taken == b)) + .unwrap(); + let insts = &p.blocks[b].insts; + let loads: Vec<Site> = (0..insts.len()) + .filter(|&i| insts[i].name().starts_with("s_load_")) + .map(|i| (b, i)) + .collect(); + let reads: Vec<Value> = insts + .iter() + .filter(|i| i.name() == "v_readfirstlane_b32") + .filter_map(|i| i.writes.first().map(|w| w.1)) + .collect(); + let accesses: Vec<usize> = (0..insts.len()) + .filter(|&i| { + matches!( + insts[i].fields, + Fields::Buffer { .. } | Fields::Image { .. } + ) + }) + .collect(); + t.waterfall_shape(b, &accesses, &reads, &loads) + } + + /// [`WATERFALL_INDEXED_WAVE32`] or [`waterfall_indexed_wave64`] with + /// words replaced. + fn indexed_with(wave64: bool, changes: &[(u32, u32)]) -> Vec<u32> { + let mut w = if wave64 { + waterfall_indexed_wave64() + } else { + WATERFALL_INDEXED_WAVE32.to_vec() + }; + for &(from, to) in changes { + let at = word_at(&w, from); + w[at] = to; + } + w + } + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_holds_by_its_shape() { + for wave64 in [false, true] { + let shape = by_shape(&indexed_with(wave64, &[]), wave64) + .unwrap_or_else(|| panic!("wave64 {wave64}")); + assert_eq!(shape.compares.len(), 1, "wave64 {wave64}"); + assert_eq!(shape.reads.len(), 1, "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_loop_with_other_work_in_it_is_none_by_shape() { + for wave64 in [false, true] { + // s_waitcnt vmcnt(0) in the loop becomes v_mov_b32 v20, v7. + let words = indexed_with(wave64, &[(0xBF8C_3F70, 0x7E28_0307)]); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_comparing_another_lane_value_is_none_by_shape() { + for wave64 in [false, true] { + // v_cmpx_eq_u32 exec, s20, v0: the lane's index, not the offset + // the first lane's was read from (v7). + let words = indexed_with(wave64, &[(0x7DA4_0E14, 0x7DA4_0014)]); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + + #[test] + fn a_waterfall_whose_lanes_to_do_are_not_exec_is_none_by_shape() { + // The mask of lanes still to do starts as every lane, not EXEC. + let words = indexed_with(false, &[(0xBE95_037E, 0xBE95_03C1)]); // s_mov_b32 s21, -1 + assert!(by_shape(&words, false).is_none()); + let words = indexed_with(true, &[(0xBE98_047E, 0xBE98_04C1)]); // s_mov_b64 s[24:25], -1 + assert!(by_shape(&words, true).is_none()); + } + + #[test] + fn a_first_lane_offset_read_after_its_loop_is_none_by_shape() { + for wave64 in [false, true] { + // The store after the loop becomes v_mov_b32 v20, s20 (the + // first lane's offset of the last pass) and s_nop. + let words = indexed_with( + wave64, + &[(0xE070_1000, 0x7E28_0214), (0x800A_0C10, 0xBF80_0000)], + ); + assert!(by_shape(&words, wave64).is_none(), "wave64 {wave64}"); + } + } + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the From 0fb1e38eeea8735d8e9889af5ccd825f07908e4c Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 04:37:06 -0500 Subject: [PATCH 28/57] Write watch: a write fault asks about its one page, not about the region around it A write fault of the title's on a block that another of its threads has just opened, or is opening, asks whether the page is writable by now. It asked with `VirtualQuery`, which answers for the whole run of pages around an address that are alike and walks to the end of it: for a view of hundreds of megabytes hundreds of microseconds, with the address space held against every change of protection meanwhile. `writable` now asks about the one page (`QueryWorkingSetEx`), and about the region only where the system does not have the page in memory. `VICTORY_PAGE_ASK=0`: the region, as before. Measured by turns in one run (prologue's cell, RTX 3090 Ti, Ryzen 9 9950X3D, Series S profile, 12 seconds a turn), per frame: 170 to 185 questions about regions, 15.5 to 17.3 ms of the title's threads' time, become 415 to 567 about pages (the wait for a block being opened asks more often in its 100 microseconds), 2.8 to 3.3 ms. The frame itself did not move by more than two runs differ by (26.80 and 26.70 ms): the title's own threads, the thread that prepares submissions and the card each take about that long there. AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/watch.rs | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index ab2e9d763..d941e2fe0 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -3219,11 +3219,45 @@ pub(crate) fn install() { }); } +/// The protection of the one page `at` lies in, where the system has that +/// page in memory (`None`: it has not, or would not say). +/// +/// `VirtualQuery` answers for the whole run of pages around an address that +/// are alike, and walks to the end of it to say how long it is: for a view of +/// hundreds of megabytes whose blocks are all read-only, hundreds of +/// microseconds with the address space held against every change of +/// protection. A write fault of the title's on a block that another of its +/// threads is opening asked so ([`writable`]): 91 such questions a frame of +/// 245 microseconds each, 22 ms a frame of the title's threads' time, and the +/// openings themselves (a change of protection each) 235 microseconds behind +/// them; 3.2 ms of every frame's chain (a timeline of the prologue's cell at +/// 38 frames a second, RTX 3090 Ti, Ryzen 9 9950X3D). This asks about one +/// page and walks nothing. `VICTORY_PAGE_ASK=0`: the region, as before. +fn page_protection(at: usize) -> Option<u32> { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if !crate::toggled!("VICTORY_PAGE_ASK") { + return None; + } + // SAFETY: plain data, the address asked about in it. + let mut info: PSAPI_WORKING_SET_EX_INFORMATION = unsafe { std::mem::zeroed() }; + info.VirtualAddress = at as *mut _; + // SAFETY: our own process; an array of one record of that size. + let ok = unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), std::ptr::from_mut(&mut info).cast(), size_of_val(&info) as u32) } != 0; + // SAFETY: every form of the answer is these bits. + let flags = unsafe { info.VirtualAttributes.Flags }; + // Bit 0: the page is in memory; bits 4 to 14: its protection then. + (ok && flags & 1 != 0).then(|| ((flags >> 4) & 0x7ff) as u32) +} + /// Whether `at` is committed read-write memory now. fn writable(at: usize) -> bool { use windows_sys::Win32::System::Memory::{ MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery, }; + if let Some(protection) = page_protection(at) { + return protection == PAGE_READWRITE; + } // 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. From 38b768c71eabd92a83f7c58b9ac4db7a198dfab2 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 04:37:25 -0500 Subject: [PATCH 29/57] Play: no loop that keeps the card awake, write faults without the lock, stores beside the guards, processors of our own, the title's rate 60 Five settings of `victory play`, each measured in the prologue's cell (Series S profile, DLSS off, RTX 3090 Ti, Ryzen 9 9950X3D, Windows 11; medians of five-second readings over four minutes, or turns of 12 seconds in one run where it says "by turns"): - `VICTORY_CARD_AWAKE=0` (was 1): 30.7 -> 31.7 frames a second; the card 86 % busy with the loop and 76 % without. - `VICTORY_FAULT_UNLOCKED=1`: by turns 29.87 -> 28.97 ms a frame. Before, five to eight of the title's threads at a time stood 2 ms and more in their write faults behind the write watch's one lock. - `VICTORY_STORE_BESIDE=1`: by turns 32.60 -> 31.17 ms on the build before these commits, 30.47 -> 30.07 ms after the first three. - `VICTORY_OWN_CPUS=auto`: the commit before the last two. - `VICTORY_FRAME_INTERVAL_MS=16.667`: the title is given the rate 60 in place of its 30. With 30 it steps 1/30 s a frame however short the frame, and ran fast above 30 frames a second: one loop of an idle animation took 6.07 s at 36.8 frames a second, 7.43 s with this at 36.9, and 7.33 s at 30. `--fps` under 60 gives the title that rate (30: its own). With all commits since the merge of a4d05e7 and these settings the cell runs at 37.1 frames a second where it ran at 30.7 (the same 4,440 to 4,470 draws a frame in both; the last four screenshots of both runs compared in 48 cells: none differs by more than 6 of 255). With DLSS Quality and FSR 3 frame generation: 35.3 rendered, 72 shown. On a shared save in the first house the build ran at about 30 frames a second in views of 5,300 to 6,500 draws a frame. There is no like-for-like figure for that scene: the build before ran at 23 in a view of 7,000 draws and 26 at 5,150, and the scripted key presses did not lead to the same situation in any two runs. Tried and left out, for no gain measured: asking the guards and the kernel about a submission's memory on a kept thread beside its start, the pages' last writes read with no lock, a wait left out at a barrier group with no shader since the one before (67 of 694 a frame), `VICTORY_GUARD_HOT`. AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- apps/victory/src/play.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index db9b5f4de..a9b163af0 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -62,7 +62,9 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_CARD_REHASH_RUNS", "1"), ("VICTORY_JOIN_COPIES", "1"), ("VICTORY_CARD_STEPS", "2"), - ("VICTORY_CARD_AWAKE", "1"), + // Neo: no loop that keeps the card's clocks up. It took a tenth of the card (RTX 3090 Ti, the + // prologue's cell: the card 86 % busy with it and 76 % without, 30.7 and 31.7 frames a second). + ("VICTORY_CARD_AWAKE", "0"), ("VICTORY_CARD_BUFFERS_MIN_KB", "64"), ("VICTORY_INDIRECT_WINDOW", "1"), ("VICTORY_INDIRECT_BATCH", "2"), @@ -108,6 +110,17 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_LEAVE_OUT", "02384a60fda6f2d0,731a39171b568298"), // Pipelines the title makes are written down, for `victory warm` ("VICTORY_PIPELINE_BOOK", "1"), + // Neo, measured in the prologue's cell on an RTX 3090 Ti and a Ryzen 9 9950X3D (README): + // the title's write faults open their block without the write watch's one lock, and a + // store that faults is done beside the guard (one that changes nothing is left out) + ("VICTORY_FAULT_UNLOCKED", "1"), + ("VICTORY_STORE_BESIDE", "1"), + // On a processor of two dies the layer's own threads keep to the die the title does not use + ("VICTORY_OWN_CPUS", "auto"), + // The title's own rate is 60, not 30: above 30 frames a second it would otherwise step + // 1/30 s a frame and run fast (the same loop of an idle animation 6.07 s at 36.8 frames a + // second without, 7.43 s with; 7.33 s at 30) + ("VICTORY_FRAME_INTERVAL_MS", "16.667"), ]; /// Path settings a start keeps from its surroundings; every other @@ -333,6 +346,11 @@ fn settings(o: &Play, menu: &[(String, String)], streamline: Option<&Path>) -> ( } let mut set = |k: &str, v: &str| drop(s.insert(k.to_owned(), v.to_owned())); set("VICTORY_FRAME_INTERVAL_US", &(1_000_000.0 / f64::from(fps)).round().to_string()); + // The title's own rate with it (`VICTORY_FRAME_INTERVAL_MS`, 60 in `SETTINGS`): a cap under 60 + // is the rate the title is given too, 30 its own. + if (1..60).contains(&fps) { + set("VICTORY_FRAME_INTERVAL_MS", &format!("{:.3}", 1000.0 / f64::from(fps))); + } for (k, v) in menu.iter().filter(|(k, _)| !k.starts_with("VICTORY_MENU_")) { if v.is_empty() { s.remove(k); From 59a41b733c460bcb5ba934f6b7fbd6318af4cd8f Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 04:52:18 -0500 Subject: [PATCH 30/57] README: the build of 28 November (37 frames a second in the cell at the game's own speed, 72 shown; keyboard and mouse; what was changed and what was tried) AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 137 +++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 109 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 2d79851b9..cbbd0afea 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # VIctory-Neo **The Xbox Series build of the title, running on a Windows PC from your own -files: about 31 frames a second, and 53 to 132 on screen with frame generation.** +files: about 37 frames a second at the game's own speed, and 72 on screen with +frame generation.** VIctory-Neo is a build of [VIctory](https://github.com/Marvisak/VIctory), the compatibility layer that runs an Xbox Series title natively on Windows. The @@ -21,9 +22,15 @@ shows it), medians over the 5-second readings of a run, hands off. | Scene | Profile | Frames a second | |---|---|---| -| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **31** (readings 27 to 33) | -| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **27 rendered, 53 shown** (F3: `FPS: 26.4 FG: 52.8`) | -| the same | Series S, DLSS Quality and DLSS frame generation through MFG Unlocker (a mod, below), 2x / 3x / 4x / 6x | 24 / 23 / 22.5 / 22 rendered; **48 / 72 / 92 / 132 shown** (F3 at 6x: `FPS: 21.5 FG: 129.0`) | +| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **37** (readings 36 to 38; 30.7 on the build before, the same draws) | +| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **35 rendered, 72 shown** (27 and 53 before) | +| The first house, from a shared save (views of 5,300 to 6,500 draws a frame) | Series S | about 30 | + +Measured on the build before (27 November), not again since: + +| Scene | Profile | Frames a second | +|---|---|---| +| Prologue, the cell | Series S, DLSS Quality and DLSS frame generation through MFG Unlocker (a mod, below), 2x / 3x / 4x / 6x | 24 / 23 / 22.5 / 22 rendered; 48 / 72 / 92 / 132 shown | | Opening cutscene | Series S | about 28 on average, 20 to 37 by shot | | Prologue, the cell | Series X, scene 1920x1080, 2560x1440 out | 26 | | Prologue, the cell | Series X, native 2560x1440 | 23 | @@ -32,10 +39,13 @@ shows it), medians over the 5-second readings of a run, hands off. cutscene play in order, and the prologue's first room stands. - Characters, hair, clothes and their prints, textures, sky and sun are drawn. - No crash and no lost graphics device in the runs these numbers come from - (a dozen, 5 to 10 minutes each, standing in the cell). Longer sessions, - play with a pad or keyboard and mouse, and anything past the prologue are - **not measured here yet**; the projects this is built on have played to the - first boat mission (see [Built on](#built-on)). + (some forty on 28 November, 4 to 5 minutes each, hands off; one more, with + the tree's sampling profiler switched on, ended in that profiler). Keyboard and + mouse were checked by a script in one scene (the mouse turns the camera, W + walks), and a shared save from after the prologue loads and plays in the + first house. Long sessions and play by hand are **not measured here yet**; + the projects this is built on have played to the first boat mission (see + [Built on](#built-on)). On the same PC, fxceless/victory-fork's `main` of the same day runs the same cell at 17 to 19 frames a second. @@ -49,17 +59,25 @@ cell at 17 to 19 frames a second. rays: a few frames a second and a broken picture. - **Haze through windows.** Bright views through glass (the cell's window) are smeared; cause not found yet. -- **A dark patch on a wall, in some runs.** In about one run in ten, the +- **A dark patch on a wall, in some runs.** In about one run in eight (on + 28 November 4 of some 35, on builds with and without the changes below), the wall to the left of the character in the cell shows a dark patch with blocky edges for the whole run; cause not found yet. +- **White specks, and bright blotches on floors,** in the first house (on + the build before too). - **Hitches** when the title streams a new scene in, and during the first launches while shaders are translated and pipelines made (see below). -- **Above 30 frames a second the game runs a little fast.** The title steps - its world at least 1/30 s a frame. `--fps 30` holds it at its own rate. - (Frames made by frame generation do not count: 27 rendered is 27.) +- **Rendered frames stop at 60 a second.** The title steps its world at + least one frame of its own rate, 30, however short the frame was, so above + 30 it ran fast. `victory play` now gives it the rate 60 (as its own code + takes it; `VICTORY_FRAME_INTERVAL_MS=16.667`), and the game keeps its + speed up to 60 rendered frames a second: the same loop of an idle + animation took 7.43 s at 36.9 frames a second, 7.33 s at 30, and 6.07 s at + 36.8 without the setting. `--fps 30` is the title's own rate. (Frames made + by frame generation do not count.) - **Frame generation adds latency** (about one rendered frame), as it does in any game, and its in-between frames can smear fast motion. -- **Memory.** On this PC it takes up to 43 GB of RAM, with a 24 GB card that +- **Memory.** On this PC it takes 36 to 42 GB of RAM, with a 24 GB card that it fills with textures. Close what you can. foxhound measures 20 GB in use (28 GB committed) on a 32 GB PC with a 12 GB card. @@ -111,7 +129,7 @@ start. **The trade-off:** DLSS frame generation costs this card more than FSR 3 does (22 to 24 real frames a second instead of 27), and frame generation never makes the game answer faster: at 4x you see 92 frames a second, but the game still reacts at about 22. For the quickest response -use FSR 3 at 2x, or no frame generation (31). Keep the shown rate under your +use FSR 3 at 2x, or no frame generation (37). Keep the shown rate under your monitor's refresh rate. - **The first launches are slow, and that is expected.** The first start @@ -121,7 +139,7 @@ monitor's refresh rate. what it needed, so it gets smoother over the first two or three. - **The first start asks once whether to download NVIDIA's DLSS files** (RTX cards). Either way works: in the cell DLSS Quality measured 31.4 and - Performance 31.7 against 30.9 without it. + Performance 31.7 against 30.9 without it (on the build of 27 November). The card's time there goes to the number of commands, not to pixels. - **Known crash, with a way round it:** with AMD's FSR 3 files fetched and `--dlss off`, the start prepares FSR 3 and the program ends during the boot @@ -137,7 +155,8 @@ Other ways to run it: |---|---| | `victory.exe play <exe>` | Series X profile at 2560x1440: sharper, slower (23 here) | | `victory.exe play <exe> --res 1080to1440` | Series X, scene at 1920x1080 (26 here) | -| `victory.exe play <exe> --series-s --fps 30` | the title's own frame rate, game speed exact | +| `victory.exe play <exe> --series-s --fps 30` | the title's own frame rate | +| `victory.exe play <exe> --series-s --set VICTORY_MOUSE_CAPTURE=1 --set VICTORY_PAD_KEYS=pc` | keyboard and mouse (below) | | `victory.exe play <exe> --series-s --set VICTORY_X=1` | add or override a switch | | `scripts\play-foxhound.ps1 -Exe <exe> -SeriesS` | the same from PowerShell, with a log file | @@ -147,10 +166,38 @@ NVIDIA's and AMD's, under their licences, fetched from their own GitHub by `victory.exe get-dlss` and `get-fsr` and never part of this repository; [docs/dlss.md](docs/dlss.md) has the details. +### Keyboard and mouse + +The title takes its camera from a controller's right stick alone. With +`--set VICTORY_MOUSE_CAPTURE=1` (or F1, MOUSE CAPTURE) the mouse is that +stick: it turns the camera, the left button is the right trigger, the right +button the left one, the middle button a press of the stick. With +`--set VICTORY_PAD_KEYS=pc` the keyboard has this layout (the names are the +Xbox buttons; what each does is the game's choice): + +| Key | Button | Key | Button | +|---|---|---|---| +| W A S D | left stick | Left Shift | A | +| Space | X | F | Y | +| R | B | Tab | LB | +| Q or E | RB | Left Ctrl | left stick's press | +| C or H | right stick's press | V | View | +| Enter | A | Backspace | B | +| Esc | Menu | arrows | D-pad | + +`VICTORY_PAD_KEYS=pc,G=Y,Space=A` changes single keys. The mouse's feel: +`VICTORY_MOUSE_LOOK_SPEED` (pixels a second that are the whole stick, 2400: +lower turns more for the same hand), `VICTORY_MOUSE_LOOK_DEADZONE` (percent, +20: raise it if slow motion does nothing), `VICTORY_MOUSE_LOOK_VERTICAL` +(percent; negative turns up and down round), `VICTORY_MOUSE_LOOK_BANK` +(milliseconds of full turning kept after a fast flick, 350), +`VICTORY_MOUSE_LOOK=0` (off). Checked by a script, not yet tuned by hand. + ## What Neo adds -Two changes on top of the tree it is built on, each measured in the game on -the PC above and sent to that project as a pull request: +Changes on top of the tree it is built on, each measured in the game on the +PC above. The first three were sent to that project as pull requests; the +others have not been sent yet: 1. **The Series S profile keeps the title's own upscaler** where no DLSS is set up. The title picks FSR 4 on a Series S; translated, that is the @@ -167,16 +214,50 @@ the PC above and sent to that project as a pull request: cache, so **the cause of the missing print here is not known yet**: the fresh cache is what fixed it, not the order. (Pull request in draft until that is tested.) -In progress, not in the build: **the console's per-lane descriptor loops run -once instead of once per distinct value** (a [pull request](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/458), -now in draft). The translator proves only some of these loops and runs the -rest as loops that cost four group barriers a pass on a card whose waves are -half as wide as the console's. A check of the loop's shape proved 32,106 -more of them, and the cell went from 31 to 32 to 33 frames a second (62 shown -with frame generation). It was taken out again because a wall in the cell -then showed a dark patch in 3 runs of 5. The same patch later turned up -without the change too (1 run of 10), so it is an older fault; whether the -change makes it more likely is being measured before it goes back in. +3. **The console's per-lane descriptor loops run once instead of once per + distinct value** (a [pull request](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/458), + in draft). The translator proves only some of these loops and runs the + rest as loops that cost four group barriers a pass on a card whose waves + are half as wide as the console's. A check of the loop's shape proves + 32,106 more of them: the title's commands take the card 24.4 ms a frame + in the cell where they took 27.6 (each command timed on its own), one + program alone 3.5 ms less. It was out of the build for a day because a + wall in the cell showed a dark patch in 3 runs of 5 with it; the patch + turns up as often without it (see above), so it is back in. +4. **The layer's threads stopped standing in each other's way** (28 + November). A timeline of the frame showed where they did: + - The eight threads that record the title's lists each lost 3.3 of the + 22 ms a frame they work waiting for one lock, to hand back objects the + title had let go of. Each now has a queue of its own. + - On a processor of two dies the title keeps its threads on one die + (its own choice of sixteen processors) and the layer's ran on both, + half the time beside the title's. They now keep to the other die + (`VICTORY_OWN_CPUS=auto`), but for the threads that only translate + ahead. + - Five to eight of the title's threads at a time stood 2 ms and more in + their write faults behind the write tracker's lock + (`VICTORY_FAULT_UNLOCKED=1`, a switch of the tree's, now on), a store + that faults is done beside the guard (`VICTORY_STORE_BESIDE=1`, the + same), and a fault asks about its one page where it asked about a + region of hundreds of megabytes (17 to 3 ms a frame of the title's + threads' time). + - The loop that kept the card's clocks up took a tenth of the card here + (`VICTORY_CARD_AWAKE=0`). + Together with the loops above: 30.7 to 37.1 frames a second in the cell, + the same draws, the picture the same within what two runs differ by. + What limits it now, each at about 25 ms a frame: the title's own main + thread (22 ms of its own work), the layer's thread that prepares the + card's work (24 ms), and the card (23 ms). +5. **The game keeps its speed above 30 frames a second**, and **keyboard and + mouse** (both above). + +Tried on 28 November and left out, for no gain measured: asking the write +tracker about a submission's memory on a helper thread beside its start +(view memory and the kernel's part), reading the pages' last writes with no +lock, leaving out a barrier's wait where no shader ran since the one before +(67 of 694 a frame), `VICTORY_GUARD_HOT`, a core of its own for the +preparing thread, more submissions joined into one (it seemed to bring the +dark patch more often: 3 runs of 5). Also in the tree, off by default: `VICTORY_GUARDS_SPIN=<microseconds>`, a shorter wait on the write tracker's lock. A profile had the thread that From 346bd2cfd733941f43d98f77c30270e0fc6462cb Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 05:52:41 -0500 Subject: [PATCH 31/57] Cores: with processors of our own, the threads that translate lists keep to them too, and are half as many The threads that translate the title's lists and make records ran on every processor while the rest of ours kept to their own die (the commit before last on this file). A timeline of that build showed the title's main thread taking turns with them on its two processors: half of what ran there was ours, and that thread's own work is the longest part of a frame's chain (22 of 27 ms in the prologue's cell). They keep to our processors now (`VICTORY_OWN_CPUS_MANY=1`: every processor, as before), and the lists are translated by a quarter as many threads as there are such processors, two to eight, where a start does not say (`VICTORY_THIN_THREADS`): eight of them beside the rest of ours were more threads than one die runs at a time. Measured in the prologue's cell (Ryzen 9 9950X3D, RTX 3090 Ti, Series S profile, DLSS off; medians of five-second readings after the first half minute, and the lowest of them), all with our threads on processors 16-31: - list threads on every processor, eight: 37.4, lowest 36.2; - on 13-31 or 8-31, eight: 37.6 and 37.5; - on 16-31: eight 38.4 (lowest 34.3), six 39.0 (36.4), five 38.8 (37.5), four 39.4 (38.2); six with six helpers for refreshes 38.8 (33.0); four helpers with eight list threads 38.2. At the new defaults, two runs: 39.1 and 38.7 (lowest 36.4 and 37.4), where the build before this work had 30.7; the thread that prepares submissions works 22.8 ms a frame where it worked 24.4. With DLSS Quality and FSR 3 frame generation: 36.4 rendered, 73 shown. AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/cores.rs | 67 +++++++++++++++++++++-------- crates/victory-gpu/src/list/thin.rs | 3 +- 2 files changed, 51 insertions(+), 19 deletions(-) diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs index 414380db6..301846c28 100644 --- a/crates/victory-gpu/src/cores.rs +++ b/crates/victory-gpu/src/cores.rs @@ -86,10 +86,46 @@ fn own_of(asked: &str, all: &[Cpu]) -> Option<Vec<u32>> { /// Whether the many threads whose work is ahead of what a frame waits for /// (lists translated, records made) run on every processor while the others -/// of ours keep to their own ([`keep_own_threads`]). +/// of ours keep to their own ([`keep_own_threads`]; `VICTORY_OWN_CPUS_MANY=1`, +/// off by default: they keep to ours too, see there). fn roaming() -> bool { static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_OWN_CPUS").is_some() && std::env::var_os("VICTORY_OWN_CPUS_MANY").is_none_or(|v| v != "0")) + *ON.get_or_init(|| std::env::var_os("VICTORY_OWN_CPUS").is_some() && std::env::var_os("VICTORY_OWN_CPUS_MANY").is_some_and(|v| v == "1")) +} + +/// The processors our own threads keep to, as the start names them +/// ([`keep_own_threads`]); `None`: none named. +fn own() -> Option<&'static Vec<u32>> { + static OWN: std::sync::OnceLock<Option<Vec<u32>>> = std::sync::OnceLock::new(); + OWN.get_or_init(|| { + let asked = std::env::var("VICTORY_OWN_CPUS").ok()?; + let all = cpus(); + let own = own_of(&asked, &all); + match &own { + Some(own) => tracing::info!(asked, processors = own.len(), of = all.len(), "our own threads are kept on these processors (VICTORY_OWN_CPUS)"), + None => tracing::warn!(asked, of = all.len(), "VICTORY_OWN_CPUS: no processors of that name, or all of them: left as it is"), + } + own + }) + .as_ref() +} + +/// How many threads translate the title's lists where the start does not +/// say (`VICTORY_THIN_THREADS`): eight, or with processors of our own a +/// quarter as many as those, two to eight. +/// +/// Eight on sixteen processors of our own, beside the thread that prepares +/// submissions, its eight helpers and the pools, were more threads than those +/// processors run at a time: the usual frame was shorter than with the +/// threads on every processor, and one frame in ten far longer. With four, +/// five and six in their place (the prologue's cell, Ryzen 9 9950X3D, RTX +/// 3090 Ti, Series S profile, DLSS off, medians of five-second readings and +/// the lowest of them): 39.4 and 38.2 frames a second, 38.8 and 37.5, 39.0 +/// and 36.4; with eight 38.4 and 34.3; with eight on every processor 37.4 and +/// 36.2. The thread that prepares submissions worked 22.8 ms a frame with +/// four where it worked 24.4. +pub(crate) fn list_threads() -> usize { + own().map_or(8, |own| (own.len() / 4).clamp(2, 8)) } /// The processors our own threads run on, where a start names them @@ -107,22 +143,19 @@ fn roaming() -> bool { /// process's default sets, the choice holds for every thread that has neither /// an affinity nor sets of its own: ours, the drivers', and not the title's. /// +/// The many threads that translate lists and make records keep to them too +/// (`VICTORY_OWN_CPUS_MANY=1`: they run on every processor). On the title's +/// die they took turns with the title's main thread on its two processors +/// (half of what ran there in a timeline was ours), and that thread's own +/// work is the longest part of a frame's chain, 22 of 27 ms. Fewer of them +/// are made in their place ([`list_threads`]). +/// /// `VICTORY_OWN_CPUS_ON=0` leaves them as they were (and `VICTORY_AB` can /// flip it while the title runs). pub(crate) fn keep_own_threads() { use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; use windows_sys::Win32::System::Threading::{GetCurrentProcess, SetProcessDefaultCpuSets}; - static OWN: std::sync::OnceLock<Option<Vec<u32>>> = std::sync::OnceLock::new(); - let Some(own) = OWN.get_or_init(|| { - let asked = std::env::var("VICTORY_OWN_CPUS").ok()?; - let all = cpus(); - let own = own_of(&asked, &all); - match &own { - Some(own) => tracing::info!(asked, processors = own.len(), of = all.len(), "our own threads are kept on these processors (VICTORY_OWN_CPUS)"), - None => tracing::warn!(asked, of = all.len(), "VICTORY_OWN_CPUS: no processors of that name, or all of them: left as it is"), - } - own - }) else { + let Some(own) = own() else { return; }; // 0: not asked yet; 1: kept; 2: let go. @@ -203,11 +236,9 @@ fn ask(what: &str, from: u32) { let set = unsafe { SetThreadPriority(GetCurrentThread(), priority) } != 0; tracing::debug!(what, priority, set, "the thread's priority (VICTORY_HELPER_PRIORITY)"); } - // With processors of our own (`keep_own_threads`): the many threads whose - // work is ahead of what a frame waits for run on any (`VICTORY_OWN_CPUS_MANY=0`: - // on ours too). They are most of our work, and with them our processors - // were more threads than they run at a time: the usual frame 26.5 ms - // where it was 29.1, and one frame in ten 41 ms where it was 34. + // With processors of our own (`keep_own_threads`) and + // `VICTORY_OWN_CPUS_MANY=1`: the many threads whose work is ahead of what + // a frame waits for run on any, the title's too. if from == 3 && roaming() { static ALL: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new(); let all = ALL.get_or_init(|| cpus().iter().map(|c| c.id).collect()); diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index e2371c308..47d034877 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -300,7 +300,8 @@ fn back_list(kind: u32) -> This { } fn start() { - let threads = std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8usize).clamp(1, 32); + let threads = + std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or_else(crate::cores::list_threads).clamp(1, 32); for i in 0..threads { let worker = move || { crate::cores::keep_many_on_fast_cores("victory-list"); From c79bb637c422227e47991a141f098bbd170f6713 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 05:52:41 -0500 Subject: [PATCH 32/57] README: 39 frames a second in the cell with the layer's threads on their own die (36 rendered and 73 shown with frame generation) AI-assisted (Claude Code, Claude Fable 5.2). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index cbbd0afea..dbc91be08 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # VIctory-Neo **The Xbox Series build of the title, running on a Windows PC from your own -files: about 37 frames a second at the game's own speed, and 72 on screen with +files: about 39 frames a second at the game's own speed, and 73 on screen with frame generation.** VIctory-Neo is a build of [VIctory](https://github.com/Marvisak/VIctory), the @@ -22,8 +22,8 @@ shows it), medians over the 5-second readings of a run, hands off. | Scene | Profile | Frames a second | |---|---|---| -| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **37** (readings 36 to 38; 30.7 on the build before, the same draws) | -| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **35 rendered, 72 shown** (27 and 53 before) | +| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **39** (two runs: 39.1 and 38.7, readings 36.4 to 40.3; 30.7 on the build before, the same draws) | +| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **36 rendered, 73 shown** (27 and 53 before) | | The first house, from a shared save (views of 5,300 to 6,500 draws a frame) | Series S | about 30 | Measured on the build before (27 November), not again since: @@ -39,7 +39,7 @@ Measured on the build before (27 November), not again since: cutscene play in order, and the prologue's first room stands. - Characters, hair, clothes and their prints, textures, sky and sun are drawn. - No crash and no lost graphics device in the runs these numbers come from - (some forty on 28 November, 4 to 5 minutes each, hands off; one more, with + (some sixty on 28 November, 4 to 5 minutes each, hands off; one more, with the tree's sampling profiler switched on, ended in that profiler). Keyboard and mouse were checked by a script in one scene (the mouse turns the camera, W walks), and a shared save from after the prologue loads and plays in the @@ -60,7 +60,7 @@ cell at 17 to 19 frames a second. - **Haze through windows.** Bright views through glass (the cell's window) are smeared; cause not found yet. - **A dark patch on a wall, in some runs.** In about one run in eight (on - 28 November 4 of some 35, on builds with and without the changes below), the + 28 November 7 of some 55, on builds with and without the changes below), the wall to the left of the character in the cell shows a dark patch with blocky edges for the whole run; cause not found yet. - **White specks, and bright blotches on floors,** in the first house (on @@ -73,7 +73,7 @@ cell at 17 to 19 frames a second. takes it; `VICTORY_FRAME_INTERVAL_MS=16.667`), and the game keeps its speed up to 60 rendered frames a second: the same loop of an idle animation took 7.43 s at 36.9 frames a second, 7.33 s at 30, and 6.07 s at - 36.8 without the setting. `--fps 30` is the title's own rate. (Frames made + 36.8 without the setting (measured on the build of the morning, at 37). `--fps 30` is the title's own rate. (Frames made by frame generation do not count.) - **Frame generation adds latency** (about one rendered frame), as it does in any game, and its in-between frames can smear fast motion. @@ -129,7 +129,7 @@ start. **The trade-off:** DLSS frame generation costs this card more than FSR 3 does (22 to 24 real frames a second instead of 27), and frame generation never makes the game answer faster: at 4x you see 92 frames a second, but the game still reacts at about 22. For the quickest response -use FSR 3 at 2x, or no frame generation (37). Keep the shown rate under your +use FSR 3 at 2x, or no frame generation (39). Keep the shown rate under your monitor's refresh rate. - **The first launches are slow, and that is expected.** The first start @@ -231,9 +231,10 @@ others have not been sent yet: title had let go of. Each now has a queue of its own. - On a processor of two dies the title keeps its threads on one die (its own choice of sixteen processors) and the layer's ran on both, - half the time beside the title's. They now keep to the other die - (`VICTORY_OWN_CPUS=auto`), but for the threads that only translate - ahead. + half the time beside the title's, whose main thread's own work is the + longest part of a frame. They now keep to the other die + (`VICTORY_OWN_CPUS=auto`), and the lists are translated by four + threads there where eight ran everywhere. - Five to eight of the title's threads at a time stood 2 ms and more in their write faults behind the write tracker's lock (`VICTORY_FAULT_UNLOCKED=1`, a switch of the tree's, now on), a store @@ -243,11 +244,11 @@ others have not been sent yet: threads' time). - The loop that kept the card's clocks up took a tenth of the card here (`VICTORY_CARD_AWAKE=0`). - Together with the loops above: 30.7 to 37.1 frames a second in the cell, + Together with the loops above: 30.7 to 38.9 frames a second in the cell, the same draws, the picture the same within what two runs differ by. What limits it now, each at about 25 ms a frame: the title's own main thread (22 ms of its own work), the layer's thread that prepares the - card's work (24 ms), and the card (23 ms). + card's work (23 ms), and the card (23 ms). 5. **The game keeps its speed above 30 frames a second**, and **keyboard and mouse** (both above). @@ -256,8 +257,8 @@ tracker about a submission's memory on a helper thread beside its start (view memory and the kernel's part), reading the pages' last writes with no lock, leaving out a barrier's wait where no shader ran since the one before (67 of 694 a frame), `VICTORY_GUARD_HOT`, a core of its own for the -preparing thread, more submissions joined into one (it seemed to bring the -dark patch more often: 3 runs of 5). +preparing thread, two frames in the line in place of one, more submissions +joined into one (it seemed to bring the dark patch more often: 3 runs of 5). Also in the tree, off by default: `VICTORY_GUARDS_SPIN=<microseconds>`, a shorter wait on the write tracker's lock. A profile had the thread that From b71075eae1033772f6f2c9fe710b2cf7623dd77a Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 08:18:56 -0500 Subject: [PATCH 33/57] Cores: VICTORY_TITLE_CPUS says where the title's threads run The title keeps each of its threads to processors it names by number, the console's sixteen (SetThreadGroupAffinity). On a PC those are whichever the system numbers 0 to 15: on a Ryzen 9 9950X3D the die with the large cache. VICTORY_TITLE_CPUS=<first>-<last> moves what it asks for to those processors, =even gives each of its processors a core of its own (processor 2n for its n), =all leaves its threads where the system puts them. Unset: as the title asks. For measuring where the title's and the layer's threads should be; not a default. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-hle/src/modules/kernel.rs | 123 +++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 4fb8e4b98..9eb2eda10 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -438,6 +438,108 @@ pub extern "system" fn SetThreadPriority(thread: *mut c_void, priority: i32) -> unsafe { windows_sys::Win32::System::Threading::SetThreadPriority(thread, priority) } } +/// `GROUP_AFFINITY`: processors of one group, a bit each. +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct GroupAffinity { + mask: usize, + group: u16, + reserved: [u16; 3], +} + +/// Where the title's threads run, if the start says so. +#[derive(Clone, Copy, PartialEq, Debug)] +enum TitleCpus { + /// On the processors the title asks for. + AsAsked, + /// On any: what the title asks for is not passed on. + All, + /// On these (first, how many): the title's processor `n` is the `n`th of them. + From(u32, u32), + /// The title's processor `n` is processor `2n`: where two processors + /// next to each other are one core's two threads, a core to each. + Even, +} + +/// `VICTORY_TITLE_CPUS=<first>-<last>` or `all`; anything else: as asked. +fn parse_title_cpus(set: &str) -> TitleCpus { + let set = set.trim(); + if set == "all" { + return TitleCpus::All; + } + if set == "even" { + return TitleCpus::Even; + } + let range = set.split_once('-').and_then(|(a, b)| Some((a.trim().parse::<u32>().ok()?, b.trim().parse::<u32>().ok()?))); + match range { + Some((first, last)) if first <= last && last < usize::BITS => TitleCpus::From(first, last - first + 1), + _ => TitleCpus::AsAsked, + } +} + +/// The processors `asked` for, moved to the `n` processors from `first`. +fn moved(asked: usize, first: u32, n: u32) -> usize { + (0..usize::BITS).filter(|bit| asked >> bit & 1 != 0).fold(0, |mask, bit| mask | 1 << (first + bit % n)) +} + +/// The processors `asked` for, each moved to twice its number (those past +/// half the word are left out; none left: as asked). +fn spread(asked: usize) -> usize { + let mask = (0..usize::BITS / 2).filter(|bit| asked >> bit & 1 != 0).fold(0, |mask, bit| mask | 1 << (2 * bit)); + if mask == 0 { asked } else { mask } +} + +/// The title keeps each of its threads to processors it names by number, +/// those of the console: 0 to 15. On a PC of more processors, or of two +/// kinds, those are whichever the system numbers so (on a Ryzen 9 9950X3D the +/// die with the large cache). `VICTORY_TITLE_CPUS=<first>-<last>` moves what +/// it asks for to those processors, `VICTORY_TITLE_CPUS=all` leaves its +/// threads where the system puts them, `VICTORY_TITLE_CPUS=even` gives each of +/// the title's sixteen processors a core of its own (processor `2n` for its +/// `n`); unset: as the title asks. +pub extern "system" fn SetThreadGroupAffinity(thread: *mut c_void, affinity: *const GroupAffinity, previous: *mut GroupAffinity) -> i32 { + #[cfg(windows)] + #[link(name = "kernel32")] + unsafe extern "system" { + #[link_name = "SetThreadGroupAffinity"] + fn host(thread: *mut c_void, affinity: *const GroupAffinity, previous: *mut GroupAffinity) -> i32; + } + static CPUS: std::sync::OnceLock<TitleCpus> = std::sync::OnceLock::new(); + let cpus = *CPUS.get_or_init(|| { + let asked = std::env::var("VICTORY_TITLE_CPUS").unwrap_or_default(); + let cpus = parse_title_cpus(&asked); + if cpus != TitleCpus::AsAsked { + tracing::info!(asked, ?cpus, "the title's threads do not run on the processors it asks for (VICTORY_TITLE_CPUS)"); + } + cpus + }); + if affinity.is_null() { + return 0; + } + // SAFETY: the title's record, read once. + let mut wanted = unsafe { *affinity }; + match cpus { + TitleCpus::AsAsked => {} + TitleCpus::All => { + if !previous.is_null() { + // SAFETY: the title's room for the answer. + unsafe { *previous = wanted }; + } + return 1; + } + TitleCpus::From(first, n) => wanted.mask = moved(wanted.mask, first, n), + TitleCpus::Even => wanted.mask = spread(wanted.mask), + } + #[cfg(windows)] + // SAFETY: the title's thread handle, a record of ours, the title's room for the answer. + return unsafe { host(thread, &wanted, previous) }; + #[cfg(not(windows))] + { + let _ = (thread, wanted); + 0 + } +} + pub(crate) fn module() -> HleModule { HleModule { name: "kernel", @@ -473,6 +575,7 @@ pub(crate) fn module() -> HleModule { hle_export!(TerminateProcess), hle_export!(SetUnhandledExceptionFilter), hle_export!(SetThreadPriority), + hle_export!(SetThreadGroupAffinity), ], } } @@ -687,6 +790,26 @@ mod host { mod tests { use super::*; + /// The title's processors by number, moved to those the start names. + #[test] + fn the_titles_processors_are_moved_to_those_named() { + assert_eq!(parse_title_cpus(""), TitleCpus::AsAsked); + assert_eq!(parse_title_cpus("auto"), TitleCpus::AsAsked); + assert_eq!(parse_title_cpus("9-3"), TitleCpus::AsAsked); + assert_eq!(parse_title_cpus("0-64"), TitleCpus::AsAsked); + assert_eq!(parse_title_cpus(" all "), TitleCpus::All); + assert_eq!(parse_title_cpus("16-31"), TitleCpus::From(16, 16)); + // One processor, all sixteen, and more than there is room for. + assert_eq!(moved(1 << 3, 16, 16), 1 << 19); + assert_eq!(moved(0xffff, 16, 16), 0xffff_0000); + assert_eq!(moved(0xffff, 8, 8), 0xff00); + assert_eq!(moved(0, 16, 16), 0); + assert_eq!(parse_title_cpus("even"), TitleCpus::Even); + assert_eq!(spread(0b1011), 0b100_0101); + assert_eq!(spread(0xffff), 0x5555_5555); + assert_eq!(spread(1 << 40), 1 << 40); + } + /// The title's idle and lowest threads run below normal; the others as /// it sets them. #[test] From 316a8c019d52cb65dca73aeb73eed3fa8d4416b7 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 08:19:18 -0500 Subject: [PATCH 34/57] Stand-in light: each part has a switch that VICTORY_AB can flip in a run VICTORY_AMBIENT_ON (the diffuse light), VICTORY_AMBIENT_SPECULAR_ON (the reflections) and VICTORY_AMBIENT_AIR_ON (the air), on unless 0. In a diagnostics build VICTORY_AB=<seconds>,<switch>.. turns them on and off while the title runs, so one view is seen with and without a part: the first house of a shared save starts in a room of its own choosing each time, and two runs do not show the same thing. VICTORY_AMBIENT_SPECULAR_ALPHA is read the same way (it was read from the environment at every dispatch of the miss program). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/draw.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e3a7be8bf..46d5fcaed 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3784,6 +3784,18 @@ impl State { /// (`crate::ambient`). Whether it recorded anything. fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { use crate::ambient::{AIR, DEPTH, LIGHT, MISS_DEPTH, MISS_LIGHT, MissNote, RADIANCE, Role, Views}; + // Each part has a switch of its own, on unless 0, that `VICTORY_AB` can flip while the + // title runs (diagnostics builds): one scene with and without it. The light the + // surfaces send out is kept either way. + let live = match role { + Role::Resolve => crate::toggled!("VICTORY_AMBIENT_ON"), + Role::Miss => crate::toggled!("VICTORY_AMBIENT_SPECULAR_ON"), + Role::Air => crate::toggled!("VICTORY_AMBIENT_AIR_ON"), + Role::Radiance => true, + }; + if !live { + return false; + } let Some(t) = p.stages.first().map(|s| s.translated()) else { return false; }; @@ -3810,7 +3822,7 @@ impl State { // On again by default (2026-11-27): those dark patches were water tiles the tile // list had dropped (`VICTORY_LOOPS_WAVE`), not this; without it glass in a dark room // mirrors the bright sky (run fix2, spectacles 75 s into the opening). `=0`: off. - let alpha_too = !std::env::var("VICTORY_AMBIENT_SPECULAR_ALPHA").is_ok_and(|v| v.trim() == "0"); + let alpha_too = crate::toggled!("VICTORY_AMBIENT_SPECULAR_ALPHA"); if role == Role::Miss && !(layer == crate::ambient::MISS_OPAQUE || (alpha_too && layer == crate::ambient::MISS_ALPHA)) { From a6e85c68666fed5d2bae7c6856214f6cfc17a33d Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 08:19:33 -0500 Subject: [PATCH 35/57] Stand-in light: the light of transparent surfaces and particles is bounded (VICTORY_AMBIENT_ALPHA) The title lights its transparent surfaces and particles from a volume before the eye (32x16x64, a mean and a direction a cell) that rays of its own fill: CS_GatherAlphaVBuffer, CS_ShadeAlpha, CS_VarianceFilterAlpha, CS_SpatialFilterAlpha. Without the ray-tracing structures those rays find the sky from everywhere, and in a room the dust in the air is lit as under the open sky: white specks all over the picture. VICTORY_AMBIENT_ALPHA=<multiple> bounds that volume, right after the last program that writes it, by a multiple of the light around, with the pass that bounds the air's light. Unset or 0: as the title has it. Seen in the first house of the story (a shared save, RTX 3090 Ti, Series S profile), flipped on and off in one view (VICTORY_AB with VICTORY_AMBIENT_ALPHA_ON, diagnostics build): specks without, none with, at 1 and at 4. On the deck outside that house the picture is the same with and without. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/ambient.rs | 47 +++++++++++++++++++++++++++++-- crates/victory-gpu/src/draw.rs | 18 ++++++++---- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index e7153c1b3..a050a1444 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -36,6 +36,11 @@ //! sky's light indoors too, a brown veil at sunset. `VICTORY_AMBIENT_AIR` //! bounds what the air scatters by a multiple of the light around. //! +//! Transparent surfaces and particles take their light from a volume the +//! title's rays fill: without them it holds the sky's light everywhere, and +//! the dust of a room shows as white specks. `VICTORY_AMBIENT_ALPHA` bounds +//! it as the air's ([`alpha`]). +//! //! Reflections are traced too, at half the picture's size: rays the //! title's screen-space march resolves (`CS_ResolveScreenSpace`) take the //! light seen on screen; the others go to the structures, find nothing, and @@ -68,6 +73,10 @@ pub(crate) enum Role { /// Gives the reflection rays that found nothing the sky's light /// (`CS_RayMiss`, not `CS_RayMiss_Volumetrics` nor the screen probes'). Miss, + /// Filters the light of transparent surfaces and particles, a volume + /// before the eye (`CS_SpatialFilterAlpha`, the last program that writes + /// it). + Alpha, } /// The program's part in this, by its name in the container. @@ -79,6 +88,8 @@ pub(crate) fn role(container: &[u8]) -> Option<Role> { Some(Role::Radiance) } else if has(b"CS_AccumulateLocalLightInscatteringVolume") { Some(Role::Air) + } else if has(b"CS_SpatialFilterAlpha") { + Some(Role::Alpha) } else if is_miss(container) { Some(Role::Miss) } else { @@ -102,6 +113,9 @@ pub(crate) const DEPTH: (u8, u32) = (0, 464); pub(crate) const RADIANCE: (u8, u32) = (1, 16); /// Where the light the air scatters is. pub(crate) const AIR: (u8, u32) = (1, 32); +/// Where the filter writes the light of transparent surfaces (a volume of +/// R11G11B10; its direction goes to (1, 16)). +pub(crate) const ALPHA: (u8, u32) = (1, 24); /// Where the miss program writes the reflected light (R11G11B10, half the /// picture's size) and where it reads the depth it is given (a 32-bit depth /// of the picture's size). @@ -191,6 +205,28 @@ fn air() -> f32 { }) } +/// The most light transparent surfaces and particles get from around them, +/// as a multiple of the light around (`VICTORY_AMBIENT_ALPHA=<multiple>`; +/// unset or 0: what the title has). +/// +/// The title keeps that light in a volume before the eye (32x16 cells, 64 +/// deep; a mean and a direction a cell) from rays of its own +/// (`CS_GatherAlphaVBuffer`, `CS_ShadeAlpha`, then a variance and a spatial +/// filter). Without the structures its rays find the sky from everywhere, +/// and the dust in a room's air is lit as under the open sky: white specks +/// all over the picture (the first house of the story, RTX 3090 Ti; flipped +/// on and off in one view with `VICTORY_AB`, they are there without the +/// bound and gone with it, at 1 and at 4). Under the sky the light around is +/// of the sky's order and the bound changes nothing seen (the deck outside +/// that house, the same way). +fn alpha() -> f32 { + static SET: OnceLock<f32> = OnceLock::new(); + *SET.get_or_init(|| { + let set = std::env::var("VICTORY_AMBIENT_ALPHA").unwrap_or_default(); + set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(0.0) + }) +} + /// Strength and radius of the creases' shade. fn shade() -> [f32; 2] { static SET: OnceLock<[f32; 2]> = OnceLock::new(); @@ -703,6 +739,9 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { if role == Role::Air && (constant > 0.0 || air() == 0.0) { return false; } + if role == Role::Alpha && (constant > 0.0 || alpha() == 0.0) { + return false; + } static SAID: Mutex<u32> = Mutex::new(0); { let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); @@ -723,7 +762,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[7] = views.depth_size[1]; words[8] = 0.04f32.to_bits(); words[9] = 4.0f32.to_bits(); - words[10] = air().to_bits(); + words[10] = if role == Role::Alpha { alpha() } else { air() }.to_bits(); words[11] = if once() { 1.0f32 } else { 0.0 }.to_bits(); let l = &list.list; // SAFETY: an open list with the heap of the views set; the title's @@ -748,7 +787,9 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { run(&pass.mean, 1, 1, 1); KEPT.store(true, Ordering::Relaxed); } - Role::Air => run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)), + Role::Air | Role::Alpha => { + run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)) + } Role::Resolve => { if constant == 0.0 { run(&pass.place, 8, 9, 1); @@ -798,6 +839,8 @@ mod tests { assert_eq!(role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), Some(Role::Resolve)); assert_eq!(role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), Some(Role::Radiance)); assert_eq!(role(b"CS_AccumulateLocalLightInscatteringVolume_7e2f5eef"), Some(Role::Air)); + assert_eq!(role(b"..indirect_light_probes:CS_SpatialFilterAlpha_08e7839f_Wrapped.."), Some(Role::Alpha)); + assert_eq!(role(b"..CS_VarianceFilterAlpha_b92710bc_Wrapped.."), None); assert_eq!(role(b"CS_TemporalResolve"), None); assert_eq!(role(b"..CS_RayMiss_de6b91a6_Wrapped.."), Some(Role::Miss)); assert_eq!(role(b"..CS_RayMiss_Volumetrics_3c5d8c00_Wrapped.."), None); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 46d5fcaed..82b2c1914 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3783,7 +3783,7 @@ impl State { /// The stand-in for the indirect light after a dispatch of `p` /// (`crate::ambient`). Whether it recorded anything. fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { - use crate::ambient::{AIR, DEPTH, LIGHT, MISS_DEPTH, MISS_LIGHT, MissNote, RADIANCE, Role, Views}; + use crate::ambient::{AIR, ALPHA, DEPTH, LIGHT, MISS_DEPTH, MISS_LIGHT, MissNote, RADIANCE, Role, Views}; // Each part has a switch of its own, on unless 0, that `VICTORY_AB` can flip while the // title runs (diagnostics builds): one scene with and without it. The light the // surfaces send out is kept either way. @@ -3791,6 +3791,7 @@ impl State { Role::Resolve => crate::toggled!("VICTORY_AMBIENT_ON"), Role::Miss => crate::toggled!("VICTORY_AMBIENT_SPECULAR_ON"), Role::Air => crate::toggled!("VICTORY_AMBIENT_AIR_ON"), + Role::Alpha => crate::toggled!("VICTORY_AMBIENT_ALPHA_ON"), Role::Radiance => true, }; if !live { @@ -3862,6 +3863,7 @@ impl State { Role::Resolve => LIGHT, Role::Radiance => RADIANCE, Role::Air => AIR, + Role::Alpha => ALPHA, Role::Miss => MISS_LIGHT, }; // Variants of the miss program bind the rays' image and the depth at @@ -4020,12 +4022,14 @@ impl State { } plain }), - Role::Radiance | Role::Air => image, + Role::Radiance | Role::Air | Role::Alpha => image, }; let (Some((of, image)), Some((seen, depth))) = (image, depth) else { once!(?role, "no stand-in for the indirect light: other tables"); if role == Role::Miss { crate::ambient::note_miss(MissNote::NotReady); + } + if matches!(role, Role::Miss | Role::Alpha) { // Once per program: what its tables hold, so one run names // the place of the rays' image and of the depth. static SEEN: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); @@ -4082,8 +4086,8 @@ impl State { } _ => (seen.Width, seen.Height) == (of.Width, of.Height), }; - if of.Format.0 != format || !sizes || volume != (role == Role::Air) { - once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image"); + if of.Format.0 != format || !sizes || volume != matches!(role, Role::Air | Role::Alpha) { + once!(?role, format = of.Format.0, width = of.Width, height = of.Height, slices = of.DepthOrArraySize, "no stand-in for the indirect light: another image"); if role == Role::Miss { crate::ambient::note_miss(MissNote::NotReady); } @@ -5424,12 +5428,14 @@ impl State { self.drew(Some(p)); } // The stand-in for reflections after the program that gives rays - // that found nothing the sky (`crate::ambient`, `Role::Miss`): the + // that found nothing the sky (`crate::ambient`, `Role::Miss`), and + // the bound of the transparent surfaces' light (`Role::Alpha`): the // execution held back is recorded first. (Not after one joined to // the run before: the tables noted are another program's.) if kind == DISPATCH && !joined - && let Some(role @ crate::ambient::Role::Miss) = p.stages.first().and_then(|s| s.shader.ambient) + && let Some(role @ (crate::ambient::Role::Miss | crate::ambient::Role::Alpha)) = + p.stages.first().and_then(|s| s.shader.ambient) && crate::ambient::on() { unsettle_indirect(list); From 3aca295c24953d12110cba96b1779ed879933346 Mon Sep 17 00:00:00 2001 From: Ahyildiz <87144467+Ahyildiz@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:22:33 +0300 Subject: [PATCH 36/57] Ambient: hold the resolved reflections to the light around (glowing eyes and floors indoors) Indoors the traced reflections came out of CS_TemporalResolve2_Opaque and CS_TemporalResolve1_Alpha far brighter than the room: eyes, glossy floors and glass glowed with the sky's light (issue #163). Bounding the miss rays does not help: the glow enters after them. With VICTORY_AMBIENT_REFLECT=<n> and VICTORY_AMBIENT_REFLECT_IN naming those programs, a pass after each resolve holds every texel of its R9G9B9E5 image to n times the light around (the ambient estimate's four points about it, a fifth of the room's mean), hue kept. Off unless both are set. Resolves dispatched with no groups, or after a count buffer, are left alone (a hold would rewrite older contents). Ported from TaynanGT/Vice-Tay#99 (fc9ef8a, fa90adf), itself from Serph91P's avatarmanz/VIctory-7900XTX#314 (6c7e3a87); idea and switch name from beloooo (VIctory-Belobug-AMD 44dcd437). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 8db298b6b4952d9e322d520f5bbaadb56307b019) --- crates/victory-gpu/src/ambient.rs | 135 +++++++++++++++++++++++++++++- crates/victory-gpu/src/draw.rs | 30 +++++-- 2 files changed, 158 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index a050a1444..cbac3574c 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -77,10 +77,29 @@ pub(crate) enum Role { /// before the eye (`CS_SpatialFilterAlpha`, the last program that writes /// it). Alpha, + /// Resolves the traced reflections (`VICTORY_AMBIENT_REFLECT_IN` names + /// the programs): after it each texel is held to a multiple of the light + /// around ([`reflect`]). + Reflect, } /// The program's part in this, by its name in the container. pub(crate) fn role(container: &[u8]) -> Option<Role> { + role_in(container, reflect_in()) +} + +/// [`role`], with the texts that name the reflections' resolves (looked for +/// last, so that no text takes a program of the other roles). +fn role_in(container: &[u8], reflect_in: &[String]) -> Option<Role> { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if let Some(found) = role_fixed(container) { + return Some(found); + } + reflect_in.iter().any(|name| has(name.as_bytes())).then_some(Role::Reflect) +} + +/// The roles named in the code. +fn role_fixed(container: &[u8]) -> Option<Role> { let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); if has(b"CS_ScreenProbes_TemporalResolve") { Some(Role::Resolve) @@ -170,6 +189,64 @@ fn parse_specular(set: &str) -> Option<Specular> { Some(Specular { share, sky }) } +/// Where the reflections' resolves write them: the first of these places +/// that holds a 2D image of their format (R32_UINT holding R9G9B9E5; the +/// opaque surfaces' resolve has it at the first, the transparent ones' at the +/// second). +pub(crate) const REFLECTIONS: [(u8, u32); 2] = [(1, 128), (1, 136)]; + +/// The most a resolved reflection may hold, as a multiple of the light +/// around (`VICTORY_AMBIENT_REFLECT=<multiple>`; unset, `0` or `off`: the +/// title's own). Acts only while `VICTORY_AMBIENT` is set and the builder +/// does not run. Ported from TaynanGT/Vice-Tay#99 (fc9ef8a, fa90adf), itself +/// from Serph91P's avatarmanz/VIctory-7900XTX#314 (6c7e3a87, GPL-3.0); the +/// idea and the switch's name are beloooo's (VIctory-Belobug-AMD 44dcd437). +fn reflect() -> f32 { + static SET: OnceLock<f32> = OnceLock::new(); + *SET.get_or_init(|| parse_reflect(&std::env::var("VICTORY_AMBIENT_REFLECT").unwrap_or_default())) +} + +fn parse_reflect(set: &str) -> f32 { + set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(0.0) +} + +/// The texts in the names of the programs that resolve the reflections +/// (`VICTORY_AMBIENT_REFLECT_IN=<text>[,<text>]`, e.g. +/// `CS_TemporalResolve2_Opaque,CS_TemporalResolve1_Alpha`); none while the +/// hold is off. +fn reflect_in() -> &'static [String] { + static SET: OnceLock<Vec<String>> = OnceLock::new(); + SET.get_or_init(|| { + let held = reflect(); + if held == 0.0 { + return Vec::new(); + } + let names = parse_reflect_in(&std::env::var("VICTORY_AMBIENT_REFLECT_IN").unwrap_or_default()); + if names.is_empty() { + tracing::warn!("VICTORY_AMBIENT_REFLECT without VICTORY_AMBIENT_REFLECT_IN: no reflections are held"); + } else { + tracing::info!(held, ?names, "reflections held to a multiple of the light around (VICTORY_AMBIENT_REFLECT)"); + } + names + }) +} + +fn parse_reflect_in(set: &str) -> Vec<String> { + set.split(',').map(str::trim).filter(|t| !t.is_empty()).map(str::to_owned).collect() +} + +/// Reflections' resolves held since the start. +static HELD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A resolve of the reflections was held after. +fn note_held() { + use std::sync::atomic::Ordering::Relaxed; + let n = HELD.fetch_add(1, Relaxed) + 1; + if n == 1 || n.is_multiple_of(5000) { + tracing::info!(n, "reflections held after their resolve, since the start (VICTORY_AMBIENT_REFLECT)"); + } +} + fn specular() -> Option<Specular> { static SET: OnceLock<Option<Specular>> = OnceLock::new(); *SET.get_or_init(|| parse_specular(&std::env::var("VICTORY_AMBIENT_SPECULAR").unwrap_or_default())) @@ -424,7 +501,7 @@ void reflect_light(uint3 at : SV_DispatchThreadID) { } #endif -#ifdef RAISE +#if defined(RAISE) || defined(HOLD) RWTexture2D<uint> light : register(u0); float3 unpack(uint v) { return float3(v & 511, (v >> 9) & 511, (v >> 18) & 511) * exp2(float(v >> 27) - 24.0); @@ -438,6 +515,40 @@ uint pack(float3 c) { uint3 m = min(uint3(c * scale + 0.5), 511u); return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); } +#endif + +#ifdef HOLD +// The resolved reflections: no brighter than `most` times the light around, +// as the estimate has it at the four points about the texel (with a fifth of +// the room's slow mean), or the constant; hue kept. +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void hold(uint3 at : SV_DispatchThreadID) { + uint w, h; + light.GetDimensions(w, h); + if (at.x >= w || at.y >= h) return; + float3 around = float3(1.0, 0.98, 0.94) * constant; + if (constant <= 0.0) { + float2 g = (float2(at.xy) + 0.5) / float2(w, h) * float2(PX, PY) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + around = 0; + for (int k = 0; k < 4; k++) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float2 b = float2(k & 1 ? f.x : 1 - f.x, k >> 1 ? f.y : 1 - f.y); + uint at0 = (q.y * PX + q.x) * 3; + around += b.x * b.y * float3(points[at0].w, points[at0 + 1].w, points[at0 + 2].w); + } + around = lerp(around, cells[CELLS].rgb, 0.2); + } + float top = most * dot(around, LUMA); + float3 c = unpack(light[at.xy]); + float has = dot(c, LUMA); + if (has > top) light[at.xy] = pack(c * (top / max(has, 1e-9))); +} +#endif + +#ifdef RAISE [RootSignature(RS)] [numthreads(8, 8, 1)] void raise(uint3 at : SV_DispatchThreadID) { @@ -543,6 +654,8 @@ struct Pass { raise: ID3D12PipelineState, air: ID3D12PipelineState, reflect: ID3D12PipelineState, + /// Made only while the hold of the reflections is on. + hold: Option<ID3D12PipelineState>, cells: ID3D12Resource, points: ID3D12Resource, } @@ -575,6 +688,13 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option<ID3D12Resource>) - let raise = pipeline("RAISE", s!("raise"))?; let air = pipeline("AIR", s!("clear_air"))?; let reflect = pipeline("REFLECT", s!("reflect_light"))?; + // Not made unless the hold is on, and on its own: without it the rest of + // the stand-in still runs. + let hold = if reflect_in().is_empty() { + None + } else { + pipeline("HOLD", s!("hold")).inspect_err(|e| tracing::warn!(%e, "no hold of the reflections")).ok() + }; let made = |bytes| buffer(bytes).ok_or_else(windows::core::Error::empty); Ok(Pass { root: root.ok_or_else(windows::core::Error::empty)?, @@ -585,6 +705,7 @@ fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option<ID3D12Resource>) - raise, air, reflect, + hold, cells: made(CELL_BYTES)?, points: made(POINT_BYTES)?, }) @@ -742,6 +863,10 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { if role == Role::Alpha && (constant > 0.0 || alpha() == 0.0) { return false; } + // The traced reflections are the title's own while its rays run. + if role == Role::Reflect && (pass.hold.is_none() || crate::pipeline::builder_runs()) { + return false; + } static SAID: Mutex<u32> = Mutex::new(0); { let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); @@ -761,7 +886,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[6] = views.depth_size[0]; words[7] = views.depth_size[1]; words[8] = 0.04f32.to_bits(); - words[9] = 4.0f32.to_bits(); + words[9] = if role == Role::Reflect { reflect() } else { 4.0f32 }.to_bits(); words[10] = if role == Role::Alpha { alpha() } else { air() }.to_bits(); words[11] = if once() { 1.0f32 } else { 0.0 }.to_bits(); let l = &list.list; @@ -797,6 +922,12 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { } run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); } + Role::Reflect => { + if let Some(hold) = &pass.hold { + run(hold, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1); + note_held(); + } + } Role::Miss => { // The points afresh, from this frame's depth: the diffuse // stand-in makes them later in the frame. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 82b2c1914..f2359cb45 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3773,6 +3773,8 @@ impl State { DISPATCHED.fetch_add(1, Ordering::Relaxed); if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient) && crate::ambient::on() + // A resolve of no groups writes nothing: a hold would rewrite what the image held before. + && !(role == crate::ambient::Role::Reflect && (x == 0 || y == 0 || z == 0)) && self.ambient(list, p, role) { self.host_pipeline = 0; @@ -3783,7 +3785,9 @@ impl State { /// The stand-in for the indirect light after a dispatch of `p` /// (`crate::ambient`). Whether it recorded anything. fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool { - use crate::ambient::{AIR, ALPHA, DEPTH, LIGHT, MISS_DEPTH, MISS_LIGHT, MissNote, RADIANCE, Role, Views}; + use crate::ambient::{ + AIR, ALPHA, DEPTH, LIGHT, MISS_DEPTH, MISS_LIGHT, MissNote, RADIANCE, REFLECTIONS, Role, Views, + }; // Each part has a switch of its own, on unless 0, that `VICTORY_AB` can flip while the // title runs (diagnostics builds): one scene with and without it. The light the // surfaces send out is kept either way. @@ -3792,6 +3796,7 @@ impl State { Role::Miss => crate::toggled!("VICTORY_AMBIENT_SPECULAR_ON"), Role::Air => crate::toggled!("VICTORY_AMBIENT_AIR_ON"), Role::Alpha => crate::toggled!("VICTORY_AMBIENT_ALPHA_ON"), + Role::Reflect => crate::toggled!("VICTORY_AMBIENT_REFLECT_ON"), Role::Radiance => true, }; if !live { @@ -3865,6 +3870,7 @@ impl State { Role::Air => AIR, Role::Alpha => ALPHA, Role::Miss => MISS_LIGHT, + Role::Reflect => REFLECTIONS[0], }; // Variants of the miss program bind the rays' image and the depth at // other places of their tables than the one found first (run @@ -3925,6 +3931,15 @@ impl State { d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.Format.0 == 26 }) }), + // The first of the places that holds a 2D image of the format + // (R32_UINT holding R9G9B9E5), else the first such in the tables. + Role::Reflect => { + let fits = |d: &D3D12_RESOURCE_DESC| d.Format.0 == 42 && d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D; + REFLECTIONS + .iter() + .find_map(|&at| entry(ResourceType::Uav, at).filter(|(d, _)| fits(d))) + .or_else(|| scan(ResourceType::Uav, &fits)) + } _ => entry(ResourceType::Uav, at), }; let usual_depth = |at: (u8, u32)| { @@ -4022,7 +4037,7 @@ impl State { } plain }), - Role::Radiance | Role::Air | Role::Alpha => image, + Role::Radiance | Role::Air | Role::Alpha | Role::Reflect => image, }; let (Some((of, image)), Some((seen, depth))) = (image, depth) else { once!(?role, "no stand-in for the indirect light: other tables"); @@ -4063,7 +4078,7 @@ impl State { return false; }; // (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.) - let format = if role == Role::Resolve { 42 } else { 26 }; + let format = if matches!(role, Role::Resolve | Role::Reflect) { 42 } else { 26 }; let volume = of.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; // The miss program's image is of half the picture's size, its depth // (32-bit) of the whole. @@ -5434,8 +5449,13 @@ impl State { // the run before: the tables noted are another program's.) if kind == DISPATCH && !joined - && let Some(role @ (crate::ambient::Role::Miss | crate::ambient::Role::Alpha)) = - p.stages.first().and_then(|s| s.shader.ambient) + && let Some( + role @ (crate::ambient::Role::Miss | crate::ambient::Role::Alpha | crate::ambient::Role::Reflect), + ) = p.stages.first().and_then(|s| s.shader.ambient) + // The reflections' resolve not after a count buffer: a count of 0 + // runs no resolve, and the hold would rewrite the image's earlier + // contents (Vice-Tay fa90adf). + && (role != crate::ambient::Role::Reflect || counter.is_none()) && crate::ambient::on() { unsettle_indirect(list); From 8556a378924c0e3002c99c137ea9952650712cf6 Mon Sep 17 00:00:00 2001 From: ballsimulation <362039263+ballsimulation@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:32:57 +0100 Subject: [PATCH 37/57] Card copies: big ones compared where written lately, and steps wait only for that (VICTORY_LAZY_COMPARE_MB, VICTORY_LAZY_NARROW; off by default) The constants heap (174 MB) is declared written by the skinning passes in every submission, so it was compared whole after each of ~12 submissions a frame (2.2 GB of the card's reads to find ~2.6 MB written), and every constant fill from it counted as blocked by flights and was planned onto the card (`card_steps`, 7-12 ms a frame on the submitting thread). VICTORY_LAZY_COMPARE_MB=<MiB>: of a card copy at least this large, a submission compares only the pieces found written lately (VICTORY_LAZY_HOT compares, 64), the left-out pieces about to be sent up (their rehash is held back, so the compare still sees older shader writes), and the next VICTORY_LAZY_SWEEP (128) left-out pieces in turn. Those compares store their hashes (mode 2). The write-back itself is unchanged: what is found is fetched and merged as before. VICTORY_LAZY_NARROW=1 (with the above): where submission steps wait for flights or are done on the card in their order (late_blocked, card_steps, cut_for, the relay's wait), such a copy counts as written only on those pieces. Refreshes still see every declared write. Accepted: a piece written for the first time reaches title memory, and is read as the title has it, only once the sweep finds it (~2 frames). Series S, DLSS Performance, 30 fps cap, RTX 4070, same walk, one build: frame time by draws per frame, switches off -> on: 4-6k 53.7 -> 50.4 ms, 6-7k 56.8 -> 54.4, 7-8k 59.2 -> 57.1, 8-9.5k 62.7 -> 58.8; submitting thread 49.5 -> 45.8 ms, its planning of steps on the card 7.4 -> 1.7 ms. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit f7cc776de444e625cd9dfe0d631b0a8bb7a0d4c9) --- crates/victory-gpu/src/host.rs | 157 +++++++++-- crates/victory-gpu/src/host/card_steps.rs | 6 +- crates/victory-gpu/src/host/lazy.rs | 311 ++++++++++++++++++++++ 3 files changed, 451 insertions(+), 23 deletions(-) create mode 100644 crates/victory-gpu/src/host/lazy.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5e2b4d5c5..1af6c2cc0 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2638,9 +2638,19 @@ struct CardRange { /// Looked at by `crate::picked`, and not declared: what is found changed /// there was written through a view nobody declared. Not landed. picked: bool, + /// Picked by [`lazy`]: compared and stored (mode 2), and what is found + /// tells `lazy` which pieces were written lately. + lazy: bool, } impl CardPlan { + /// [`lazy`] is told which of its pieces the compare found written. + fn lazy_found(&self, differs: &[u32]) { + for r in self.ranges.iter().filter(|r| r.lazy && r.compared) { + lazy::found(&r.shadow, &r.span, |p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d))); + } + } + /// `crate::picked` is told where what it looked at changed, by the /// compare's results. fn picked_found(&self, differs: &[u32]) { @@ -3134,6 +3144,9 @@ struct Line { /// The title memory the flights' shaders and texture readbacks may write /// (address, end), in order and joined. written: Vec<(usize, usize)>, + /// `written`, with big card copies' parts only where written lately + /// ([`lazy::narrow`]; empty when that is off): what steps wait for. + narrow: Vec<(usize, usize)>, /// Host lists in the flights. lists: usize, /// The value signalled on the host's fence behind the last flight. @@ -3162,6 +3175,7 @@ unsafe impl Send for Line {} static LINE: Mutex<Line> = Mutex::new(Line { line: Vec::new(), written: Vec::new(), + narrow: Vec::new(), lists: 0, target: 0, settling: false, @@ -3177,6 +3191,33 @@ fn line() -> std::sync::MutexGuard<'static, Line> { LINE.lock().unwrap_or_else(|e| e.into_inner()) } +impl Line { + /// What steps of a submission wait for (or are done on the card for): + /// `written`, or with [`lazy::narrow`] its narrowed form. + fn blocking(&self) -> &Vec<(usize, usize)> { + if lazy::narrow() { &self.narrow } else { &self.written } + } + + /// A flight's declared writes and texture read-backs join `written` (and + /// `narrow`). + fn joined(&mut self, back: &[Declared], textures: &[(usize, usize)]) { + join_ranges(&mut self.written, back.iter().flat_map(|(_, r)| r.iter().copied()).chain(textures.iter().copied())); + if lazy::narrow() { + let mut more: Vec<(usize, usize)> = textures.to_vec(); + for (shadow, ranges) in back { + if lazy::on(shadow) { + for &(from, to) in ranges { + lazy::hot_within(shadow, from, to, &mut more); + } + } else { + more.extend(ranges.iter().copied()); + } + } + join_ranges(&mut self.narrow, more); + } + } +} + /// Why flights were settled ([`LATE_STATS`]' places from 2 on). pub(crate) const WHY_SYNC: usize = 2; const WHY_CARD_DONE: usize = 3; @@ -3241,10 +3282,10 @@ fn flying() -> bool { fn late_blocked(runs: &[&HostList]) -> Option<usize> { let (written, copies) = { let line = line(); - if line.written.is_empty() { + if line.blocking().is_empty() { return None; } - (line.written.clone(), card_steps::copies(&line)) + (line.blocking().clone(), card_steps::copies(&line)) }; blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ)) } @@ -4222,6 +4263,7 @@ mod card_steps; #[cfg(feature = "diagnostics")] pub(crate) mod indirects; mod font; +mod lazy; mod menu; mod panel; mod place; @@ -4929,6 +4971,12 @@ impl Host { }; // The same pieces in fewer passes (`rehash_runs`). let runs = if joins { crate::shadow::joined_piece_runs(runs) } else { runs }; + // Pending pieces keep their hashes (`lazy`). + let runs = if lazy::on(shadow) && !whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { + lazy::hold_back(shadow, runs) + } else { + runs + }; CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed); for run in runs { @@ -4969,10 +5017,36 @@ impl Host { } } let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let lazy_copy = twin && lazy::on(shadow); + let start = shadow.span().0 as usize; for (from, to) in spans { let Some(span) = shadow.card_span(from, to) else { continue; }; + if lazy_copy { + // Only what `lazy` picks; the rest is left pending. + for (i0, i1) in lazy::select(shadow, &span) { + let (lo, hi) = (shadow.card_piece(&span, i0).0, shadow.card_piece(&span, i1 - 1).1); + if lo >= hi { + continue; + } + let span = shadow.card_run(lo, hi); + let compared = u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (start + lo, start + hi), + span, + at, + compared, + picked: false, + lazy: true, + }); + if compared { + at += span.pieces; + } + } + continue; + } let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; plan.ranges.push(CardRange { shadow: shadow.clone(), @@ -4981,12 +5055,44 @@ impl Host { at, compared, picked: false, + lazy: false, }); if compared { at += span.pieces; } } } + // `lazy`: the pieces forced by a send and the sweep's next ones, of + // the copies declared or sent up here. + if lazy::min().is_some() { + let mut copies: Vec<&Arc<crate::shadow::Shadow>> = Vec::new(); + for shadow in declared.iter().map(|d| &d.0).chain(plan._synced.iter()) { + if lazy::on(shadow) + && shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()) + && !copies.iter().any(|s| Arc::ptr_eq(s, shadow)) + { + copies.push(shadow); + } + } + for shadow in copies { + let start = shadow.span().0 as usize; + for span in lazy::sweep(shadow) { + let compared = u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (start + span.from as usize, start + span.to as usize), + span, + at, + compared, + picked: false, + lazy: true, + }); + if compared { + at += span.pieces; + } + } + } + } for (shadow, from, len) in looked { let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); if let Some(span) = shadow.card_span(*from, from + len) @@ -5000,6 +5106,7 @@ impl Host { at, compared: true, picked: true, + lazy: false, }); at += span.pieces; } @@ -5038,7 +5145,10 @@ impl Host { list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); // (What is only looked at keeps its hashes: what // changed there is the next declared range's to land.) - card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 }); + // (`lazy`'s keep what they find: a piece left out + // keeps its old hashes, one compared takes new ones.) + let mode = if r.lazy || flown && !r.picked { 2 } else { 1 }; + card_pass(list, &r.span, size as u32, r.at, mode); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } list.Close()?; @@ -5168,6 +5278,7 @@ impl Host { let mut seen = std::collections::HashSet::new(); for &(plan, behind) in plans { plan.picked_found(differs); + plan.lazy_found(differs); let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() @@ -5502,6 +5613,7 @@ impl Host { let Line { line: items, written, + narrow, lists, settling, poke, @@ -5515,16 +5627,31 @@ impl Host { landing.clear(); // What is still in the air, from the flights that are. written.clear(); + narrow.clear(); *lists = 0; let mut ranges = Vec::new(); + let mut narrowed = 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())); ranges.extend(flight.texture_back_ranges.iter().copied()); + if lazy::narrow() { + narrowed.extend(flight.texture_back_ranges.iter().copied()); + for (shadow, r) in &flight.back { + if lazy::on(shadow) { + for &(from, to) in r { + lazy::hot_within(shadow, from, to, &mut narrowed); + } + } else { + narrowed.extend(r.iter().copied()); + } + } + } } } join_ranges(written, ranges); + join_ranges(narrow, narrowed); *settling = false; // The landed lists are reset, and what queues hold looked at, // by the helper thread (they take locks a waiter may hold). @@ -5562,6 +5689,7 @@ impl Host { let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); let mut total = 0u64; plan.picked_found(differs); + plan.lazy_found(differs); for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) { for p in 0..r.span.pieces { if r.compared && !torn::flagged(differs[(r.at + p) as usize]) { @@ -5737,14 +5865,8 @@ impl Host { let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); 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()) - .chain(sent.texture_back_ranges.iter().copied()), - ); + line.joined(&sent.back, &sent.texture_back_ranges); + let Line { line: items, lists: flying, target, .. } = &mut *line; *flying += order.len(); *target = *submitted; items.push(Late::Run(Flight { @@ -5793,14 +5915,8 @@ impl Host { 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()) - .chain(sent.texture_back_ranges.iter().copied()), - ); + line.joined(&sent.back, &sent.texture_back_ranges); + let Line { line: items, lists: flying, target, .. } = &mut *line; *flying += 1; *target = *submitted; items.push(Late::Run(Flight { @@ -5860,6 +5976,7 @@ impl Host { } line.settling = true; line.written.clear(); + line.narrow.clear(); line.lists = 0; std::mem::take(&mut line.line) }; @@ -6073,7 +6190,7 @@ impl Host { // 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() && !card_steps::copied_read(&card_steps::copies(line), runs) + blocked_by(line.blocking(), runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) }); } else { self.settle(&mut submitted, why); diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 3baf286c5..f0f966f53 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -580,7 +580,7 @@ pub(super) fn cut_for(runs: &[&HostList]) -> Option<usize> { if first + 1 == runs.len() { return None; } - let written = line().written.clone(); + let written = line().blocking().clone(); blocked_by(&written, runs, false)?; let (does, steps) = does_of(&written, runs); let mut behind = None; @@ -769,10 +769,10 @@ impl Host { } let (written, copies) = { let line = line(); - if line.written.is_empty() { + if line.blocking().is_empty() { return None; } - (line.written.clone(), copies(&line)) + (line.blocking().clone(), copies(&line)) }; blocked_by(&written, runs, false)?; let taken = if copied_read(&copies, runs) { diff --git a/crates/victory-gpu/src/host/lazy.rs b/crates/victory-gpu/src/host/lazy.rs new file mode 100644 index 000000000..3ea40fd39 --- /dev/null +++ b/crates/victory-gpu/src/host/lazy.rs @@ -0,0 +1,311 @@ +//! Fewer compares of big copies in the card's memory (`VICTORY_LAZY_COMPARE_MB=<MiB>`, +//! off by default). +//! +//! A copy whose shader writes are declared is compared on the card after +//! every submission, every declared piece. For the constants heap +//! (174 MB) that is 2.2 GB of the card's reads a frame to find about +//! 2.6 MB that shaders wrote. With this switch, of a copy at least that +//! large, a submission compares only: +//! +//! - the pieces found written lately ("hot", for `VICTORY_LAZY_HOT` +//! compares, 64 by default, after the last time one was found written); +//! - the pieces about to be sent up that were left out of a compare since +//! their last one ("forced": they are not hashed again when sent, so the +//! compare still sees what shaders wrote there before); +//! - the next `VICTORY_LAZY_SWEEP` pieces (128 by default) of those left +//! out, in turn, so a piece written for the first time is found within a +//! sweep of the copy. +//! +//! The other declared pieces are left out and marked pending; their hashes +//! stay as they were, so what shaders wrote there is found when the sweep +//! or a send reaches them. These compares store the hashes they make +//! (mode 2), so a piece the CPU sent up and nothing wrote is not found +//! again. What is found is fetched and merged as before: a merge takes only +//! the bytes that differ from the CPU's side, so a piece found that nothing +//! wrote costs a fetch and nothing else. Left out: shader bytes in a 4 KiB +//! page that the CPU sends up before the piece's compare are lost. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use crate::shadow::{CardSpan, Shadow}; + +/// The smallest copy (bytes) taken this way, if on. +pub(super) fn min() -> Option<u64> { + static MIN: OnceLock<Option<u64>> = OnceLock::new(); + *MIN.get_or_init(|| { + let mb = std::env::var("VICTORY_LAZY_COMPARE_MB").ok()?.trim().parse::<u64>().ok().filter(|&mb| mb > 0)?; + tracing::info!( + mb, + hot = hot_life(), + sweep = sweep_len(), + "copies in the card's memory this large are compared only where written lately, before a send, and in a sweep \ + (VICTORY_LAZY_COMPARE_MB)" + ); + Some(mb << 20) + }) +} + +fn hot_life() -> u8 { + static N: OnceLock<u8> = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LAZY_HOT").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(64)) +} + +fn sweep_len() -> usize { + static N: OnceLock<usize> = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LAZY_SWEEP").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128)) +} + +/// Whether what flights may write of such a copy counts, for the steps that +/// wait for flights or are done on the card in their order, as only its +/// pieces written lately (`VICTORY_LAZY_NARROW=1`, with +/// `VICTORY_LAZY_COMPARE_MB`). The skinning passes declare the whole +/// constants heap written; every constant read of it then waited or was +/// done on the card (5.5 ms a frame of planning on the submitting thread). +/// A piece written for the first time is read as the title has it until the +/// sweep finds it, as its write-back is late until then anyway. +pub(super) fn narrow() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let on = min().is_some() && std::env::var_os("VICTORY_LAZY_NARROW").is_some_and(|v| v == "1"); + if on { + tracing::info!("flights' writes to big card copies count only where written lately (VICTORY_LAZY_NARROW)"); + } + on + }) +} + +/// Of the title range `[from, to)` of `shadow`: the parts in pieces written +/// lately, as title ranges. +pub(super) fn hot_within(shadow: &Shadow, from: usize, to: usize, out: &mut Vec<(usize, usize)>) { + let start = shadow.span().0 as usize; + let len = shadow.span().1 as usize; + let (lo, hi) = (from.max(start) - start, to.min(start + len).saturating_sub(start)); + if lo >= hi { + return; + } + let (first, last) = (shadow.card_piece_of(lo), shadow.card_piece_of(hi - 1)); + let states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let Some(state) = states.as_ref().and_then(|s| s.get(&shadow.id())) else { + return; + }; + for piece in first..=last { + if state.hot.get(piece as usize).is_some_and(|&h| h > 0) { + let (a, b) = piece_offsets(shadow, piece); + let (a, b) = (a.max(lo) + start, b.min(hi) + start); + match out.last_mut() { + Some(last) if last.1 >= a => last.1 = last.1.max(b), + _ => out.push((a, b)), + } + } + } +} + +/// Whether `shadow` is compared this way. +pub(super) fn on(shadow: &Shadow) -> bool { + min().is_some_and(|min| shadow.span().1 >= min) +} + +#[derive(Default)] +struct State { + /// Per piece: compares left while it counts as written lately. + hot: Vec<u8>, + /// Per piece: left out of a compare since it was last compared. + pending: Vec<bool>, + /// Per piece: pending and sent up without being hashed again. + forced: Vec<bool>, + cursor: usize, +} + +impl State { + fn sized(&mut self, pieces: usize) { + if self.hot.len() < pieces { + self.hot.resize(pieces, 0); + self.pending.resize(pieces, false); + self.forced.resize(pieces, false); + } + } +} + +static STATES: Mutex<Option<HashMap<u64, State>>> = Mutex::new(None); + +/// Since the last line: pieces compared (hot, forced, swept), left out, found. +static STATS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +fn with<R>(shadow: &Shadow, f: impl FnOnce(&mut State) -> R) -> R { + let pieces = pieces_of(shadow); + let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let state = states.get_or_insert_with(HashMap::new).entry(shadow.id()).or_default(); + state.sized(pieces); + f(state) +} + +/// How many pieces the copy has (piece 0 holds offset 0). +fn pieces_of(shadow: &Shadow) -> usize { + let len = shadow.span().1 as usize; + if len == 0 { 0 } else { shadow.card_piece_of(len - 1) as usize + 1 } +} + +/// The offsets of the copy's piece `piece`. +fn piece_offsets(shadow: &Shadow, piece: u32) -> (usize, usize) { + let full = shadow.card_run(0, usize::MAX); + shadow.card_piece(&full, piece - full.first) +} + +/// Contiguous runs of the sorted, unique `pieces`, as spans of the copy. +fn runs_of(shadow: &Shadow, pieces: &[u32]) -> Vec<CardSpan> { + let mut out = Vec::new(); + let mut i = 0; + while i < pieces.len() { + let mut j = i + 1; + while j < pieces.len() && pieces[j] == pieces[j - 1] + 1 { + j += 1; + } + let lo = piece_offsets(shadow, pieces[i]).0; + let hi = piece_offsets(shadow, pieces[j - 1]).1; + if lo < hi { + out.push(shadow.card_run(lo, hi)); + } + i = j; + } + out +} + +/// The hash passes after a send: of `runs`, the pending pieces are left +/// out (and forced into this submission's compare). +pub(super) fn hold_back(shadow: &Shadow, runs: Vec<CardSpan>) -> Vec<CardSpan> { + let mut kept: Vec<u32> = with(shadow, |state| { + let mut kept = Vec::new(); + for run in &runs { + for piece in run.first..run.first + run.pieces { + let p = piece as usize; + if state.pending.get(p).copied().unwrap_or(false) { + state.forced[p] = true; + } else { + kept.push(piece); + } + } + } + kept + }); + kept.sort_unstable(); + kept.dedup(); + runs_of(shadow, &kept) +} + +/// Of a declared `span` of the copy: the runs `[i0, i1)` of its pieces (by +/// index in the span) to compare now; the others are marked pending. +pub(super) fn select(shadow: &Shadow, span: &CardSpan) -> Vec<(u32, u32)> { + with(shadow, |state| { + let mut out: Vec<(u32, u32)> = Vec::new(); + let (mut now, mut left) = (0u64, 0u64); + for i in 0..span.pieces { + let p = (span.first + i) as usize; + let Some(&hot) = state.hot.get(p) else { + continue; + }; + if hot > 0 || state.forced[p] { + state.pending[p] = false; + state.forced[p] = false; + now += 1; + match out.last_mut() { + Some(last) if last.1 == i => last.1 = i + 1, + _ => out.push((i, i + 1)), + } + } else { + state.pending[p] = true; + left += 1; + } + } + STATS[0].fetch_add(now, Ordering::Relaxed); + STATS[3].fetch_add(left, Ordering::Relaxed); + out + }) +} + +/// After the declared spans: the copy's forced pieces still pending, and the +/// next pending pieces of the sweep, as spans to compare now. +pub(super) fn sweep(shadow: &Shadow) -> Vec<CardSpan> { + let pieces: Vec<u32> = with(shadow, |state| { + let n = state.pending.len(); + let mut out = Vec::new(); + for p in 0..n { + if state.forced[p] { + state.forced[p] = false; + state.pending[p] = false; + out.push(p as u32); + } + } + STATS[1].fetch_add(out.len() as u64, Ordering::Relaxed); + let (mut taken, mut looked) = (0, 0); + while taken < sweep_len() && looked < n { + let p = state.cursor % n.max(1); + state.cursor = (p + 1) % n.max(1); + looked += 1; + if state.pending[p] { + state.pending[p] = false; + out.push(p as u32); + taken += 1; + } + } + STATS[2].fetch_add(taken as u64, Ordering::Relaxed); + out + }); + let mut pieces = pieces; + pieces.sort_unstable(); + pieces.dedup(); + runs_of(shadow, &pieces) +} + +/// A compared piece of the copy was found written (`flagged`) or not. +pub(super) fn found(shadow: &Shadow, span: &CardSpan, flagged: impl Fn(u32) -> bool) { + let life = hot_life(); + let mut hits = 0; + with(shadow, |state| { + for i in 0..span.pieces { + let p = (span.first + i) as usize; + let Some(hot) = state.hot.get_mut(p) else { + continue; + }; + if flagged(i) { + *hot = life; + hits += 1; + } else { + *hot = hot.saturating_sub(1); + } + } + }); + STATS[4].fetch_add(hits, Ordering::Relaxed); + log(); +} + +fn log() { + static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let now = std::time::Instant::now(); + if last.is_some_and(|t| now.duration_since(t).as_secs() < 5) { + return; + } + let first = last.is_none(); + *last = Some(now); + if first { + return; + } + let [hot, forced, swept, left, found] = std::array::from_fn(|i| STATS[i].swap(0, Ordering::Relaxed)); + let hot_now: usize = STATES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |s| s.values().map(|s| s.hot.iter().filter(|&&h| h > 0).count()).sum()); + tracing::info!( + hot, + forced, + swept, + left, + found, + hot_now, + "lazy compares in the last 5 s (VICTORY_LAZY_COMPARE_MB): pieces compared as written lately, before a send, in the \ + sweep; left out; found written; written lately now" + ); +} From 74857704f52bb682ccab7e0700129fdb75b6b48b Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 08:20:06 -0500 Subject: [PATCH 38/57] Diagnostics: passes skipped in turn, to see one view with and without them VICTORY_SKIP_A to VICTORY_SKIP_D take shader hashes as VICTORY_SKIP_PIPELINES does; each group is skipped only while its switch (VICTORY_SKIP_A_ON ..) is on, and VICTORY_AB flips those while the title runs. Diagnostics builds only. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-gpu/src/pipeline.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index f8cd62849..d3b2a2dfa 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -516,7 +516,30 @@ fn skipped_shader(p: &Pipeline) -> Option<&str> { #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn is_skipped(this: This) -> bool { - !this.is_null() && skipped_shader(pipeline(this)).is_some() + !this.is_null() && (skipped_shader(pipeline(this)).is_some() || skipped_in_turn(pipeline(this))) +} + +/// `VICTORY_SKIP_A` to `VICTORY_SKIP_D` (shader hashes, as +/// `VICTORY_SKIP_PIPELINES` takes them): skipped only while the group's +/// switch (`VICTORY_SKIP_A_ON` and so on) is on, and `VICTORY_AB` flips +/// those while the title runs: one view with and without a pass. +#[cfg(all(windows, feature = "diagnostics"))] +fn skipped_in_turn(p: &Pipeline) -> bool { + static GROUPS: OnceLock<[Vec<String>; 4]> = OnceLock::new(); + let groups = GROUPS.get_or_init(|| { + ["VICTORY_SKIP_A", "VICTORY_SKIP_B", "VICTORY_SKIP_C", "VICTORY_SKIP_D"] + .map(|name| parse_skip_hashes(&std::env::var(name).unwrap_or_default())) + }); + if groups.iter().all(Vec::is_empty) { + return false; + } + let on = [ + crate::asked_for!("VICTORY_SKIP_A_ON"), + crate::asked_for!("VICTORY_SKIP_B_ON"), + crate::asked_for!("VICTORY_SKIP_C_ON"), + crate::asked_for!("VICTORY_SKIP_D_ON"), + ]; + groups.iter().zip(on).any(|(hashes, on)| on && p.shaders.iter().any(|shader| hashes.contains(&shader.hash))) } /// Counts a draw or dispatch of `this` intentionally skipped or dropped From cfecf3562d715c5504039d2045c85211ddc4e60a Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 10:11:26 -0500 Subject: [PATCH 39/57] Play: the reflections' hold and the transparent light's bound on, the memory stack off Neo's launcher settings after the merge of upstream's main (63b902f), each measured on an RTX 3090 Ti and a Ryzen 9 9950X3D, Series S profile, DLSS off: - VICTORY_AMBIENT_REFLECT=1 with VICTORY_AMBIENT_REFLECT_IN naming the two resolves (Ahyildiz's change, trustno1 #818), and VICTORY_AMBIENT_ALPHA=4. In the first house of a shared save, flipped on and off inside one run and one view: without them a terrarium's glass is a white box, a table top, a patch of floor, a microwave's door and a wall clock are white, and white specks stand in the air; with them none of that. On the deck outside the picture is the same but for a glass door, darker with the hold. In the prologue's cell 39.3, 39.0 and 38.8 frames a second with them against 39.5 and 39.3 without: nothing. - Upstream's memory stack (VICTORY_SLOT_EVICT, VICTORY_ALLOCATOR_TRIM, VICTORY_BUDGET_PACK), which its main now turns on, is left off: 38.5 frames a second with it in that cell, 39.4 without, and the process held as much memory either way (36 to 41 GB by run). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- apps/victory/src/play.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/apps/victory/src/play.rs b/apps/victory/src/play.rs index 627ed1d0b..f4957d0f1 100644 --- a/apps/victory/src/play.rs +++ b/apps/victory/src/play.rs @@ -104,17 +104,22 @@ const SETTINGS: &[(&str, &str)] = &[ ("VICTORY_AMBIENT", "0.8"), ("VICTORY_AMBIENT_AIR", "1.5"), ("VICTORY_AMBIENT_SPECULAR", "1"), + // Indoors, without it: the reflections the title resolves hold the sky's light (a + // terrarium's glass, a table top and a floor show white), and the dust in the air is lit + // as under the open sky (white specks) + ("VICTORY_AMBIENT_REFLECT", "1"), + ("VICTORY_AMBIENT_REFLECT_IN", "CS_TemporalResolve2_Opaque,CS_TemporalResolve1_Alpha"), + ("VICTORY_AMBIENT_ALPHA", "4"), // Pixel programs keep the console's early depth test ("VICTORY_EARLY_DEPTH", "1"), // Left out: the decal heap's defragmentation and the heat-haze pass ("VICTORY_LEAVE_OUT", "02384a60fda6f2d0,731a39171b568298"), // Pipelines the title makes are written down, for `victory warm` ("VICTORY_PIPELINE_BOOK", "1"), - // Memory stack (skornuta): texture slots left unused are given back, old command allocators - // are taken anew, small buffers share card memory (off since .8; on again 2026-11-28) - ("VICTORY_SLOT_EVICT", "1"), - ("VICTORY_ALLOCATOR_TRIM", "1"), - ("VICTORY_BUDGET_PACK", "1"), + // (The tree this is built on turns the memory stack on here: VICTORY_SLOT_EVICT, + // VICTORY_ALLOCATOR_TRIM, VICTORY_BUDGET_PACK. Not in Neo: in the prologue's cell on an + // RTX 3090 Ti it took 38.5 frames a second where 39.4 ran without, and the process held as + // much memory either way; `--set VICTORY_SLOT_EVICT=1` and so on turn it on.) // Neo, measured in the prologue's cell on an RTX 3090 Ti and a Ryzen 9 9950X3D (README): // the title's write faults open their block without the write watch's one lock, and a // store that faults is done beside the guard (one that changes nothing is left out) From 9a8e3179992713019c267cf827c3c5140a294dee Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 10:46:36 -0500 Subject: [PATCH 40/57] Input: the tables' letters go by their place alone, as upstream has them The merge of upstream's main joined its rule (a letter of the stand-in pad counts by where it is on the keyboard, and a letter in none of the pad's places presses nothing) with Neo's keys from the start (VICTORY_PAD_KEYS) too loosely: a letter in none of the pad's places still pressed what the tables name for that letter. Upstream's test for a Dvorak keyboard's S said so. Now the tables' letters go by their place alone. A key the start gave a button goes by its place if it is one of the pad's places, and by what it is otherwise (the PC layout's R and V have no place in upstream's table). Neo's tests build their keys as a keyboard sends them, with the place; one more case checks an AZERTY keyboard under the PC layout. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/victory-hle/src/modules/gameinput.rs | 25 ++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index e8d5a3f86..715b43831 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -315,8 +315,12 @@ fn fallback(keys: &[KeyState]) -> PadState { /// The stand-in pad for the keys held, `given` being the start's own keys /// ([`parse_pad_keys`]). fn fallback_with(keys: &[KeyState], given: &[(u8, PadKey)]) -> PadState { - // A letter of the stand-in pad's counts by where it is ([`pad_key`]), any - // other key by what it is. + // What the tables name: a letter counts by where it is ([`pad_key`]), and + // a letter in none of the pad's places presses nothing. + let placed = |vk: u8| keys.iter().any(|k| pad_key(k) == vk); + // What the start gave a button: a letter of the pad's places by where it + // is too, and any other key by what it is (the letters the tables do not + // know, R or V, have no place to go by). let held = |vk: u8| { keys.iter().any(|k| match pad_key(k) { 0 => k.virtual_key == vk, @@ -325,7 +329,7 @@ fn fallback_with(keys: &[KeyState], given: &[(u8, PadKey)]) -> PadState { }; // A key the start gave a button is no longer what the tables say. let on = |vk: u8| { - if held(vk) && !given.iter().any(|(k, _)| *k == vk) { + if placed(vk) && !given.iter().any(|(k, _)| *k == vk) { 1.0 } else { 0.0 @@ -2196,8 +2200,11 @@ mod tests { /// last word on a key holds. #[test] fn the_start_can_give_the_stand_in_pad_its_keys() { + // Keys of a US keyboard: a letter of the pad's places comes with its place. let down = |vks: &[u8]| -> Vec<KeyState> { - vks.iter().map(|&vk| KeyState { virtual_key: vk, ..Default::default() }).collect() + vks.iter() + .map(|&vk| KeyState { virtual_key: vk, scan_code: letter_position(vk).unwrap_or(0), ..Default::default() }) + .collect() }; // Nothing given: as the tables say (C the right trigger, F the left stick's press). let pad = fallback_with(&down(&[b'C', b'F', b'W']), &[]); @@ -2217,12 +2224,20 @@ mod tests { let pad = fallback_with(&down(&[b'G', b'7', b'F']), &keys); assert_eq!((pad.right_trigger, pad.buttons), (1.0, UP | DOWN)); assert!(parse_pad_keys("").is_empty()); + // A given letter of the pad's places goes by its place, as the tables' letters do: on an + // AZERTY keyboard the key at Q's place is marked A, and is the PC layout's Q all the same. + // A given letter the tables do not know (R) goes by what it is. + let at = |scan_code, virtual_key| KeyState { scan_code, virtual_key, ..Default::default() }; + assert_eq!(fallback_with(&[at(0x10, b'A')], &pc).buttons, RIGHT_SHOULDER); + assert_eq!(fallback_with(&[at(0x13, b'R')], &pc).buttons, B); + // And the tables' letters stay by their place beside the given ones: the key above S walks. + assert_eq!(fallback_with(&[at(0x11, b'Z')], &pc).left_y, 1.0); } /// The stand-in pad carries the mouse's stick beside the keyboard's keys. #[test] fn the_stand_in_pad_takes_the_mouse_and_the_keys() { - let keys = [KeyState { virtual_key: b'W', ..Default::default() }]; + let keys = [KeyState { virtual_key: b'W', scan_code: 0x11, ..Default::default() }]; let mut m = MouseLook::default(); let look = Look { speed: 1000.0, dead_zone: 0.0, curve: 1.0, vertical: 1.0, bank: 0.5 }; m.pad(&look, Some(&mouse_at(0, 0)), 0); From 81239fb98ca4320bc0d13a331bc2d9a040a1a5d8 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 11:03:45 -0500 Subject: [PATCH 41/57] README, docs: the build of 28 November, afternoon; what was tried for speed The first house without its white glow and specks, the merge of upstream's main, and docs/speed-methods.md: every speed method tried on 28 November in the prologue's cell with what it measured (frame rate and frame times), what did nothing, what was not built and why its gain is bounded, and what the frame waits for now. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 57 ++++++++++++++++++++++++++++++++------ docs/speed-methods.md | 64 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 8 deletions(-) create mode 100644 docs/speed-methods.md diff --git a/README.md b/README.md index dbc91be08..95642ebde 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,9 @@ shows it), medians over the 5-second readings of a run, hands off. | Scene | Profile | Frames a second | |---|---|---| -| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **39** (two runs: 39.1 and 38.7, readings 36.4 to 40.3; 30.7 on the build before, the same draws) | -| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **36 rendered, 73 shown** (27 and 53 before) | -| The first house, from a shared save (views of 5,300 to 6,500 draws a frame) | Series S | about 30 | +| Prologue, the cell (4,300 to 4,700 draws a frame) | Series S, 1920x1080 out | **39** (runs of this build: 39.5, 39.3, 39.3, 39.0 and 38.8; frames of 25 ms at the median, 31 at the 95th percentile, 35 at the 99th; 30.7 on the build of 27 November, the same draws) | +| the same | Series S, DLSS Quality and AMD FSR 3 frame generation | **36 rendered, 73 shown** on the build of the morning of 28 November (27 and 53 the day before). Not measured on this build: the one run was stopped before the scene by a guard on memory, the process at 42.5 GB and 1.5 GB of the PC's left | +| The first house, from a shared save (views of 5,300 to 7,400 draws a frame) | Series S | 27 to 31 by view | Measured on the build before (27 November), not again since: @@ -39,7 +39,7 @@ Measured on the build before (27 November), not again since: cutscene play in order, and the prologue's first room stands. - Characters, hair, clothes and their prints, textures, sky and sun are drawn. - No crash and no lost graphics device in the runs these numbers come from - (some sixty on 28 November, 4 to 5 minutes each, hands off; one more, with + (some hundred on 28 November, 3 to 5 minutes each, hands off; one more, with the tree's sampling profiler switched on, ended in that profiler). Keyboard and mouse were checked by a script in one scene (the mouse turns the camera, W walks), and a shared save from after the prologue loads and plays in the @@ -55,7 +55,7 @@ cell at 17 to 19 frames a second. - **No ray tracing.** The title traces its indirect light, reflections and some shadows itself, and no layer runs that fast enough yet. An estimate stands in for indirect light and reflections (foxhound's work): rooms are - lit, reflections are blurry. `VICTORY_BVH_BUILDER=1` runs the title's own + lit, reflections are blurry, lamps cast no shadows of their own. `VICTORY_BVH_BUILDER=1` runs the title's own rays: a few frames a second and a broken picture. - **Haze through windows.** Bright views through glass (the cell's window) are smeared; cause not found yet. @@ -63,8 +63,9 @@ cell at 17 to 19 frames a second. 28 November 7 of some 55, on builds with and without the changes below), the wall to the left of the character in the cell shows a dark patch with blocky edges for the whole run; cause not found yet. -- **White specks, and bright blotches on floors,** in the first house (on - the build before too). +- **Windows seen from a dark room are very bright**, with a wide glow: the + room gets less light than the title's own rays would bring it, and the + picture is exposed for the room. - **Hitches** when the title streams a new scene in, and during the first launches while shaders are translated and pipelines made (see below). - **Rendered frames stop at 60 a second.** The title steps its world at @@ -248,9 +249,44 @@ others have not been sent yet: the same draws, the picture the same within what two runs differ by. What limits it now, each at about 25 ms a frame: the title's own main thread (22 ms of its own work), the layer's thread that prepares the - card's work (23 ms), and the card (23 ms). + card's work (23 ms), and the card (23 ms). (A later test took the card + off that list: with half the pixels to draw the frame rate is the same.) 5. **The game keeps its speed above 30 frames a second**, and **keyboard and mouse** (both above). +6. **Rooms without the white glow** (28 November). In the first house of the + story a terrarium's glass was a white box, a table top, a patch of floor, + a microwave's door and a wall clock were white, and white specks stood in + the air. Two things, both the sky's light getting into a room because the + title's rays, which would find the walls, do not run: + - The reflections the title resolves after tracing hold the sky's light. + [Ahyildiz's change](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/818) + (from TaynanGT/Vice-Tay and Serph91P's work on avatarmanz's tree, an + idea of beloooo's) holds them to the light around; Neo has it on. With + it the glass is clear, the snake behind it is seen, and table, floor, + door and clock are as they should be. + - The dust in the air takes its light from a volume the title's rays + fill, which held the sky's light too. `VICTORY_AMBIENT_ALPHA` (new in + Neo) bounds it as the tree bounds the air's light: in a dark part of the + picture 20 specks without it, 3 with it. + Each was flipped on and off inside one run, in one view, because that + save starts in a room of its own choosing every time; on the deck outside + the picture is the same with and without, but for a glass door that is + darker. Neither costs frame rate that can be measured (39.3 against 39.4 + in the cell). +7. **The tree it is built on, as of 28 November** (its `main` at `63b902f`): + frames are shown as soon as they are presented (38.5 against 37.7 here), + the keyboard's stand-in pad reads its letter keys by their place, not + by their letter, and there are fixes to shaders and to the loader. One of its new defaults is left off: the memory stack + (`VICTORY_SLOT_EVICT`, `VICTORY_ALLOCATOR_TRIM`, `VICTORY_BUDGET_PACK`) + ran 38.5 frames a second here where 39.4 ran without, and the process + held as much memory either way. + +**What else was measured** for speed on 28 November, method by method, with +frame times: [docs/speed-methods.md](docs/speed-methods.md). In short: on +this PC the frame is no longer the card's (half the pixels to draw changes +nothing) but the title's own main thread and the layer's thread that +prepares the card's work, and where the threads run is worth more than any +switch (nothing pinned: 34.8; as shipped: 39.4). Tried on 28 November and left out, for no gain measured: asking the write tracker about a submission's memory on a helper thread beside its start @@ -288,6 +324,11 @@ people's: the tree this one is taken from (its `main` of 2026-11-27): the launcher built into the program, the F1 menu, the stats panel, DLSS and frame generation, and the pull requests of its contributors. +- **Ahyildiz** ([#818](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/818): + the reflections held indoors) and **ballsimulation** + ([#501](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/501): the big + card copies compared where written lately, in the tree and off unless + asked for), whose open pull requests to that tree are carried here. - And everyone those name: avatarmanz, DexNom, Belobug, Vice-Tay and more. Their READMEs are kept here: [VIctory on NVIDIA](docs/README-nvidia.md), [foxhound](docs/README-foxhound.md), [fxceless](docs/README-fxceless.md), diff --git a/docs/speed-methods.md b/docs/speed-methods.md new file mode 100644 index 000000000..2a0f5a04a --- /dev/null +++ b/docs/speed-methods.md @@ -0,0 +1,64 @@ +# What was tried for speed, method by method (28 November 2026) + +One PC: Ryzen 9 9950X3D (16 cores in two dies; the die with the large cache is processors 0 to 15), GeForce RTX 3090 Ti +24 GB (driver 616.92), 64 GB RAM, Windows 11, power plan Ultimate Performance. One scene: the prologue's cell, about +4,450 draws a frame, Series S profile at 1920x1080, DLSS off, hands off. A run is 4.5 to 5 minutes; its first half +minute in the cell is left out. Frame rates are medians of the 5-second readings; frame times (median, 95th and 99th +percentile, in ms) are of the builds that log them. Two runs of one build differ by up to 0.4 frames a second +(39.5 and 39.3; 39.1, 38.7 and 39.0), so **anything under 0.5 is nothing**. + +Where the day began: 30.7 frames a second. Where it ended: 39.0 to 39.5 by run as shipped (frame 24.7 to 25.1 ms at the +median, 31 to 32 at the 95th percentile, 35 to 36 at the 99th), and 40 with the one opt-in switch that gained. + +## What moved the frame + +| Method | Where it comes from | Measured | In Neo | +|---|---|---|---| +| The title's threads on the large-cache die (its own choice of processors), the layer's on the other, four threads translating lists | what Process Lasso users do by hand; games with their own affinity masks | nothing pinned: 34.8 (frame 28.1 / 33.2 / 34.8); the layer roaming: 35.2; a core to each of the title's processors, the layer roaming: 35.1; all on the large-cache die: 38.2; the two dies swapped: 37.4; **as shipped: 39.4** (24.9 / 30.7 / 35.1) | on | +| The loop that kept the card's clocks up, off | (the layer's own) | with the loop: 34.5 and a 95th percentile of 44 ms; **without: 39.4 and 31 ms**. The card is in its highest power state either way | off | +| Translated shaders that wait less (per-lane loops proven once: the "waterfall shape") | shader recompilers of emulators | the card's time by command 27.6 to 24.4 ms a frame; 35.8 to 36.9 | on | +| Write tracking without its one lock in the way (faults open their block unlocked, a faulting store done beside the guard, one page asked about, a queue of let-go objects to each thread) | dirty-page tracking of emulators and of virtual machines | 32.6 to 30.1 ms a frame together, by turns in one run | on | +| Frames shown as soon as presented (a tearing swap chain; upstream's) | "VSync off" of every game | 38.5 against 37.7 | on | +| Big card copies compared only where written lately (upstream pull request 501, ballsimulation) | (the layer's own) | 40.1 and 40.0 against 39.4 and 39.0 (two builds, a run each); the picture the same cell by cell | in the tree, off unless asked for (`VICTORY_LAZY_COMPARE_MB=64`, `VICTORY_LAZY_NARROW=1`) | +| Compiler settings (thin link-time optimisation, one codegen unit, AVX2) and another allocator (mimalloc) | every shipped game | 31.7 to 31.9; the preparing thread 29.3 to 28.7 ms a frame | on | + +## What did nothing, or harm + +| Method | Where it comes from | Measured | +|---|---|---| +| Profile-guided optimisation of the layer (counts taken in this scene; sixteen codegen units, since with one the optimiser ran over twenty minutes on the last crate and was stopped) | browsers, game engines, compilers themselves | 38.5 and 38.8 against 39.3, 39.0 and 38.8 in turn: nothing. (The build that takes the counts runs the scene at 29.4.) | +| Half the pixels to draw (DLSS Performance, the scene at 960x540) | every modern game; dynamic resolution | 39.7 against 39.4 (Quality: 39.5). **The frame is not the card's** | +| The NVIDIA driver's "prefer maximum performance" for the program, in place of the keep-awake loop | driver tweak guides | 38.2 against 39.4: the card was in its highest state before (P0 in 66 of 71 two-second samples, in 82 of 85 with the setting) | +| That driver setting and the loop together | | 34.2, as the loop alone | +| The title's own 40-frames mode | the console's performance modes | 38.0 against 39.4 (frame 25.9 / 31.4 / 34.2 against 24.9 / 30.7 / 35.1): a little slower and no evener | +| The process at High priority | Process Lasso, task manager | 39.2 against 39.4: nothing | +| The title's stores that change nothing, patched to look first (the tree's `VICTORY_WRITE_SITES`) | game patches, code hooks | 27 such stores found in a run and patched in the next: 39.3 against 39.4; the preparing thread 17.9 ms a frame against 18.5 | +| Upstream's memory stack (texture slots given back, allocators trimmed, small buffers packed) | texture streaming budgets | 38.5 against 39.4; the process held as much memory (36 to 41 GB by run) | +| A submission's askings holding only their own pages (upstream pull request 697) | lock splitting | 39.4 against 39.7 without | +| Write-combined buffers with one copy on the card (upstream 481, `VICTORY_WC_BAR=1`) | | 39.4; the preparing thread 0.6 ms less | +| Two frames in the line (`VICTORY_SUBMIT_FRAMES=2`) | render-ahead queues | +0.4 once, nothing at the shipped settings; one more frame of delay | +| More submissions joined into one | draw-call batching | nothing, and the dark patch on the cell's wall in 3 runs of 5 | +| Asking the write tracker ahead, or on a helper thread; lock-free last-write stamps; barrier waits left out; the preparing thread on a core of its own; a shorter wait on the tracker's lock | | -1.2 to +0.5, none kept | +| 41 more programs of the ray-tracing structures' inputs left out | "effects off" patches | +0.3 | + +## What was not built, and what it could bring + +- **The game telling the layer what it wrote** (hooks on its descriptor writes, buffer writes and small copies). The tree + has one such patcher already, for stores that change nothing (above). The rest would save part of the preparing + thread's refreshes (6 to 9 of its 19 ms a frame). That thread is one of two things the frame waits for, so the gain + is bounded by the other: the title's own main thread. +- **The preparing thread in two stages.** The same bound. +- **The title's own ray tracing** (`VICTORY_BVH_BUILDER=1`). Not a speed method: it is what would make the light right. + Upstream measured 35 to 23.5 frames a second with it on an RTX 5080 and a picture more broken than without. +- Not tested, each needs something this session could not do: hardware-accelerated GPU scheduling (a restart), + large pages (a policy change and a new sign-in), overclocking. + +## What the frame waits for now + +- Not the card: half the pixels changes nothing, and it sits in its highest power state at 83 to 87 % busy. +- The title's own main thread and its render thread: in a timeline of the frame they are the longest chain in four + frames of five, about 22 ms of the title's own code. +- The layer's thread that prepares the card's work: 18 to 19 ms a frame. Slowing the layer's code shows how close + behind it is: the build that counts for the profile runs the same scene at 29.4. + +Frame generation is not in this table: it shows more frames (73 with FSR 3 at 2x here) and renders no more. From 5a86970cd963cd952e9ba38f0dc7560427717922 Mon Sep 17 00:00:00 2001 From: Kyle Soderlund <soderlun@msu.edu> Date: Sat, 28 Nov 2026 11:08:01 -0500 Subject: [PATCH 42/57] docs: the linker's row in what was tried for speed Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/speed-methods.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/speed-methods.md b/docs/speed-methods.md index 2a0f5a04a..af2d482d9 100644 --- a/docs/speed-methods.md +++ b/docs/speed-methods.md @@ -27,6 +27,7 @@ median, 31 to 32 at the 95th percentile, 35 to 36 at the 99th), and 40 with the | Method | Where it comes from | Measured | |---|---|---| | Profile-guided optimisation of the layer (counts taken in this scene; sixteen codegen units, since with one the optimiser ran over twenty minutes on the last crate and was stopped) | browsers, game engines, compilers themselves | 38.5 and 38.8 against 39.3, 39.0 and 38.8 in turn: nothing. (The build that takes the counts runs the scene at 29.4.) | +| Another linker (the toolchain's `rust-lld`) | build systems of large games | a build's matter only: the last crate again in 42 s against 44 s with the default linker, nearly all of it the compiler's own whole-program step. Not run in the game | | Half the pixels to draw (DLSS Performance, the scene at 960x540) | every modern game; dynamic resolution | 39.7 against 39.4 (Quality: 39.5). **The frame is not the card's** | | The NVIDIA driver's "prefer maximum performance" for the program, in place of the keep-awake loop | driver tweak guides | 38.2 against 39.4: the card was in its highest state before (P0 in 66 of 71 two-second samples, in 82 of 85 with the setting) | | That driver setting and the loop together | | 34.2, as the loop alone | From 7f6a7c9c62cb0bb32e1c51b8193d3a163f899bc3 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 16:57:48 +0000 Subject: [PATCH 43/57] Small and large texture pieces in blocks of their own (VICTORY_POOL_CLASSES=1, off by default) Mixed in the same 64 MiB blocks, thousands of 64 KiB textures and the few large ones leave holes as they come and go: 1.0 to 1.7 GB free in the texture blocks throughout the runs on an RTX 3070 Ti (8 GB), which the texture queue counts as room while a large texture finds no range in it. With the switch, pieces up to 256 KiB and larger ones are cut from blocks of their own; an emptied block takes either class. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/pool.rs | 108 ++++++++++++++++++++++++++++++--- 1 file changed, 99 insertions(+), 9 deletions(-) diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index f94df0483..4b6da36f6 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -76,6 +76,41 @@ fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize { } } +/// Pieces of up to this many bytes are of the small class ([`class_of`]). +const SMALL_PIECE: u64 = 256 << 10; + +/// The size class a texture's piece of `len` bytes is cut from: with +/// [`classes`], 1 for small pieces (up to [`SMALL_PIECE`]) and 2 for the +/// others, each from blocks of their own; 0 (any block, as before) without. +fn class_of(len: u64) -> u8 { + if !classes() { + return 0; + } + if len <= SMALL_PIECE { 1 } else { 2 } +} + +/// Whether textures' small and large pieces are cut from blocks of their own +/// (`VICTORY_POOL_CLASSES=1`; off by default). +/// +/// Mixed in the same 64 MiB blocks, the many small textures (13,363 of +/// 15,836 in pieces of 64 KiB on an 8 GiB card, Series S, [`stats_on`]) and +/// the few large ones leave holes between them as they come and go: 1,260 MB +/// of 3,648 free in 1,655 ranges there, and 1.0 to 1.7 GB free in the blocks +/// throughout the runs on an RTX 3070 Ti (2026-11-28), card memory the +/// texture queue counts as room while a large texture finds no range in it +/// and a new block is made. Kept apart, a small texture's hole is the next +/// small texture's place, and the large ones' blocks empty out and go. +fn classes() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_POOL_CLASSES").is_some_and(|v| v == "1"); + if on { + tracing::info!("texture blocks: small and large pieces in blocks of their own (VICTORY_POOL_CLASSES=1)"); + } + on + }) +} + /// Milliseconds until a piece given back is used again. (It was three /// frames, a tenth of a second while the title shows a loading screen at 30 /// a second, with up to 18 submissions in the air.) @@ -194,6 +229,8 @@ struct Block<B> { /// When that was (ms). #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] since: u64, + /// The size class of the pieces cut from it ([`class_of`]; 0: any). + class: u8, } struct Pool<B> { @@ -226,6 +263,20 @@ impl<B: Clone> Pool<B> { align: u64, now: u64, ripe: Ripe, + make: impl FnMut() -> Option<B>, + ) -> Option<(Piece, B, bool)> { + self.take_class(len, align, now, ripe, 0, make) + } + + /// [`Self::take_ripe`] from a block of size class `class` ([`class_of`]; + /// 0: any block, as before), or an empty one, which takes that class. + fn take_class( + &mut self, + len: u64, + align: u64, + now: u64, + ripe: Ripe, + class: u8, mut make: impl FnMut() -> Option<B>, ) -> Option<(Piece, B, bool)> { // With blocks made ahead, what would be an allocation of its own (and @@ -235,12 +286,22 @@ impl<B: Clone> Pool<B> { } self.rested(now); let mut found = None; - for (i, block) in self.blocks.iter_mut().enumerate() { - if let Some(block) = block - && ripe.is(block) - && let Some(start) = block.free.take(len, align) - { - found = Some((i, start)); + // Blocks of the class first, then empty ones of another (given the class). + for pass in 0..2 { + for (i, block) in self.blocks.iter_mut().enumerate() { + if let Some(block) = block + && ripe.is(block) + && (class == 0 || block.class == class || (pass == 1 && block.free.whole(BLOCK))) + && let Some(start) = block.free.take(len, align) + { + if class != 0 { + block.class = class; + } + found = Some((i, start)); + break; + } + } + if found.is_some() || class == 0 { break; } } @@ -258,7 +319,9 @@ impl<B: Clone> Pool<B> { None => { let memory = self.grow(now, &mut make)?; let i = self.add(memory, ripe.started); - (i, self.blocks[i].as_mut()?.free.take(len, align)?) + let block = self.blocks[i].as_mut()?; + block.class = class; + (i, block.free.take(len, align)?) } }; if ripe.ahead > 0 { @@ -300,7 +363,7 @@ impl<B: Clone> Pool<B> { self.blocks.len() - 1 } }; - self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made, since: crate::host::now_ms() }); + self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made, since: crate::host::now_ms(), class: 0 }); i } @@ -822,8 +885,9 @@ pub(crate) unsafe fn texture( } else { 0 }; + let class = class_of(info.SizeInBytes); #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] - let (piece, heap, again) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || { + let (piece, heap, again) = lock(&TEXTURES).take_class(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), class, || { let desc = D3D12_HEAP_DESC { SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -886,6 +950,32 @@ pub(crate) unsafe fn texture( mod tests { use super::*; + #[test] + fn small_and_large_pieces_keep_to_blocks_of_their_own() { + let made = std::cell::Cell::new(0u64); + let mut pool: Pool<u64> = Pool::new(SPARE_KEPT); + let mut make = || { + made.set(made.get() + 1); + Some(made.get()) + }; + let (small, a, _) = pool.take_class(65536, 65536, 0, Ripe::ALL, 1, &mut make).unwrap(); + let (large, b, _) = pool.take_class(4 << 20, 65536, 0, Ripe::ALL, 2, &mut make).unwrap(); + assert_ne!(a, b, "a large piece does not go into the small pieces' block"); + let (_, c, _) = pool.take_class(65536, 65536, 0, Ripe::ALL, 1, &mut make).unwrap(); + assert_eq!(a, c, "small pieces share their block"); + // Emptied, a block takes pieces of the other class. + pool.give(small, 0); + pool.give(large, 0); + let (_, d, _) = pool.take_class(65536, 65536, REST, Ripe::ALL, 1, &mut make).unwrap(); + assert_eq!(d, a); + let (_, e, _) = pool.take_class(1 << 20, 65536, REST, Ripe::ALL, 2, &mut make).unwrap(); + assert_eq!(e, b, "the emptied large block is used again, no new block"); + assert_eq!(made.get(), 2); + // Class 0: any block, as before. + let (_, f, _) = pool.take_class(65536, 65536, REST, Ripe::ALL, 0, &mut make).unwrap(); + assert!(f == a || f == b); + } + #[test] fn ranges_are_cut_aligned_and_join_again() { let mut r = Ranges::new(1024); From e2825530a35cd1f009f5c54c8c1a9a39faf508ad Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 17:58:34 +0000 Subject: [PATCH 44/57] Shaders and pipelines kept where VICTORY_SHADER_CACHE_DIR says A launcher that keeps the cache in a folder of its own may empty it: on an RTX 3070 Ti started by VILauncher, 7 of 11 sessions began with no translation and no pipeline library (about 2,250 shaders translated and 800 pipelines made again, the first cutscene black for a minute). A folder it does not know of keeps them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- apps/victory/src/run.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 2e645525a..8ecc1df36 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -102,6 +102,29 @@ fn title_executable(given: &Path) -> Result<std::path::PathBuf> { } } +/// The folder of the translated shaders, with the pipelines beside it: +/// `<VICTORY_SHADER_CACHE_DIR>\shaders` where that is set, else the cache's +/// `shaders`. +/// +/// A launcher that keeps the cache in a folder of its own may empty it: on +/// an RTX 3070 Ti started by VILauncher, 7 of 11 sessions in a day began +/// with no translation and no pipeline library (hits=0, about 2,250 +/// shaders translated and 800 pipelines made again, the first cutscene +/// black for a minute), the sessions after a change of its launch options +/// or an update. A folder it does not know of keeps them. +#[cfg(windows)] +fn shader_cache_dir(cfg: &victory_core::Config) -> Result<std::path::PathBuf> { + match std::env::var_os("VICTORY_SHADER_CACHE_DIR").filter(|v| !v.is_empty()) { + Some(root) => { + let dir = std::path::PathBuf::from(root).join("shaders"); + std::fs::create_dir_all(&dir).with_context(|| format!("creating {} (VICTORY_SHADER_CACHE_DIR)", dir.display()))?; + println!("shaders kept in {} (VICTORY_SHADER_CACHE_DIR)", dir.display()); + Ok(dir) + } + None => cfg.cache_subdir("shaders"), + } +} + #[cfg(windows)] pub fn run( exe: &Path, @@ -226,7 +249,7 @@ pub fn run( } else { cfg.cache_subdir("images")? }; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + victory_hle::modules::d3d12x::use_shader_cache(shader_cache_dir(&cfg)?); 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 From a1c607e0ba92f779dfa6602612aa4b35b0f11d3e Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 18:21:00 +0000 Subject: [PATCH 45/57] Shaders: VICTORY_WATERFALL_SHAPE=0 leaves Neo's proof of waterfalls by their shape out On an RTX 3070 Ti, after the merge of VIctory-Neo, the skin of a face in a cutscene came out as coloured stripes (as nothing in a run before), where the build before drew it right. The switch, part of the shader cache's key, tells whether it is that proof. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/shader_cache.rs | 1 + crates/victory-shader/src/resource.rs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 39687d8b7..c35a28d94 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -81,6 +81,7 @@ fn build() -> [u8; 32] { "VICTORY_THREAD_TICKET", "VICTORY_LDS_LOOP_ATOMICS", "VICTORY_LDS_BOUNDS", + "VICTORY_WATERFALL_SHAPE", ] { bytes.extend_from_slice(name.as_bytes()); bytes.push(b'='); diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index ae16c51ed..cc789469f 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -368,7 +368,7 @@ pub fn track( let proof = t .waterfall(block, &accesses, &reads) .ok() - .or_else(|| t.waterfall_shape(block, &accesses, &reads, &loads)); + .or_else(|| waterfall_shape_on().then(|| t.waterfall_shape(block, &accesses, &reads, &loads)).flatten()); if let Some(proof) = proof { out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); @@ -2692,6 +2692,20 @@ pub(crate) fn inline(code: u8) -> Option<u32> { } } +/// Whether a waterfall loop the per-lane form cannot follow is still proven +/// by its exact shape ([`Tracer::waterfall_shape`], VIctory-Neo 37b0ace; +/// `VICTORY_WATERFALL_SHAPE=0`: not, as before). Part of the shader cache's +/// key (`victory_gpu::shader_cache`). +/// +/// On an RTX 3070 Ti the skin of a face in a cutscene came out as coloured +/// stripes, and in a run before that as nothing, where the build before +/// the merge drew it right (2026-11-28): this switch tells whether it is +/// this proof. +fn waterfall_shape_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WATERFALL_SHAPE").is_none_or(|v| v != "0")) +} + #[cfg(test)] pub(crate) mod tests { use super::*; From 3e16f0dc2fb00f58e073a3a7ccc0f2c1b3138553 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 18:35:45 +0000 Subject: [PATCH 46/57] Shaders: waterfalls proven by their shape off by default (VICTORY_WATERFALL_SHAPE=1 turns it on) On an RTX 3070 Ti it drew the skin of a face in a cutscene as coloured stripes (as nothing in another run); with it off the same shot was right. The shader cache's key holds its effect, not its switch's text, so that a translation cached with it on (VIctory-Neo's default) is not served without it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/shader_cache.rs | 4 ++++ crates/victory-shader/src/resource.rs | 14 +++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index c35a28d94..8aceb1b8d 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -60,6 +60,10 @@ fn build() -> [u8; 32] { bytes.extend_from_slice(&limit.to_le_bytes()); // Which group barriers wait is part of the translation too. bytes.push(victory_shader::emit::group_sync()); + // And whether waterfalls are proven by their shape: by its effect, not + // its switch's text, since the default changed (on in VIctory-Neo, off + // here) and a translation cached with it on must not be served without. + bytes.extend_from_slice(if victory_shader::resource::waterfall_shape_on() { b"shape1" } else { b"shape0" }); // So are the switches that pick the form of a wave64 program: // without them here a run with `VICTORY_WAVE_WIDE=0` was // served the translations an earlier run of the same diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index cc789469f..70e471e9d 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2694,16 +2694,16 @@ pub(crate) fn inline(code: u8) -> Option<u32> { /// Whether a waterfall loop the per-lane form cannot follow is still proven /// by its exact shape ([`Tracer::waterfall_shape`], VIctory-Neo 37b0ace; -/// `VICTORY_WATERFALL_SHAPE=0`: not, as before). Part of the shader cache's -/// key (`victory_gpu::shader_cache`). +/// `VICTORY_WATERFALL_SHAPE=1`; off by default in this fork). Its effect is +/// part of the shader cache's key (`victory_gpu::shader_cache`). /// /// On an RTX 3070 Ti the skin of a face in a cutscene came out as coloured -/// stripes, and in a run before that as nothing, where the build before -/// the merge drew it right (2026-11-28): this switch tells whether it is -/// this proof. -fn waterfall_shape_on() -> bool { +/// stripes with it, and in a run before that as nothing; with +/// `VICTORY_WATERFALL_SHAPE=0` the same shot drew the face right +/// (2026-11-28). It saved some 3 ms of the card a frame on an RTX 3090 Ti. +pub fn waterfall_shape_on() -> bool { static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WATERFALL_SHAPE").is_none_or(|v| v != "0")) + *ON.get_or_init(|| std::env::var_os("VICTORY_WATERFALL_SHAPE").is_some_and(|v| v == "1")) } #[cfg(test)] From e6140be83baca0aaba4ff9757e965f623fa6150f Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 19:33:23 +0000 Subject: [PATCH 47/57] Cores: VICTORY_OWN_CPUS=auto only where the title's sixteen processors are one die; the 9900X guide's final settings On a Ryzen 9 9900X (dies of twelve) four of the title's sixteen processors lie on the other die, and the layer's threads crowded there beside them: frames of 3,500 to 5,000 draws took 63.9 ms with auto and 44.7 ms without (RTX 3070 Ti). auto now leaves such a processor as it is. docs/ryzen-9900x-rtx-3070ti.md: what was measured on that PC, the settings it ended with, and what did not work. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/cores.rs | 27 +++++- docs/ryzen-9900x-rtx-3070ti.md | 152 +++++++++++++++++++------------- 2 files changed, 119 insertions(+), 60 deletions(-) diff --git a/crates/victory-gpu/src/cores.rs b/crates/victory-gpu/src/cores.rs index 4f54d7135..ec9f2f8c9 100644 --- a/crates/victory-gpu/src/cores.rs +++ b/crates/victory-gpu/src/cores.rs @@ -83,14 +83,28 @@ fn cpus() -> Vec<Cpu> { all } +/// The processors the title keeps its threads on: the console's sixteen, +/// the first sixteen here. +const TITLE_PROCESSORS: usize = 16; + /// The processors `asked` names among `all`: `<first>-<last>` by their /// numbers; `auto`, those of every last-level cache but the one processor 0 -/// has, if there is more than one (a processor of two dies). `None`: not +/// has, if there is more than one (a processor of two dies) and processor +/// 0's holds the title's sixteen ([`TITLE_PROCESSORS`]). `None`: not /// understood, or none. fn own_of(asked: &str, all: &[Cpu]) -> Option<Vec<u32>> { let asked = asked.trim(); let chosen: Vec<u32> = if asked.eq_ignore_ascii_case("auto") { let first = all.iter().find(|c| c.logical == 0)?.cache; + // The title keeps its threads on the first sixteen processors: only + // where those are one die is the other die free for ours. On a die of + // twelve (a Ryzen 9 9900X) four of the title's sixteen lie on the + // other die, and ours crowded there beside them: the frame of 3,500 to + // 5,000 draws 63.9 ms where it was 44.7 with ours on every processor + // (RTX 3070 Ti, 2026-11-28). + if all.iter().filter(|c| c.cache == first).count() < TITLE_PROCESSORS { + return None; + } all.iter().filter(|c| c.cache != first).map(|c| c.id).collect() } else { let (from, to) = asked.split_once('-')?; @@ -429,6 +443,17 @@ mod tests { std::thread::spawn(|| keep_on_fast_cores("test")).join().unwrap(); } + #[test] + fn auto_takes_the_other_die_only_where_the_first_holds_the_titles_sixteen() { + let dies = |per: u8| -> Vec<Cpu> { (0..per * 2).map(|i| Cpu { id: 256 + u32::from(i), logical: i, cache: i / per }).collect() }; + // 9950X: two dies of sixteen: the second. + assert_eq!(own_of("auto", &dies(16)), Some((272..288).collect())); + // 9900X: two dies of twelve: the title's sixteen spill over, none. + assert_eq!(own_of("auto", &dies(12)), None); + // A range is taken as asked, whatever the dies. + assert_eq!(own_of("12-23", &dies(12)), Some((268..280).collect())); + } + #[test] fn two_dies_of_alike_cores_keep_one_die() { // A 9900X: 24 sets, 12 on each die's cache; no ranking given: the first die. diff --git a/docs/ryzen-9900x-rtx-3070ti.md b/docs/ryzen-9900x-rtx-3070ti.md index ba949c03a..de3198519 100644 --- a/docs/ryzen-9900x-rtx-3070ti.md +++ b/docs/ryzen-9900x-rtx-3070ti.md @@ -1,67 +1,101 @@ # Ryzen 9 9900X, RTX 3070 Ti 8 GB, 32 GB DDR5 -What the layer does for this kind of PC on its own, and the settings to -start from. Not measured on this exact PC yet: compare with a log of each run -(F3 shows frame rate, VRAM and RAM) and report what you find. - -## What the code does by itself - -- **The layer's frame threads stay on one die of the 9900X.** Its twelve - cores sit on two dies (CCDs) of six, each with its own 32 MB L3. The - threads a frame waits for hand their work to each other; across the two - dies every hand-over goes over the link between them, at several times the - latency. They are now kept on the die of the system's preferred cores - (`crates/victory-gpu/src/cores.rs`, `one_cache_of`). The title's own - threads and the list translators keep both dies. `VICTORY_ONE_CCD=0` - turns it off, to compare. Single-die Ryzens (9700X, 9800X3D) and Intel's - hybrid cores are not affected. -- **8 GB cards keep less room for render targets.** The texture queue held - back a flat 3,072 MB for render targets not made yet, measured on 12 GB - cards. On an 8 GB card that is 40-60 % of the budget, and the picture - stayed black while textures waited for room (docs/windows-memory.md). It - is now at most three tenths of the budget (about 2.1 GB of a 7.2 GB - budget); 12 GB cards and up are unchanged. - `VICTORY_CARD_ROOM_FOR_TARGETS_MB=<n>` still sets it by hand. -- **32 GB of RAM counts as limited**, so 8 pipeline workers at most and - smaller idle caches (already so before). - -## Settings to start from - -| | | -|---|---| -| Console profile | **Series S** (F1, CONSOLE). Series X at 1440p needs more than 8 GB of VRAM for its targets and textures together | -| DLSS | **Quality** (720p inside, 1080p out); Performance (540p) if the GPU is the limit | -| Frame generation | **FSR 3, 2x** (DLSS frame generation needs an RTX 40). It takes 1.5-2 GB of VRAM: off if textures come late or the F3 panel shows VRAM over the budget | -| Frame rate cap | 60, or your monitor's rate with frame generation | -| Build | `-Build native` (below) | - -```powershell -.\scripts\play-nvidia.ps1 -Exe 'D:\Games\MyDump\game_scarlett_master.exe' -SeriesS -Dlss quality -Build native -``` +What was measured on one such PC on 2026-11-28 (Windows 11, the layer started +by VILauncher with `victory run`), the settings it ended with, and what did not +work. Frame rates are the layer's own count; scenes are told apart by their +draws a frame. + +## Where it ended -`victory.exe` alone: `victory.exe play --series-s --dlss quality --fps 60`. +| Scene (draws a frame) | At the start | At the end | +| --- | --- | --- | +| Light cutscenes (1,000-2,000) | 6-14, VRAM past its budget | 29-30 (the title's own cap) | +| Heavy cutscenes, the boat (3,500-5,000) | about 17 | about 22-23 | +| The beach (5,000-8,000) | 6-9, textures in patches | about 18-19, textures whole | +| Seconds without a frame over 50 ms | about 25 % | about 47 % | +| First cutscene of a session | black for a minute, every session | right from the second session on | -## A build for this CPU +## Settings (VILauncher: Arguments and Switches) -`-Build native` builds `target\native\victory.exe` with the CPU's own -instructions (`-C target-cpu=native`: AVX-512 on Zen 5) and one optimisation -over the whole program (`[profile.native]` in `Cargo.toml`: fat LTO, one code -generation unit). It takes several minutes more to build and runs only on a -CPU with the same instructions. It helps the CPU side (shader translation, -hashing, copies), not the GPU. By hand: +Arguments: `--console series-s` -```powershell -$env:RUSTFLAGS = '-C target-cpu=native'; cargo build --locked --profile native -p victory +Switches, on top of VILauncher's `play-foxhound` preset: + +``` +VICTORY_DLSS=1 +VICTORY_DLSS_MODE=quality +VICTORY_STREAMLINE_DIR=C:\NVIDIA\Streamline\bin\x64 +VICTORY_SHADER_CACHE_DIR=C:\VictoryCache +VICTORY_CARD_AWAKE=0 +VICTORY_FAULT_UNLOCKED=1 +VICTORY_STORE_BESIDE=1 +VICTORY_POOL_CLASSES=1 +VICTORY_HELPER_PRIORITY=1 +VICTORY_TEXSPK_PASS_MS=8 +VICTORY_PASSES_HOT=1 +VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS=5000 +VICTORY_AMBIENT_REFLECT=1 +VICTORY_AMBIENT_REFLECT_IN=CS_TemporalResolve2_Opaque,CS_TemporalResolve1_Alpha +VICTORY_AMBIENT_ALPHA=4 +VICTORY_LOG_FILE=C:\Users\<you>\Desktop\victory-log.txt ``` -## Windows - -- **A page file**, managed by Windows. With 32 GB of RAM and none, the first - scene load ran out of commit (docs/windows-memory.md). -- **AMD chipset driver** installed: it tells Windows which cores are - preferred, and so which die the layer's threads keep. -- **Resizable BAR** on in the BIOS (an RTX 30 supports it) and - **hardware-accelerated GPU scheduling** on (needed for frame generation). -- **EXPO** on for the DDR5, so it runs at its rated speed. -- Close programs that hold VRAM (browsers with video, overlays): every MB of - the 8 GB counts. +NVIDIA's files: `scripts\get-nvidia-sdks.ps1 -To C:\NVIDIA`. Optional: +`VICTORY_WATER_LIGHT=0` takes away the dark blocks in the water behind boats +(the water is then bluer and darker; no frame rate either way). + +Not set, on purpose: `VICTORY_OWN_CPUS` (below), `VICTORY_THIN_THREADS`, +`VICTORY_FRAME_INTERVAL_US` (a cap under the title's rate made cutscenes +stutter and cut their sound), frame generation (below). + +## The PC itself + +- **The graphics card in PCIe x16.** It ran at 4.0 x8: on the Gigabyte X870E + AORUS PRO an M.2 drive in `M2B_CPU` or `M2C_CPU` halves the graphics slot. + The drive moved to another slot: x16, 25 to 28 frames a second where the + card waited for memory read over the bus. Check with + `nvidia-smi --query-gpu=pcie.link.width.current --format=csv`. +- **A page file of 16 to 32 GB.** With 32 GB of RAM the system's commit + limit, not the RAM, ran out (3.8 GB left with 7.1 GB of RAM free), and the + layer held back texture prefetch for the whole session. +- **Other programs closed.** With a browser and the rest open, 3 GB of RAM + was left and the same holding back came on. +- The NVIDIA driver's shader cache at its largest. + +## What the code does for it + +- A render target reserve sized to an 8 GB card, given up once the targets + hold 1 GiB (the Series S profile's never reached half of the flat 3,072 MB, + which stayed kept for whole runs while textures waited). +- `VICTORY_SHADER_CACHE_DIR`: VILauncher emptied its cache folder after a + change of its options or an update (7 of 11 sessions began with no + translation and no pipeline library). +- `VICTORY_POOL_CLASSES`: small and large textures in blocks of their own. +- VIctory-Neo's merge (KyleS98): no keep-awake loop on the card, write faults + without the write watch's lock, the reflections' hold indoors. +- `VICTORY_OWN_CPUS=auto` does nothing on a die of twelve: the title's sixteen + processors spill onto the other die, and the layer's threads crowded there + beside them (heavy scenes 16.5 frames a second with it, 22.6 without). +- VIctory-Neo's proof of waterfalls by their shape is off + (`VICTORY_WATERFALL_SHAPE=1` turns it on): it drew a face's skin as coloured + stripes. It was worth 3 to 5 frames a second on the boat. + +## What did not work + +| Tried | What came of it | +| --- | --- | +| `VICTORY_VRAM_BUDGET_MB=5000` | 3 fps: what left the card went to the PC's memory, read over the bus | +| `VICTORY_SELECTIVE_BARRIERS` (no wait for barrier groups that order no write) | 4 % of the groups qualified, and the title stopped submitting: 3.5 fps | +| `VICTORY_INDIRECT_ONE_WAIT` | No indirect command is clamped one at a time in this build | +| Leaving out the title's heaviest passes | Nothing measured (0.3-1 ms each) for what they may draw | +| `VICTORY_WATER_LIGHT=0` for speed | The same frame rate | +| `VICTORY_THIN_THREADS=12` with more pool threads | Textures and light came later | +| `VICTORY_THIN_THREADS=6` with `VICTORY_OWN_CPUS=auto` | Slower everywhere: more threads on the same twelve processors | +| FSR 3 frame generation 2x | 40-59 shown, but on 8 GB the textures waited and cutscenes went black while pipelines were made | + +## What the frame waits for now + +The card at 70-93 % busy in light scenes; in heavy ones the title's own +threads and the layer's thread that prepares submissions (35-45 ms a frame +at 4,000 draws and more). Thousands of small commands, each between waits the +title asks for, keep the card at about half its power. From 8a9b37c376efeb35ccfb31f5330a92fea542472e Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 19:38:28 +0000 Subject: [PATCH 48/57] Shaders: VICTORY_WATERFALL_SHAPE=compute proves waterfalls by their shape in compute programs only Neo's proof in every stage drew a face's skin as coloured stripes on an RTX 3070 Ti; without it heavy cutscenes lose 3 to 5 frames a second to the card. compute keeps it where no face is drawn (Neo's 3.5 ms program was a compute one). The mode is part of the shader cache's key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/shader_cache.rs | 3 +- crates/victory-shader/src/resource.rs | 39 ++++++++++++++++++-------- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 8aceb1b8d..8bdd3a92b 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -63,7 +63,8 @@ fn build() -> [u8; 32] { // And whether waterfalls are proven by their shape: by its effect, not // its switch's text, since the default changed (on in VIctory-Neo, off // here) and a translation cached with it on must not be served without. - bytes.extend_from_slice(if victory_shader::resource::waterfall_shape_on() { b"shape1" } else { b"shape0" }); + bytes.extend_from_slice(b"shape"); + bytes.push(b'0' + victory_shader::resource::waterfall_shape_mode()); // So are the switches that pick the form of a wave64 program: // without them here a run with `VICTORY_WAVE_WIDE=0` was // served the translations an earlier run of the same diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 70e471e9d..53f518336 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -368,7 +368,7 @@ pub fn track( let proof = t .waterfall(block, &accesses, &reads) .ok() - .or_else(|| waterfall_shape_on().then(|| t.waterfall_shape(block, &accesses, &reads, &loads)).flatten()); + .or_else(|| waterfall_shape_for(stage).then(|| t.waterfall_shape(block, &accesses, &reads, &loads)).flatten()); if let Some(proof) = proof { out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); @@ -2692,18 +2692,35 @@ pub(crate) fn inline(code: u8) -> Option<u32> { } } -/// Whether a waterfall loop the per-lane form cannot follow is still proven -/// by its exact shape ([`Tracer::waterfall_shape`], VIctory-Neo 37b0ace; -/// `VICTORY_WATERFALL_SHAPE=1`; off by default in this fork). Its effect is -/// part of the shader cache's key (`victory_gpu::shader_cache`). +/// Where a waterfall loop the per-lane form cannot follow is still proven +/// by its exact shape ([`Tracer::waterfall_shape`], VIctory-Neo 37b0ace), +/// as `VICTORY_WATERFALL_SHAPE` says: `1`, in every stage (Neo's way); +/// `compute`, in compute programs only; anything else or unset, nowhere (as +/// before Neo). The answer is part of the shader cache's key +/// (`victory_gpu::shader_cache`, [`waterfall_shape_mode`]). /// /// On an RTX 3070 Ti the skin of a face in a cutscene came out as coloured -/// stripes with it, and in a run before that as nothing; with -/// `VICTORY_WATERFALL_SHAPE=0` the same shot drew the face right -/// (2026-11-28). It saved some 3 ms of the card a frame on an RTX 3090 Ti. -pub fn waterfall_shape_on() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_WATERFALL_SHAPE").is_some_and(|v| v == "1")) +/// stripes with it in every stage, and in a run before that as nothing; +/// without it the same shot drew the face right (2026-11-28). It saved some +/// 3 ms of the card a frame on an RTX 3090 Ti (one compute program alone +/// 3.5 ms), and 3 to 5 frames a second on the boat here: `compute` is for +/// keeping that where no face is drawn. +pub fn waterfall_shape_mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_WATERFALL_SHAPE").as_deref().map(str::trim) { + Ok("1") => 2, + Ok("compute") => 1, + _ => 0, + }) +} + +/// Whether [`waterfall_shape_mode`] proves waterfalls by their shape in `stage`. +fn waterfall_shape_for(stage: HwStage) -> bool { + match waterfall_shape_mode() { + 2 => true, + 1 => matches!(stage, HwStage::Cs), + _ => false, + } } #[cfg(test)] From adbf7fda8540df581248163e8ae657f19b19dae9 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 20:12:32 +0000 Subject: [PATCH 49/57] Shaders, docs: VICTORY_WATERFALL_SHAPE=compute broke a face too A policewoman's skin came out as coloured noise in a cutscene with the proof in compute programs alone (the skin is made in a compute pass), for 4 frames a second in scenes of 2,000 to 3,500 draws and nothing in heavier ones. Off, the default, is the only setting that draws every face. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-shader/src/resource.rs | 8 ++++++-- docs/ryzen-9900x-rtx-3070ti.md | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 53f518336..0330dc43c 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2703,8 +2703,12 @@ pub(crate) fn inline(code: u8) -> Option<u32> { /// stripes with it in every stage, and in a run before that as nothing; /// without it the same shot drew the face right (2026-11-28). It saved some /// 3 ms of the card a frame on an RTX 3090 Ti (one compute program alone -/// 3.5 ms), and 3 to 5 frames a second on the boat here: `compute` is for -/// keeping that where no face is drawn. +/// 3.5 ms), and 3 to 5 frames a second on the boat here. `compute` was for +/// keeping that where no face is drawn, but it broke one too (a policewoman's +/// skin as coloured noise in a cutscene, the same day): the skin is made in +/// a compute pass before it is drawn. It gained 4 frames a second in scenes +/// of 2,000 to 3,500 draws and nothing in heavier ones. Off is the only +/// setting that draws every face right. pub fn waterfall_shape_mode() -> u8 { static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); *MODE.get_or_init(|| match std::env::var("VICTORY_WATERFALL_SHAPE").as_deref().map(str::trim) { diff --git a/docs/ryzen-9900x-rtx-3070ti.md b/docs/ryzen-9900x-rtx-3070ti.md index de3198519..1aff3d3dd 100644 --- a/docs/ryzen-9900x-rtx-3070ti.md +++ b/docs/ryzen-9900x-rtx-3070ti.md @@ -78,7 +78,9 @@ stutter and cut their sound), frame generation (below). beside them (heavy scenes 16.5 frames a second with it, 22.6 without). - VIctory-Neo's proof of waterfalls by their shape is off (`VICTORY_WATERFALL_SHAPE=1` turns it on): it drew a face's skin as coloured - stripes. It was worth 3 to 5 frames a second on the boat. + stripes. It was worth 3 to 5 frames a second on the boat. In compute + programs alone (`VICTORY_WATERFALL_SHAPE=compute`) it broke another face + and gained only in scenes of 2,000 to 3,500 draws. ## What did not work From 0b5458155555188c2ad38f66e2ea205637357fa0 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 20:43:59 +0000 Subject: [PATCH 50/57] docs: the 9900X guide with DLSS Performance and FSR 3 frame generation (60 shown in light cutscenes, 43-52 in heavy ones) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- docs/ryzen-9900x-rtx-3070ti.md | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/docs/ryzen-9900x-rtx-3070ti.md b/docs/ryzen-9900x-rtx-3070ti.md index 1aff3d3dd..c1cb1f25d 100644 --- a/docs/ryzen-9900x-rtx-3070ti.md +++ b/docs/ryzen-9900x-rtx-3070ti.md @@ -9,10 +9,11 @@ draws a frame. | Scene (draws a frame) | At the start | At the end | | --- | --- | --- | -| Light cutscenes (1,000-2,000) | 6-14, VRAM past its budget | 29-30 (the title's own cap) | -| Heavy cutscenes, the boat (3,500-5,000) | about 17 | about 22-23 | -| The beach (5,000-8,000) | 6-9, textures in patches | about 18-19, textures whole | -| Seconds without a frame over 50 ms | about 25 % | about 47 % | +| Light cutscenes (1,000-2,000) | 6-14, VRAM past its budget | 30 rendered (the title's own cap), 60 shown | +| Medium cutscenes (2,000-3,500) | 19-25 | 26 rendered, about 52 shown | +| Heavy cutscenes, the boat (3,500-5,000) | about 17 | 24 rendered, about 48 shown | +| The beach (5,000-8,000) | 6-9, textures in patches | 22 rendered, about 43 shown, textures whole | +| Frames over 50 ms, a second | 4-6 | about 3 | | First cutscene of a session | black for a minute, every session | right from the second session on | ## Settings (VILauncher: Arguments and Switches) @@ -23,8 +24,12 @@ Switches, on top of VILauncher's `play-foxhound` preset: ``` VICTORY_DLSS=1 -VICTORY_DLSS_MODE=quality +VICTORY_DLSS_MODE=performance VICTORY_STREAMLINE_DIR=C:\NVIDIA\Streamline\bin\x64 +VICTORY_FSR_FRAMEGEN=1 +VICTORY_FRAMEGEN_X=2 +VICTORY_FIDELITYFX_DIR=C:\FSR +VICTORY_TEXTURE_ROOM_PERCENT=90 VICTORY_SHADER_CACHE_DIR=C:\VictoryCache VICTORY_CARD_AWAKE=0 VICTORY_FAULT_UNLOCKED=1 @@ -40,13 +45,18 @@ VICTORY_AMBIENT_ALPHA=4 VICTORY_LOG_FILE=C:\Users\<you>\Desktop\victory-log.txt ``` -NVIDIA's files: `scripts\get-nvidia-sdks.ps1 -To C:\NVIDIA`. Optional: +NVIDIA's files: `scripts\get-nvidia-sdks.ps1 -To C:\NVIDIA`; AMD's: +`scripts\get-amd-fsr.ps1 -To C:\FSR`. DLSS Performance (540p inside the +Series S profile's 1080p) is what made room on the card for FSR 3 frame +generation, and it rendered faster in heavy scenes too (24 against 22.6 at +3,500-5,000 draws, 22 against 18.6 at the beach) where Quality's 720p did not +look worth it next to frame generation. Optional: `VICTORY_WATER_LIGHT=0` takes away the dark blocks in the water behind boats (the water is then bluer and darker; no frame rate either way). Not set, on purpose: `VICTORY_OWN_CPUS` (below), `VICTORY_THIN_THREADS`, `VICTORY_FRAME_INTERVAL_US` (a cap under the title's rate made cutscenes -stutter and cut their sound), frame generation (below). +stutter and cut their sound). ## The PC itself @@ -93,7 +103,7 @@ stutter and cut their sound), frame generation (below). | `VICTORY_WATER_LIGHT=0` for speed | The same frame rate | | `VICTORY_THIN_THREADS=12` with more pool threads | Textures and light came later | | `VICTORY_THIN_THREADS=6` with `VICTORY_OWN_CPUS=auto` | Slower everywhere: more threads on the same twelve processors | -| FSR 3 frame generation 2x | 40-59 shown, but on 8 GB the textures waited and cutscenes went black while pipelines were made | +| FSR 3 frame generation 2x with DLSS Quality | 40-59 shown, but on 8 GB the textures waited and cutscenes went black while pipelines were made (with DLSS Performance, the shader cache and the texture block classes it fits: above) | ## What the frame waits for now From 0f8cc2033d8869eae285b6e91d558d877e9811d1 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:12:18 -0800 Subject: [PATCH 51/57] Merge pull request #81 (cherry picked from commit 60a6ca85fd24af311b363bc2eba53445822fe327) --- crates/victory-gpu/src/pipeline/library.rs | 43 +++++++++++++++++++++- crates/victory-gpu/src/pipeline/make.rs | 2 +- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 06db5a1e9..40f1f5632 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -637,15 +637,56 @@ pub(crate) fn pipeline( Ok(pso) } +/// As [`save`], from a worker while more pipelines are still queued. +/// +/// Every save serialises the whole library (over a gigabyte once it is warm) +/// and, while it does, holds off every store; in the middle of a burst of new +/// pipelines (a new area, a cutscene) that is exactly when the title is +/// waiting on them, and the write competes with texture streaming for the +/// disk. Saves in a burst are kept to one every `VICTORY_LIBRARY_SAVE_BUSY_S` +/// seconds (default 180; 20 as before); the save when the queue runs dry and +/// the one at exit are as they were. +pub(crate) fn save_while_busy() { + static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); + static EVERY: OnceLock<std::time::Duration> = OnceLock::new(); + let every = *EVERY.get_or_init(|| { + let secs = std::env::var("VICTORY_LIBRARY_SAVE_BUSY_S").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(180); + std::time::Duration::from_secs(secs) + }); + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + match *last { + // The first busy save of the run waits a full interval too. + None => { + *last = Some(std::time::Instant::now()); + return; + } + Some(t) if t.elapsed() < every => return, + _ => *last = Some(std::time::Instant::now()), + } + } + save(false); +} + /// Writes the library and the early list if pipelines were added since the /// last save and `SAVE_EVERY` has passed (or `now`). +/// +/// Under host memory pressure ([`crate::residency::pressured`]) the interval +/// is `SAVE_EVERY_PRESSURED` instead: the serialised library (over a gigabyte +/// once warm) is written through the PC's memory, and on a 32 GB PC that ran +/// pressured for a whole session (log of 2026-11-27, commit headroom 3.4 GB) +/// those pages pushed the title's own out, and its threads stalled on page +/// faults. The save at exit (`now`) is unchanged, so nothing made is lost +/// unless the process ends without one. pub(crate) fn save(now: bool) { static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); + const SAVE_EVERY_PRESSURED: std::time::Duration = std::time::Duration::from_secs(600); let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; { let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); - if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + let every = if crate::residency::pressured() { SAVE_EVERY_PRESSURED } else { SAVE_EVERY }; + if !now && last.is_some_and(|t| t.elapsed() < every) { return; } *last = Some(std::time::Instant::now()); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 226f47843..22d903b01 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -599,7 +599,7 @@ fn workers() -> bool { if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { - super::library::save(false); + super::library::save_while_busy(); } } }); From 7fae2b2d33b670ce8fe07c40f8c7b43cb365d199 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:13:44 -0800 Subject: [PATCH 52/57] Merge pull request #1179 (cherry picked from commit 20c79c6fa3b3628e68656e1c3c777c0e5ecb3fa8) --- crates/victory-gpu/src/descriptor/host.rs | 33 ++++++++++++++--------- crates/victory-gpu/src/resource.rs | 8 +++++- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index d331dd46e..2c129cb24 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -3197,14 +3197,17 @@ impl HostHeap { if key == 0 { return; } - match view_at(key as u32, (key >> 32) as u32) { - Some(view) => null_for(&view, self.at(index)), - None => null_view(self.at(index)), - } + let kept = match view_at(key as u32, (key >> 32) as u32) { + Some(view) => neutral_for(&view, self.at(index)), + None => { + null_view(self.at(index)); + None + } + }; self.put(index); self.clear_twin(index); self.write_stride(index, 0); - self.keep(index, None); + self.keep(index, kept); } /// The slots [`HostHeap::note_buffer`] found stale for slot `index`, with @@ -3520,13 +3523,15 @@ impl HostHeap { /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { let kept = make_twinned(view, self.at(index), self.twin(index)); - if kept.is_none() { - null_for(view, self.at(index)); - } + let stand_in = if kept.is_none() { + neutral_for(view, self.at(index)) + } else { + None + }; self.put(index); self.twin_made(index, kept.is_some() && twinned(view)); self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 }); - self.keep(index, kept.flatten()); + self.keep(index, kept.flatten().or(stand_in)); } /// Makes slot `index` (a dynamic one) the view the record `words` names, @@ -4092,14 +4097,16 @@ impl HostHeap { } else { make_twinned(&view, self.at(index), self.twin(index)) }; - if kept.is_none() && !self.sampler { - null_for(&view, self.at(index)); - } + let stand_in = if kept.is_none() && !self.sampler { + neutral_for(&view, self.at(index)) + } else { + None + }; if kept.is_some() || !self.sampler { self.put(index); } self.twin_made(index, kept.is_some() && twinned(&view)); - self.keep(index, kept.flatten()); + self.keep(index, kept.flatten().or(stand_in)); self.quick_is(index, if later { 0 } else { key }); drop(held); self.unmake_stale(index, stale); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index d10bde7fd..db18104b0 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2620,6 +2620,10 @@ fn slot_evict(video: Option<[u64; 4]>, idle_ms: u64, frames: u64) { frame_at(&ring, now_ms.saturating_sub(idle_ms)) }; static EVICTING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let line_pct = (room_line(budget) * 100 / budget.max(1)).clamp(50, 97); + let high = high.min(line_pct); + let low = low.min(high.saturating_sub(5).max(40)); + let used = used.saturating_sub(crate::pool::texture_room()); let (on, need) = slot_plan(EVICTING.load(Relaxed), budget, used, high, low, cap); EVICTING.store(on, Relaxed); SLOT_STATE[0].store(u64::from(on), Relaxed); @@ -5251,7 +5255,9 @@ float4 lit() : SV_Target { return 1.0; } const MIB: u64 = 1 << 20; let most = 3072 * MIB; // Before the world: kept, however long. - assert_eq!(targets_kept(most, 652 * MIB, 60_000, 20_000), 2420 * MIB); + assert_eq!(targets_kept(most, 652 * MIB, 300_000, 20_000), 2420 * MIB); + // On 8 GB GPUs / Series S / DLSS, world targets settle around 1,185-1,450 MB. + assert_eq!(targets_kept(most, 1185 * MIB, 25_000, 20_000), 0); // The world's first frames: still growing. assert_eq!(targets_kept(most, 2083 * MIB, 5_000, 20_000), 989 * MIB); // Settled: nothing kept. From 24a5d03b6f7256c31e1430babc5c875ca4f845fb Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:09:44 -0800 Subject: [PATCH 53/57] Merge pull request #949 (cherry picked from commit e09f44a7c8248abeff4b7b206c01de69a1652f2f) --- README.md | 3 +++ crates/victory-gpu/src/pipeline/host.rs | 7 ++++--- crates/victory-gpu/src/shader_cache.rs | 1 + crates/victory-shader/src/emit/mod.rs | 8 +++++++- xtask/src/policy.rs | 10 +++++++++- 5 files changed, 24 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f078eef64..351e49b01 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,9 @@ speed, in the picture and in simply being able to play it: card a frame. They are left out there: no blocks and 30 fps instead of 25 on the first boat ride (RTX 5070), with water that is darker and bluer. WATER LIGHT in the menu (`VICTORY_WATER_LIGHT=1`) runs them again. + `--set VICTORY_WATER_VOLUME_PORTALS=1` separately enables an experimental + lowering for the volume-portals compute shader on 32-lane hosts. An explicit + `VICTORY_WAVE_WIDE` setting takes precedence. - **One command to play**: the launcher builds the layer the first time and applies what the menu saved. - **`Get-NVIDIA-DLSS.cmd`**: the eight NVIDIA files that are loaded, about diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index d5343c84b..515d9a5aa 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -1237,14 +1237,15 @@ mod tests { 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. + // Subobject 21 (`DEPTH_STENCIL1`) enables depth bounds. + // Keep the depth buffer active. ALWAYS and a zero write mask leave + // depth bounds as the only test that can reject a fragment. #[repr(C, align(8))] struct Sub21(u32, D3D12_DEPTH_STENCIL_DESC1); let sub = Sub21( 21, D3D12_DEPTH_STENCIL_DESC1 { - DepthEnable: false.into(), + DepthEnable: true.into(), DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, DepthBoundsTestEnable: true.into(), diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 8bdd3a92b..971482886 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -71,6 +71,7 @@ fn build() -> [u8; 32] { // executable had cached with the switch unset. for name in [ "VICTORY_WAVE_WIDE", + "VICTORY_WATER_VOLUME_PORTALS", "VICTORY_WAVE_DEEP_SKIPS", "VICTORY_WAVE_OWN_BITS", "VICTORY_WAVE_LOCAL", diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index ac48b9ebf..c99131270 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -682,7 +682,13 @@ fn emit_once( ) || matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 128) && c.digest == [0x50, 0xcf, 0x28, 0x32, 0x8b, 0x58, 0x05, 0x3d, 0xa8, 0x9a, 0x8d, 0xa0, 0x1a, 0xa1, 0x23, 0xc6]; - let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1"); + // The preferred build validates this one additional 64-thread water + // lighting program with its wave-wide route. Keep it isolated for a + // matched trial on this renderer, where the lowering has diverged. + let water_portals = std::env::var_os("VICTORY_WATER_VOLUME_PORTALS").is_some_and(|v| v == "1") + && c.digest == [0x4f, 0xa5, 0x83, 0x20, 0xd7, 0x61, 0xbf, 0x55, 0x81, 0x20, 0xf9, 0x2c, 0x19, 0xd3, 0x84, 0xaa] + && matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64); + let wide_on = wide_option.as_ref().map_or(scene_kernel || water_portals, |v| v == "1"); // A single guest wave can iterate an active-lane loop until both host // halves have finished. The precise latch and convergence conditions // for the driver compute route are checked by widen(). diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs index e594017a5..d4d88be02 100644 --- a/xtask/src/policy.rs +++ b/xtask/src/policy.rs @@ -148,7 +148,8 @@ pub fn check(path: &str, content: &[u8]) -> Vec<String> { let mut problems = Vec::new(); let name = path.rsplit('/').next().unwrap_or(path); let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()); - let allowed = ALLOWED_NAMES.contains(&name) + let allowed = path == "bindings.ini" + || ALLOWED_NAMES.contains(&name) || ext .as_deref() .is_some_and(|e| ALLOWED_EXTENSIONS.contains(&e)); @@ -238,6 +239,13 @@ mod tests { assert!(check(".githooks/pre-commit", b"#!/bin/sh\n").is_empty()); } + #[test] + fn accepts_only_the_root_bindings_template_with_content_checks() { + assert!(check("bindings.ini", b"MoveUp = W\n").is_empty()); + assert!(!check("other/bindings.ini", b"MoveUp = W\n").is_empty()); + assert!(!check("bindings.ini", b"MZ\x90\0").is_empty()); + } + #[test] fn rejects_game_like_files() { assert!(!check("assets/tex.dds", b"DDS \x7c\0\0\0").is_empty()); From 6c877183749aed8348c873864a105e228c67d97f Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:09:44 -0800 Subject: [PATCH 54/57] Merge pull request #938 (cherry picked from commit e41744e8407f531cc504d18e39f0a539c557be7d) --- crates/victory-gpu/src/shader_cache.rs | 8 +++- crates/victory-shader/src/emit/lower.rs | 50 +++++++++++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 2 +- 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 971482886..2984c06b5 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -88,6 +88,7 @@ fn build() -> [u8; 32] { "VICTORY_LDS_LOOP_ATOMICS", "VICTORY_LDS_BOUNDS", "VICTORY_WATERFALL_SHAPE", + "VICTORY_LDS_BOUNDS_EXEMPT", ] { bytes.extend_from_slice(name.as_bytes()); bytes.push(b'='); @@ -138,7 +139,12 @@ pub fn precompile(container: &[u8]) -> Result<bool, String> { /// The translation of a console shader container, from the cache when /// there is one. pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> { - let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); + // (The container's name as run logs give it, for the settings that name programs.) + let translate = |c: &[u8]| { + let hash = blake3::hash(c).to_hex(); + victory_shader::emit::with_program(&hash[..16], || victory_shader::emit::translate(c)) + .map_err(|e| e.to_string()) + }; let shader = match CACHE.get() { Some(cache) => cached(cache, &build(), container, translate), None => translate(container), diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 8f1cefeac..ec57baed7 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -612,6 +612,56 @@ pub(super) fn loop_branches(p: &Program, st: &Structured) -> HashSet<usize> { /// (reads give 0, writes are dropped; `VICTORY_LDS_BOUNDS=0`: taken as inside, as before). fn lds_bounds() -> bool { !std::env::var("VICTORY_LDS_BOUNDS").is_ok_and(|v| v.trim() == "0") + && !lds_bounds_exempt() +} + +/// Programs the bounds above are not applied to (`VICTORY_LDS_BOUNDS_EXEMPT=<16 hex digits>[,..]`, +/// the BLAKE3 of the title's container as run logs name shaders; `0` or empty: none; unset: the +/// face programs below). The face network's operations (`compute_graph_ops`: the matrix +/// products, dot products and reductions) and the two programs that rebuild the face's normals +/// from its blend shapes use shared memory past the size their headers give; held to that size, +/// their results were zeros and cutscene faces were not drawn but for the eyes and teeth (Series X, +/// 1.0.2.1, the interview and the store flashback). Every other program keeps the bounds: +/// without them anywhere, the submitting thread waited 71 ms a frame for the card (median, RTX +/// 5080; about 1 ms with them) and the frame rate halved. +const FACE_PROGRAMS: [&str; 25] = [ + "38a65783327c30b6", "60c4f9d76c3aed89", "3eed5349508763fb", "25c0eac2493ca478", + "f8425d3c03df62a0", "44679bc29abcf17a", "d603b4c3b6505026", "3931481a3e2ff49f", + "7031554d409c394f", "e72489e94f2e167a", "e52a6557e730c889", "c41ee78453b1eed8", + "fcbb2e25040a325b", "24a83bd1f400880f", "6b1ec09dad51d662", "95efe597345a9e17", + "e45172602f6280b6", "0709e8356abd9082", "e4576c6eca0f8ce3", "6831220e1ed5878f", + "433e7b2c5496ceea", "7de0f9db96ddd295", "3d65925d7cd4a39a", "7ae4af7c4309b836", + "e4a7e088c7780ce8", +]; + +thread_local! { + /// The 16 hex digits of the container being translated on this thread ([`with_program`]). + static PROGRAM: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) }; +} + +/// Runs `f` (a translation) with `hash` (16 hex digits of the container's BLAKE3) as the program +/// being translated, for the settings that name programs ([`lds_bounds_exempt`]). +pub fn with_program<T>(hash: &str, f: impl FnOnce() -> T) -> T { + PROGRAM.with(|p| hash.clone_into(&mut p.borrow_mut())); + let out = f(); + PROGRAM.with(|p| p.borrow_mut().clear()); + out +} + +fn lds_bounds_exempt() -> bool { + static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new(); + let list = LIST.get_or_init(|| match std::env::var("VICTORY_LDS_BOUNDS_EXEMPT") { + Err(_) => FACE_PROGRAMS.iter().map(|h| (*h).to_owned()).collect(), + Ok(v) => v + .split(',') + .map(|h| h.trim().to_ascii_lowercase()) + .filter(|h| !h.is_empty() && h != "0") + .collect(), + }); + !list.is_empty() && PROGRAM.with(|p| { + let p = p.borrow(); + !p.is_empty() && list.iter().any(|h| p.starts_with(h.as_str())) + }) } /// Whether a refusal is of code that needs every lane of the wave where it stands (two host diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c99131270..0647dcb0a 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -120,7 +120,7 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; +pub use lower::{host_settings, set_host_max_wave, set_host_rdna, with_program}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, From cc1b9246a701e0d82e1b60a939871852253f1d1f Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 28 Nov 2026 21:22:05 +0000 Subject: [PATCH 55/57] Shaders: upstream's face-program exemption from shared memory's bounds off by default (VICTORY_LDS_BOUNDS_EXEMPT=faces turns it on) On an RTX 3070 Ti, with #938's 25 face programs exempt, a policewoman's skin came out as coloured noise in a cutscene; with VICTORY_LDS_BOUNDS_EXEMPT=0 every face was right (two sessions each). The shader cache's key holds the list in effect, not the switch's text, so translations cached with the exemption are not served without it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- crates/victory-gpu/src/shader_cache.rs | 5 +++++ crates/victory-shader/src/emit/lower.rs | 29 +++++++++++++++---------- crates/victory-shader/src/emit/mod.rs | 1 + docs/ryzen-9900x-rtx-3070ti.md | 7 ++++++ 4 files changed, 31 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 2984c06b5..d485e6576 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -63,6 +63,11 @@ fn build() -> [u8; 32] { // And whether waterfalls are proven by their shape: by its effect, not // its switch's text, since the default changed (on in VIctory-Neo, off // here) and a translation cached with it on must not be served without. + // And the programs left without shared memory's bounds, by the list in + // effect (its default changed here from upstream's face programs to none). + bytes.extend_from_slice(b"lds-exempt:"); + bytes.extend_from_slice(victory_shader::emit::lds_bounds_exempt_list().join(",").as_bytes()); + bytes.push(0); bytes.extend_from_slice(b"shape"); bytes.push(b'0' + victory_shader::resource::waterfall_shape_mode()); // So are the switches that pick the form of a wave64 program: diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ec57baed7..43f3e41f1 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -616,8 +616,12 @@ fn lds_bounds() -> bool { } /// Programs the bounds above are not applied to (`VICTORY_LDS_BOUNDS_EXEMPT=<16 hex digits>[,..]`, -/// the BLAKE3 of the title's container as run logs name shaders; `0` or empty: none; unset: the -/// face programs below). The face network's operations (`compute_graph_ops`: the matrix +/// the BLAKE3 of the title's container as run logs name shaders; `faces`: the face programs below; +/// `0`, empty or unset: none in this fork). +/// +/// Exempt on an RTX 3070 Ti (32-lane waves), a policewoman's skin came out as coloured noise in a +/// cutscene where the bounds drew it right (2026-11-28): what lies past the headers' size there is +/// not what the console's shared memory held. Upstream's default (#938, RTX 5080) was the faces. The face network's operations (`compute_graph_ops`: the matrix /// products, dot products and reductions) and the two programs that rebuild the face's normals /// from its blend shapes use shared memory past the size their headers give; held to that size, /// their results were zeros and cutscene faces were not drawn but for the eyes and teeth (Series X, @@ -648,16 +652,19 @@ pub fn with_program<T>(hash: &str, f: impl FnOnce() -> T) -> T { out } -fn lds_bounds_exempt() -> bool { +/// The programs [`lds_bounds_exempt`] names, as `VICTORY_LDS_BOUNDS_EXEMPT` gives them (part of +/// the shader cache's key by this list, not the switch's text, since the default changed). +pub fn lds_bounds_exempt_list() -> &'static [String] { static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new(); - let list = LIST.get_or_init(|| match std::env::var("VICTORY_LDS_BOUNDS_EXEMPT") { - Err(_) => FACE_PROGRAMS.iter().map(|h| (*h).to_owned()).collect(), - Ok(v) => v - .split(',') - .map(|h| h.trim().to_ascii_lowercase()) - .filter(|h| !h.is_empty() && h != "0") - .collect(), - }); + LIST.get_or_init(|| match std::env::var("VICTORY_LDS_BOUNDS_EXEMPT").as_deref().map(str::trim) { + Ok("faces") => FACE_PROGRAMS.iter().map(|h| (*h).to_owned()).collect(), + Ok(v) => v.split(',').map(|h| h.trim().to_ascii_lowercase()).filter(|h| !h.is_empty() && h != "0").collect(), + Err(_) => Vec::new(), + }) +} + +fn lds_bounds_exempt() -> bool { + let list = lds_bounds_exempt_list(); !list.is_empty() && PROGRAM.with(|p| { let p = p.borrow(); !p.is_empty() && list.iter().any(|h| p.starts_with(h.as_str())) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0647dcb0a..41b03d586 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -93,6 +93,7 @@ mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; mod lower; +pub use lower::lds_bounds_exempt_list; mod own_bits; #[cfg(all(test, windows))] mod permlane_tests; diff --git a/docs/ryzen-9900x-rtx-3070ti.md b/docs/ryzen-9900x-rtx-3070ti.md index c1cb1f25d..ab7323a9e 100644 --- a/docs/ryzen-9900x-rtx-3070ti.md +++ b/docs/ryzen-9900x-rtx-3070ti.md @@ -91,6 +91,13 @@ stutter and cut their sound). stripes. It was worth 3 to 5 frames a second on the boat. In compute programs alone (`VICTORY_WATERFALL_SHAPE=compute`) it broke another face and gained only in scenes of 2,000 to 3,500 draws. +- Upstream's #938 (shared memory past the header's size for 25 face programs) + is off by default here (`VICTORY_LDS_BOUNDS_EXEMPT=faces` turns it on): on + this card it drew a policewoman's skin as coloured noise, and with the + bounds kept every face was right. Upstream's #81 (no pipeline library saved + mid-burst), #1179 (texture slots given back by the texture queue's line, + neutral stand-ins) and #949 (the water portal program on 32-lane waves) are + in. ## What did not work From fa55d86a428576c1158e98c2db8f6a33b7ecffe0 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sun, 29 Nov 2026 01:54:21 +0000 Subject: [PATCH 56/57] Precaching for VILauncher: PRECACHE.cmd, and shaders, warm and preload keep to VICTORY_SHADER_CACHE_DIR victory preload translated into the default cache and warm built from it, so a preload filled a folder the runs started by VILauncher (with VICTORY_SHADER_CACHE_DIR) never read. They all keep to the same folder now. PRECACHE.cmd finds the victory.exe VILauncher built (the driver keeps pipelines by program path), asks once for the game folder and runs the preload into C:\VictoryCache. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- .gitignore | 3 ++ PRECACHE.cmd | 12 +++++++ apps/victory/src/main.rs | 25 ++++++++++++++ apps/victory/src/run.rs | 25 +------------- apps/victory/src/translate.rs | 4 +-- apps/victory/src/warm.rs | 6 ++-- docs/ryzen-9900x-rtx-3070ti.md | 12 +++++++ scripts/precache.ps1 | 62 ++++++++++++++++++++++++++++++++++ 8 files changed, 120 insertions(+), 29 deletions(-) create mode 100644 PRECACHE.cmd create mode 100644 scripts/precache.ps1 diff --git a/.gitignore b/.gitignore index 65e781aec..b295ae819 100644 --- a/.gitignore +++ b/.gitignore @@ -84,3 +84,6 @@ Thumbs.db # What the F1 menu saved /victory-settings.txt /victory-settings.*.txt + +# The game folder the launch and precache scripts remember (a path on this PC) +/game_dir.txt diff --git a/PRECACHE.cmd b/PRECACHE.cmd new file mode 100644 index 000000000..ddf808cb4 --- /dev/null +++ b/PRECACHE.cmd @@ -0,0 +1,12 @@ +@echo off +rem Precaching: every shader of the title translated and the recorded pipelines built ahead of play, +rem into C:\VictoryCache (VICTORY_SHADER_CACHE_DIR) with the victory.exe VILauncher built. ASCII only. +rem PRECACHE.cmd as above +rem PRECACHE.cmd -GameDir "E:\Game" another game folder (else game_dir.txt, asked once) +setlocal +set "PS1=%~dp0scripts\precache.ps1" +set "PSH=powershell" +where pwsh >nul 2>nul && set "PSH=pwsh" +%PSH% -NoProfile -ExecutionPolicy Bypass -File "%PS1%" %* +echo. +pause diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index b7ee76fd7..e21622589 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -578,6 +578,31 @@ fn show_config() -> Result<()> { } /// Paths given on the command line, or the configured game + test titles. +/// The folder of the translated shaders, with the pipelines beside it: +/// `<VICTORY_SHADER_CACHE_DIR>\shaders` where that is set, else the cache's +/// `shaders`. `victory run`, `shaders`, `warm` and `preload` all +/// keep to it, so that a preload fills the folder the runs read. +/// +/// A launcher that keeps the cache in a folder of its own may empty it: on +/// an RTX 3070 Ti started by VILauncher, 7 of 11 sessions in a day began +/// with no translation and no pipeline library (hits=0, about 2,250 +/// shaders translated and 800 pipelines made again, the first cutscene +/// black for a minute), the sessions after a change of its launch options +/// or an update. A folder it does not know of keeps them. +pub(crate) fn shader_cache_dir(cfg: &victory_core::Config) -> Result<PathBuf> { + match std::env::var_os("VICTORY_SHADER_CACHE_DIR").filter(|v| !v.is_empty()) { + Some(root) => { + use anyhow::Context as _; + let dir = PathBuf::from(root).join("shaders"); + std::fs::create_dir_all(&dir).with_context(|| format!("creating {} (VICTORY_SHADER_CACHE_DIR)", dir.display()))?; + // (On stderr: the processes of `warm` answer on stdout, line by line.) + eprintln!("shaders kept in {} (VICTORY_SHADER_CACHE_DIR)", dir.display()); + Ok(dir) + } + None => cfg.cache_subdir("shaders"), + } +} + pub(crate) fn default_paths(paths: Vec<PathBuf>) -> Result<Vec<PathBuf>> { if !paths.is_empty() { return Ok(paths); diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 8ecc1df36..909e94e84 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -102,29 +102,6 @@ fn title_executable(given: &Path) -> Result<std::path::PathBuf> { } } -/// The folder of the translated shaders, with the pipelines beside it: -/// `<VICTORY_SHADER_CACHE_DIR>\shaders` where that is set, else the cache's -/// `shaders`. -/// -/// A launcher that keeps the cache in a folder of its own may empty it: on -/// an RTX 3070 Ti started by VILauncher, 7 of 11 sessions in a day began -/// with no translation and no pipeline library (hits=0, about 2,250 -/// shaders translated and 800 pipelines made again, the first cutscene -/// black for a minute), the sessions after a change of its launch options -/// or an update. A folder it does not know of keeps them. -#[cfg(windows)] -fn shader_cache_dir(cfg: &victory_core::Config) -> Result<std::path::PathBuf> { - match std::env::var_os("VICTORY_SHADER_CACHE_DIR").filter(|v| !v.is_empty()) { - Some(root) => { - let dir = std::path::PathBuf::from(root).join("shaders"); - std::fs::create_dir_all(&dir).with_context(|| format!("creating {} (VICTORY_SHADER_CACHE_DIR)", dir.display()))?; - println!("shaders kept in {} (VICTORY_SHADER_CACHE_DIR)", dir.display()); - Ok(dir) - } - None => cfg.cache_subdir("shaders"), - } -} - #[cfg(windows)] pub fn run( exe: &Path, @@ -249,7 +226,7 @@ pub fn run( } else { cfg.cache_subdir("images")? }; - victory_hle::modules::d3d12x::use_shader_cache(shader_cache_dir(&cfg)?); + victory_hle::modules::d3d12x::use_shader_cache(crate::shader_cache_dir(&cfg)?); let image = victory_loader::load(&prepared, &images)?; // The program is mapped from the copy `load` wrote: the file's bytes // and their patched copy are not read again, and were held for the diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index a86ab3e64..8d7823e24 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -175,7 +175,7 @@ pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>) -> Result<()> // (what is done stays in the cache; the next warm-up goes on from there). let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::<u64>().ok()); let cfg = victory_core::Config::load()?; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + victory_hle::modules::d3d12x::use_shader_cache(crate::shader_cache_dir(&cfg)?); let paths = crate::default_paths(paths)?; let threads = jobs.unwrap_or(4).max(1); let began = std::time::Instant::now(); @@ -419,7 +419,7 @@ fn may_hold_shaders(path: &std::path::Path) -> bool { /// Every shader found into the cache runs translate from. pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>) -> Result<()> { let cfg = victory_core::Config::load()?; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + victory_hle::modules::d3d12x::use_shader_cache(crate::shader_cache_dir(&cfg)?); let paths = crate::default_paths(paths)?; let threads = jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); diff --git a/apps/victory/src/warm.rs b/apps/victory/src/warm.rs index 6d3ee9fa8..c55d3f552 100644 --- a/apps/victory/src/warm.rs +++ b/apps/victory/src/warm.rs @@ -23,7 +23,7 @@ const SLOW_MS: f64 = 1000.0; fn folder() -> Result<PathBuf> { let cfg = victory_core::Config::load()?; - Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines")) + Ok(crate::shader_cache_dir(&cfg)?.with_file_name("pipelines")) } pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, these: Option<String>) -> Result<()> { @@ -160,7 +160,7 @@ pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, t pub fn into_library(jobs: Option<usize>) -> Result<()> { let dir = folder()?; let cfg = victory_core::Config::load()?; - known::use_library(cfg.cache_subdir("shaders")?); + known::use_library(crate::shader_cache_dir(&cfg)?); let keys = known::keys(&dir); let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); let (bad, early, slow) = (read("warm-bad.txt"), read("early-pipelines.txt"), read("slow-pipelines.txt")); @@ -269,7 +269,7 @@ fn child(these: &[usize], mut each: impl FnMut(usize, f64, bool)) -> (usize, Opt fn make(dir: &Path, these: &str) -> Result<()> { let these: Vec<usize> = these.split(',').map(|n| n.parse().context("--these")).collect::<Result<_>>()?; let cfg = victory_core::Config::load()?; - victory_hle::known_pipelines::use_translations(cfg.cache_subdir("shaders")?); + victory_hle::known_pipelines::use_translations(crate::shader_cache_dir(&cfg)?); let mut out = std::io::stdout(); known::make(dir, &these, |n, came| { let told = match came { diff --git a/docs/ryzen-9900x-rtx-3070ti.md b/docs/ryzen-9900x-rtx-3070ti.md index ab7323a9e..0d00ca1f3 100644 --- a/docs/ryzen-9900x-rtx-3070ti.md +++ b/docs/ryzen-9900x-rtx-3070ti.md @@ -58,6 +58,18 @@ Not set, on purpose: `VICTORY_OWN_CPUS` (below), `VICTORY_THIN_THREADS`, `VICTORY_FRAME_INTERVAL_US` (a cap under the title's rate made cutscenes stutter and cut their sound). +## Precaching + +`PRECACHE.cmd` (in the repository's folder, with the game closed) translates +every shader of the title and builds the pipelines earlier runs wrote down, +into `C:\VictoryCache` (the `VICTORY_SHADER_CACHE_DIR` the runs read), with the +`victory.exe` VILauncher built: the NVIDIA driver keeps pipelines by program +path, so another copy's are built again. It asks once for the game folder +(kept in `game_dir.txt`). It takes a while the first time; stopped, the next +run goes on from there. Worth running after a new build, a new NVIDIA driver, +and before areas not played yet. (XSEmu Launcher offers pre-caching only for +the runners it ships; a repository added as a custom runner gets none.) + ## The PC itself - **The graphics card in PCIe x16.** It ran at 4.0 x8: on the Gigabyte X870E diff --git a/scripts/precache.ps1 b/scripts/precache.ps1 new file mode 100644 index 000000000..1b58404ff --- /dev/null +++ b/scripts/precache.ps1 @@ -0,0 +1,62 @@ +# Precaching for VILauncher (and any start of this fork): every shader of the title translated and the +# pipelines earlier runs wrote down built, into the folder the runs read (VICTORY_SHADER_CACHE_DIR), with the +# same victory.exe the game runs with. The NVIDIA driver keeps pipelines by program path, so pipelines built +# by another copy of victory.exe are built again by the game's. +# +# PRECACHE.cmd game folder from game_dir.txt (asked once), victory.exe found by itself +# PRECACHE.cmd -GameDir 'E:\Game' that game folder +# PRECACHE.cmd -Exe 'C:\...\victory.exe' -CacheDir 'D:\VictoryCache' +# +# Run it with the game closed. What is done is kept: stopped (close the window), the next run goes on from there. +param( + [string]$GameDir = '', + [string]$Exe = '', + [string]$CacheDir = 'C:\VictoryCache' +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path $PSScriptRoot -Parent +$gameExeName = 'game_scarlett_master.exe' + +# The game folder: given, else the first line of game_dir.txt here, else asked (and saved there). +$txt = Join-Path $repo 'game_dir.txt' +if (-not $GameDir -and (Test-Path $txt)) { $GameDir = (Get-Content $txt -Encoding UTF8 -TotalCount 1).Trim().Trim('"') } +if (-not $GameDir -or -not (Test-Path (Join-Path $GameDir $gameExeName))) { + $GameDir = (Read-Host "Folder with $gameExeName (for example E:\GTA6\Grand Theft Auto VI\Game)").Trim().Trim('"') + if (-not (Test-Path (Join-Path $GameDir $gameExeName))) { Write-Host "No $gameExeName in $GameDir."; exit 1 } + Set-Content -Path $txt -Value $GameDir -Encoding UTF8 +} + +# victory.exe: given, else the newest VILauncher built, else this repository's own build. +if (-not $Exe) { + $vil = Join-Path $env:LOCALAPPDATA 'VILauncher' + if (Test-Path $vil) { + $found = Get-ChildItem -Path $vil -Recurse -Filter 'victory.exe' -File -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | Select-Object -First 1 + if ($found) { $Exe = $found.FullName } + } +} +if (-not $Exe) { + foreach ($p in @('target\release\victory.exe', 'target\native\victory.exe')) { + $c = Join-Path $repo $p + if (Test-Path $c) { $Exe = $c; break } + } +} +if (-not $Exe -or -not (Test-Path $Exe)) { + Write-Host 'No victory.exe found: play once with VILauncher (it builds it), or give -Exe <path to victory.exe>.' + exit 1 +} + +Write-Host "victory.exe : $Exe" +Write-Host "game : $GameDir" +Write-Host "cache : $CacheDir (VICTORY_SHADER_CACHE_DIR: put the same line in VILauncher's switches)" +Write-Host '' +$env:VICTORY_SHADER_CACHE_DIR = $CacheDir +$env:VICTORY_GAME_DIR = $GameDir +$began = Get-Date +& $Exe preload $GameDir +$code = $LASTEXITCODE +$minutes = [math]::Round(((Get-Date) - $began).TotalMinutes, 1) +Write-Host '' +if ($code -eq 0) { Write-Host "Precaching done in $minutes min." } +else { Write-Host "Precaching stopped (exit code $code) after $minutes min; what it did is kept." } +exit $code From 9304ffbdb33b9e264162c0a36efc088e0d8e7ceb Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sun, 29 Nov 2026 03:01:54 +0000 Subject: [PATCH 57/57] run: MFG Unlocker loaded where VICTORY_MFG_UNLOCKER_DLL names it, as play does A launcher that starts victory run itself (VILauncher) had no way to load the mod: only victory play loaded it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ULB8X6uKz9YY1ZUqZ9W4YP --- apps/victory/src/main.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index e21622589..cbcf2ea66 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -526,6 +526,12 @@ fn main() -> Result<()> { title_args, } => { victory_hle::runtime::set_title_args(title_args); + // MFG Unlocker where `VICTORY_MFG_UNLOCKER_DLL` names it, as `play` does: a launcher + // that starts `run` itself (VILauncher) had no way to load it. + #[cfg(windows)] + if execute { + play::load_mfg(); + } run::run(&exe, unimplemented, strict, execute, console) } #[cfg(all(windows, feature = "diagnostics"))]