From 5a537b3efd31a7c1343e3a83366414eb615d143d Mon Sep 17 00:00:00 2001 From: 1bugproof <254564796+1bugproof@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:06:52 +0100 Subject: [PATCH 01/34] Docs: contribution guidelines for people and AI agents CONTRIBUTING.md: small single-purpose PRs (~400 changed lines, stacked when dependent), Area: commit subjects as in the history, tests with every logic change, licence and provenance rules, and an AI policy (disclose tool and model, the author answers for every line, tests actually run, AI test reports welcome). AGENTS.md: the same rules as instructions for coding agents, plus build and test commands and what an agent must never do. CLAUDE.md loads both. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 97 +++++++++++++++++++++++++++ CLAUDE.md | 15 +++++ CONTRIBUTING.md | 171 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 283 insertions(+) create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 CONTRIBUTING.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..166e42e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,97 @@ +# Instructions for AI agents + +This file is for coding agents (Claude Code, Codex, Copilot, Cursor, …) working in this repository. +The full rules for every contributor are in [`CONTRIBUTING.md`](CONTRIBUTING.md); read it before you +start. This file is the short version, plus what an agent needs to know about running the project. + +## The project + +XCL runs Xbox Series X|S (GDK) game files on Windows without CPU emulation: the game's x64 code runs +natively, XCL stands in for the console libraries (`kernelx`, XGameRuntime, D3D12.X, …), and the +console's RDNA2 GPU code is recompiled to HLSL → DXIL. Rust workspace: `crates/xcl` (the runtime and +the `xcl` CLI), `tests/testtitle` + `tests/testgamedll` (our own console title for e2e tests). + +- What works and how to use it: `README.md` +- Design: `docs/specs/2026-11-20-xcl-design.md` +- Status, measurements and findings: `HANDOFF.md` (long; search it rather than reading it all) + +## Build and test + +Windows 10/11 x64 only, `stable-x86_64-pc-windows-msvc`, Windows SDK (DXC), a D3D12 GPU with SM 6.6. + +```powershell +.\scripts\test.ps1 # build + all tests +cargo build --workspace && cargo test --workspace -- --test-threads=4 # same, from bash / in the background +cargo test -p xcl --lib # one area while iterating +``` + +- GPU tests print `SKIPPED : ` when the adapter cannot run them and still pass. Report + skips; do not count them as coverage. +- On macOS / Linux the crate does not build or run. Do not claim it does: say "not built / not tested" + in the PR. +- Editing files through PowerShell `Get-Content` / `Set-Content` corrupts UTF-8: use your file tools. +- Some steps (DXC compiles of many shaders, whole-pack runs) take many minutes: run them on small + samples first. + +## Rules + +### Scope +- **Do what was asked, nothing more.** No refactors, renames, reformatting, comment rewrites or + dependency changes the task does not need. Mention other problems you notice instead of fixing them. +- **Never run `cargo fmt` on files or the crate**: the tree is not `rustfmt`-clean. Format only the + lines you change. +- Before starting, check whether an open PR or issue already covers the work + (`gh pr list -R ivall/xcl --search ""`), and tell the user if one does. +- Follow the code around you: reuse existing helpers and the module's patterns instead of adding layers. +- When your change makes something work (or stop working) for users, update `README.md`. If it makes + a statement in `HANDOFF.md` or `docs/specs/` wrong, say so in the PR description instead of editing them. + +### Splitting the work +- **One logical change per PR, under ~400 changed lines** (generated files and test data excluded). +- When a task is bigger, propose the split to the user **before** writing code: preparation with no + behaviour change → new code with its tests → turning it on → diagnostics. Each part is its own + branch and PR; dependent ones are stacked (`Stacked on #N` in the description). + +### Commits +- Commit only when the user asks. +- Subject: `: `, about 72 characters, in the style of `git log`, e.g. + `VFS: preserve the destination when an overlay rename fails`. Areas: `Recompiler`, `D3D12.X`, + `DirectStorage`, `XGameRuntime`, `kernelx`, `XAudio2`, `VFS`, `Memory`, `TLS`, `PE loader`, `Shaders`, + `Frame clock`, `xcl run`, `Tests`, `e2e`, `Scripts`, `README`, `Docs`. No `fix:` / `feat(x):`. +- Body: why, root cause, what was measured. One logical change per commit; every commit builds and + passes the tests. Squash fixups before the PR is reviewed. +- Keep the attribution trailer your tool adds (e.g. `Co-Authored-By: Claude Opus 5.5 <…>`); it is how + AI use is disclosed in history. If your tool adds none, add `Assisted-by: ()`. + +### Tests +- A bug fix comes with a test that fails without the fix. New logic comes with a test of it. + Docs, logging and renames need none. +- Unit tests in the file's `#[cfg(test)] mod tests`; integration tests in `crates/xcl/tests/`. +- GPU tests call `gpu::recomp::runner::skip_test(reason)` and return when the hardware is missing. + Never `#[ignore]` a test to make it pass, and never weaken an assertion to make a test pass. +- Tests on game data use `XCL_SAMPLE_*` variables and do nothing when they are unset. +- **Run the tests before saying they pass.** Report the exact command and the counts + (passed / failed / ignored / skipped). If you could not run them, say so plainly. + +### Never +- Commit game data, game dumps, console SDK headers or binaries, keys, or anything for getting + around DRM. +- Port code from WinDurango (LGPL-3.0, reference only) or add a dependency that is not + GPL-2.0-compatible. +- Edit generated files (`*_spec.rs`, generated tables) by hand: change the generator in `scripts/` and + rerun it. +- Rewrite `HANDOFF.md` or `docs/specs/` as part of a feature change. +- Push, open PRs, or post issues, reviews or comments on GitHub unless the user asks in this session. +- Report results you did not produce. A test report on a PR is fine: name the exact commit, the + hardware, the commands and their counts, and the tool and model that wrote it. A review + comment is posted only after the user has checked each point. + +## Pull request description + +Write it to the outline in `CONTRIBUTING.md`: what and why, **What is in it**, **Tested** (hardware, +commands, counts), **Not tested**, **AI use**. Keep it short and factual: no summaries of the diff line +by line, no claims that were not measured, no filler. Link the issue (`Fixes #N`). + +**Always name your model** (and the tool you run in) in **AI use**, in commit trailers and in test +reports, e.g. `Claude Code, Claude Opus 5.5`. Use the exact model name you were given; if you do not +know it, write that you do not know rather than guessing. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..e77b0fa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,15 @@ +# Claude Code + +The instructions for agents in this repository are in `AGENTS.md`, and the rules for every +contributor are in `CONTRIBUTING.md`. Both apply to you: + +@AGENTS.md +@CONTRIBUTING.md + +Specific to Claude Code: + +- Plan a task that spans more than one subsystem or more than ~400 lines (plan mode), and propose + how to split it into PRs before you write code. +- Run the tests and report the real output; do not stop at "the tests should pass". +- Leave the `Co-Authored-By: Claude …` trailer in commits, and fill in the **AI use** section of the + PR description with Claude Code and your exact model name. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..641b823 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,171 @@ +# Contributing to XCL + +Thanks for helping. XCL gets far more pull requests than one maintainer can read carefully, so +these rules exist to make every PR **cheap to review and safe to merge**. A PR that ignores them +may be closed without a review, however good the code is. + +AI tools are welcome (see [AI-assisted contributions](#ai-assisted-contributions)). The rules are +the same for code written by hand and by an agent. + +## Before you start + +1. **Search open PRs and issues first.** Several PRs have solved the same problem at once and all + but one were closed. If someone is already on it, review or test their PR instead. +2. **Say what you are doing.** For anything bigger than a small fix, comment on the issue (or open + one) with the plan in two or three lines before writing it. That avoids duplicate work and wasted + effort on a direction the maintainer would not take. +3. **One problem per PR.** If you find a second bug while working, it gets its own PR. + +## Pull requests: small and single-purpose + +The smaller the PR, the faster it gets reviewed and merged. + +- **One logical change per PR.** A fix, a feature, a refactor and a test-only change are four PRs, + not one. "While I was here" changes go into a separate PR. +- **Size target: under ~400 changed lines**, not counting generated files and test data. Over ~800 + lines, the description must say why it cannot be split. Most large PRs can be split. +- **How to split** a large piece of work, in roughly this order: + 1. preparation that changes no behaviour (moving code, a new helper, a renamed type), + 2. new code behind a check or not yet called, with its tests, + 3. turning it on, + 4. diagnostics, logging and env-var switches, each on its own. +- **Stacked PRs** are fine when one change depends on another. Open each PR against `main`, say + `Stacked on #N` at the top of the description, and make it clear which commits belong to this PR. + Each PR in the stack must make sense when reviewed on its own. +- **No drive-by reformatting.** The tree is not `rustfmt`-clean. Do not run `cargo fmt` on whole + files or the whole crate: format only the lines you change. Reformatting buries the real diff. +- **No unrelated churn:** no renames, reordering, comment rewrites or dependency bumps the change + does not need. +- Keep the PR up to date by rebasing onto `main`, not by merging `main` into it. +- Open the PR as a **draft** until it builds, its tests pass and you have checked it yourself. + +### PR description + +Use this outline: + +```markdown + + + +**What is in it** +- one bullet per commit or part, with the file it lives in + +**Tested** +- hardware (GPU + driver, CPU), Windows build, Rust version, debug/release +- commands run and their results, e.g. `cargo test --workspace -- --test-threads=4`: 541 passed, 0 failed, 21 ignored +- `SKIPPED` GPU tests on your adapter, if any +- game checked (if any), and what got better, with numbers if you have them + +**Not tested** +- what you could not check, e.g. AMD / NVIDIA, the retail title, wave32-only GPUs + +**AI use** +- none / which tool and model (e.g. Claude Code with Claude Opus 5.5), and for what (see below) +``` + +"Not tested" is required. An honest "not tested on AMD" is fine. A test you did not run listed as +passing is not, and gets the PR closed. + +## Commits + +History is merged with merge commits, so every commit on a PR ends up in `main`. + +- **Scope prefix + outcome**, as in the existing history: + ``` + Recompiler: round f16 conversions and products to nearest-even by default + VFS: preserve the destination when an overlay rename fails + D3D12.X: draws with untranslated pipelines get the title's root signature + ``` + The prefix is the subsystem: `Recompiler`, `D3D12.X`, `DirectStorage`, `XGameRuntime`, + `kernelx`, `XAudio2`, `VFS`, `Memory`, `TLS`, `PE loader`, `Shaders`, `Frame clock`, `xcl run`, + `Tests`, `e2e`, `Scripts`, `README`, `Docs`, `Issue templates`. Use one that exists already when it fits. + No `fix:` / `feat(...)` style prefixes; this repo does not use Conventional Commits. +- Subject line of about 72 characters or less, saying what the change does, not "update file.rs" or + "fix bug". +- The body (optional for small changes) says **why**, and anything a reviewer could not see from the + diff: the root cause, what was measured, what was ruled out. +- **One logical change per commit.** Each commit builds and passes the tests on its own, so `git bisect` + works. +- **No fixup commits in the final PR**: squash "fix review", "wip", "fmt", "oops" commits into the + commit they fix before asking for review (`git rebase -i`, then force-push). +- Reference issues as `(#123)` in the subject or `Fixes #123` in the body. + +## Tests + +Add or change a test when the change touches logic: a bug fix gets a test that fails before the fix +and passes after it, and new behaviour gets a test that shows it working. Docs, comments, logging +and pure renames need no test. + +- **Unit tests** go in a `#[cfg(test)] mod tests` in the same file, the way the rest of the crate does it. +- **Integration / end-to-end tests** go in `crates/xcl/tests/`. The e2e test drives our own console + title in `tests/testtitle` / `tests/testgamedll`: extend it when a change concerns the path a title + takes. +- **GPU tests** must run without a GPU too: when the adapter cannot run them, call + `gpu::recomp::runner::skip_test("no GPU" | "no DXC" | "no wave64" | "no mesh shaders")` and return. + Never mark a test `#[ignore]` only so that it passes. +- **Tests on game data** read files the contributor owns through the `XCL_SAMPLE_*` variables + (see README / `scripts/test.ps1`), and pass without doing anything when the variable is not set. + **Never commit game data**, console SDK headers or binaries, or output dumped from a game. +- **Recompiler instructions** get a per-instruction GPU test compared against an expected result, + like the existing ones. +- Run the whole suite before opening the PR: + ```powershell + .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace + ``` + XCL builds and runs on Windows only. If you could not run the tests (e.g. you work on macOS or + Linux), say so in **Not tested**; a PR with no Windows test run waits until someone runs one. + +## Licence and provenance + +XCL is **GPL-2.0-only**. + +- Dependencies must be GPL-2.0-compatible (no Apache-2.0-only, no GPL-3.0). New dependencies need a + reason in the PR description; avoid them for a few lines of code. +- Code ported or adapted from another project needs a provenance note in the file (project, URL, + licence) and an entry in `THIRD_PARTY.md` when it is new. +- WinDurango (LGPL-3.0) is a reference only: no code is ported from it. +- Nothing from the console SDK: no headers, no binaries, no copied documentation. +- Generated files (`*_spec.rs`, tables) come with the script in `scripts/` that generates them, and + the PR says how they were generated. Do not edit them by hand. +- Nothing for decrypting or getting around DRM. + +## Docs + +- `README.md` tells users what works. Update it when your change makes something work (or stop + working) for them. +- `HANDOFF.md` and `docs/specs/` are the maintainer's design and status notes. Do not rewrite them in + a feature PR; if your change makes a statement in them wrong, point that out in the PR description. +- Everything in the repository (code, comments, commit messages, docs) is in English. + +## Reviews and test reports + +- **Test results on your GPU** go to [#42](https://github.com/ivall/xcl/issues/42), not a new issue. +- Testing someone else's PR helps the most when it follows the **Tested / Not tested** outline above + and names the exact commit tested. Post one comment and edit it when you rerun the tests; do not + post a new comment for every run. +- **AI-written test reports are welcome** when they come from a real run: the exact commit, the + hardware, the commands and their results. Say which tool and model wrote the report. +- **AI reviews:** check each point yourself, post only what you confirmed, and say that a tool helped. +- Reply to review comments in the thread, push the fix (squashed into the right commit), and mark the + thread resolved only once it is addressed. + +## AI-assisted contributions + +You can use any AI tool. In return: + +- **You are the author and you are responsible.** You have read every line of the diff, you + understand it, and you can answer questions about it without asking the tool again. "The AI wrote it" + is not an answer in a review. +- **Disclose it** in the PR's **AI use** section: the tool, the model, and what it did (wrote the + code, wrote the tests, wrote the description, only reviewed). A trailer in the commit naming the + model, such as `Co-Authored-By: ` or `Assisted-by: ()`, is welcome too. +- **The tests were run, not just written.** Results in the PR come from a run you did, on hardware + you name. +- **A person opens the PR.** No PRs or issues opened by an unattended agent. +- **Keep the description short and true.** Leave out generated filler, marketing tone and claims + nobody measured. A reviewer should be able to read the description in one minute. +- The same size and scope rules apply. An agent can write 2000 lines in an hour, and nobody can + review that in an hour. Split it. + +Agents working in this repository read [`AGENTS.md`](AGENTS.md) (and Claude Code also reads +[`CLAUDE.md`](CLAUDE.md)), which put these rules into instructions for them. From 63b99306364326e8170412c88a81b8ba185d00e3 Mon Sep 17 00:00:00 2001 From: ivall Date: Mon, 23 Nov 2026 22:56:29 +0100 Subject: [PATCH 02/34] Docs: what a PR needs to be merged - tests run, a regression run on a title, checked by PR checks CONTRIBUTING.md gets the merge requirements: both required checks green (CI, PR checks), the whole suite run on a GPU with its counts, and for a runtime change (crates/xcl/src outside tests) two xcl-smoke blocks from scripts/smoke.ps1 - built from main and from the PR's head commit with no uncommitted changes - with no device removal or crash. The maintainer runs the suite and a retail title again on every merged batch. - scripts/smoke.ps1: runs a title for a fixed time (network off, XCL_ACTIVITY) and prints the xcl-smoke block: commit, GPU, exit, frames shown, presents, device removals, crashes, peak commit. - .github/pull_request_template.md: Tested / Regression run / Not tested / AI use. - .github/workflows/pr-check.yml: refuses a description without those sections, and a runtime change without a smoke block made on the PR's head commit. - AGENTS.md / CLAUDE.md (from #212): the same rules for agents; AI use is disclosed in the PR's AI use section, a commit trailer is not required. --- .github/pull_request_template.md | 23 ++++++++++++ .github/workflows/pr-check.yml | 59 +++++++++++++++++++++++++++++ AGENTS.md | 12 +++++- CLAUDE.md | 5 ++- CONTRIBUTING.md | 28 ++++++++++++++ scripts/smoke.ps1 | 64 ++++++++++++++++++++++++++++++++ 6 files changed, 187 insertions(+), 4 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/pr-check.yml create mode 100644 scripts/smoke.ps1 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..fe52870 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,23 @@ + + +**What is in it** +- + +**Tested** +- hardware (GPU + driver, CPU), Rust version, debug / release: +- `cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored (SKIPPED GPU tests: …) + +**Regression run** + + +main: + +PR: + +**Not tested** +- + +**AI use** +- none / tool and model, and what it did diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml new file mode 100644 index 0000000..c46c223 --- /dev/null +++ b/.github/workflows/pr-check.yml @@ -0,0 +1,59 @@ +# The description a pull request needs before it can be merged (CONTRIBUTING.md, "What a PR +# needs to be merged"): the Tested / Not tested / AI use sections, and – when it changes the +# runtime (crates/xcl/src outside tests) – two `xcl-smoke` blocks from scripts/smoke.ps1, one of +# them made on the PR's head commit with no uncommitted changes. Runs again when the description +# is edited or a commit is pushed. +name: PR checks + +on: + pull_request: + types: [opened, edited, synchronize, reopened, ready_for_review] + +permissions: + contents: read + pull-requests: read + +jobs: + description: + name: PR description + runs-on: ubuntu-latest + steps: + - name: Check the description + env: + GH_TOKEN: ${{ github.token }} + BODY: ${{ github.event.pull_request.body }} + HEAD: ${{ github.event.pull_request.head.sha }} + NUMBER: ${{ github.event.pull_request.number }} + REPO: ${{ github.repository }} + run: | + gh api "repos/$REPO/pulls/$NUMBER/files" --paginate --jq '.[].filename' > files.txt + python3 - <<'EOF' + import os, re, sys + body = os.environ.get("BODY") or "" + head = os.environ["HEAD"] + files = open("files.txt").read().split() + problems = [] + for section in ("Tested", "Not tested", "AI use"): + if not re.search(r"\*\*" + section + r"\*\*\s*\n\s*\S", body): + problems.append(f"the **{section}** section is missing or empty") + def runtime(f): + return f.startswith("crates/xcl/src/") and "/tests" not in f and not f.endswith("tests.rs") + if any(runtime(f) for f in files): + blocks = re.findall(r"xcl-smoke v1\s*\ncommit: (\S+)(.*)", body) + if len(blocks) < 2: + problems.append("the PR changes the runtime: **Regression run** needs two `xcl-smoke` blocks " + "(scripts/smoke.ps1 built from main and from this PR's head commit)") + elif not any(head.startswith(c) and "uncommitted" not in rest for c, rest in blocks): + problems.append(f"no `xcl-smoke` block was made on this PR's head commit {head[:12]} without " + "uncommitted changes - rerun scripts/smoke.ps1 after the last push") + for key in ("device removals", "crashes"): + for n in re.findall(key + r": (\d+)", body): + if int(n) > 0: + problems.append(f"a regression run shows {key}: {n}") + if problems: + print("This PR cannot be merged yet (see CONTRIBUTING.md, 'What a PR needs to be merged'):") + for p in problems: + print(" -", p) + sys.exit(1) + print("description ok") + EOF diff --git a/AGENTS.md b/AGENTS.md index 166e42e..2fc6bb3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,6 +35,14 @@ cargo test -p xcl --lib # one area while iter ## Rules +### Before a PR can be merged +The full list is in CONTRIBUTING.md ("What a PR needs to be merged"). In short: run the whole test +suite and report the real counts; for a change to `crates/xcl/src` outside tests, run +`scripts/smoke.ps1 -Game ` on a title built from `main` and from the PR's head commit (no +uncommitted changes) and paste both `xcl-smoke` blocks under **Regression run**, rerunning the PR's +after every push. The `PR checks` workflow refuses the PR without them. Never write a smoke block or +test counts by hand. + ### Scope - **Do what was asked, nothing more.** No refactors, renames, reformatting, comment rewrites or dependency changes the task does not need. Mention other problems you notice instead of fixing them. @@ -60,8 +68,8 @@ cargo test -p xcl --lib # one area while iter `Frame clock`, `xcl run`, `Tests`, `e2e`, `Scripts`, `README`, `Docs`. No `fix:` / `feat(x):`. - Body: why, root cause, what was measured. One logical change per commit; every commit builds and passes the tests. Squash fixups before the PR is reviewed. -- Keep the attribution trailer your tool adds (e.g. `Co-Authored-By: Claude Opus 5.5 <…>`); it is how - AI use is disclosed in history. If your tool adds none, add `Assisted-by: ()`. +- Disclose AI use in the PR's **AI use** section (tool, model, what it did). A trailer in the commit + (`Assisted-by: ()`) is welcome but not required. ### Tests - A bug fix comes with a test that fails without the fix. New logic comes with a test of it. diff --git a/CLAUDE.md b/CLAUDE.md index e77b0fa..e30885a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,5 +11,6 @@ Specific to Claude Code: - Plan a task that spans more than one subsystem or more than ~400 lines (plan mode), and propose how to split it into PRs before you write code. - Run the tests and report the real output; do not stop at "the tests should pass". -- Leave the `Co-Authored-By: Claude …` trailer in commits, and fill in the **AI use** section of the - PR description with Claude Code and your exact model name. +- Fill in the **AI use** section of the PR description with Claude Code and your exact model name. +- For a runtime change, run `scripts/smoke.ps1` on main and on the PR's head commit and paste both + `xcl-smoke` blocks; do not write or edit them by hand. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 641b823..75e48de 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,6 +7,31 @@ may be closed without a review, however good the code is. AI tools are welcome (see [AI-assisted contributions](#ai-assisted-contributions)). The rules are the same for code written by hand and by an agent. +## What a PR needs to be merged + +XCL gets more pull requests in an hour than anyone can test by hand, most of them written with AI +tools. So a PR is merged only when it shows that it was tested and that it breaks nothing. These are +checked before anything else; a PR that does not meet them waits (or is closed after a week). + +1. **Both required checks are green:** `CI` (build and tests on Windows, no GPU) and `PR checks` + (the description: the sections below, and the regression runs when they are needed). +2. **The whole suite ran on a GPU**, with the counts in **Tested** + (`cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored, and the SKIPPED tests). +3. **A PR that changes the runtime** (`crates/xcl/src` outside tests) **has a regression run on a real + title**: `scripts/smoke.ps1 -Game ` built from `main` and built from the PR's head + commit, both `xcl-smoke` blocks pasted under **Regression run**. The PR's block must name its head + commit with no uncommitted changes: rerun it after every push. It must show no device removal and + no crash, at least as many frames as `main` and no much higher peak commit. A run on a title that + does not reach the code the PR changes still counts as a regression check; say what it does not + cover under **Not tested**. +4. **No regression on the maintainer's run.** The maintainer merges in batches: the whole suite and a + retail title run again on the merged tree, on an AMD RDNA4 GPU. A PR that breaks either is taken + out of the batch and gets a comment with what failed. +5. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and + scope rules below. A PR that duplicates one already merged is closed. + +A test result that was not produced by a real run on the hardware named gets the PR closed. + ## Before you start 1. **Search open PRs and issues first.** Several PRs have solved the same problem at once and all @@ -56,6 +81,9 @@ Use this outline: - `SKIPPED` GPU tests on your adapter, if any - game checked (if any), and what got better, with numbers if you have them +**Regression run** +- for a runtime change: the two `xcl-smoke` blocks (main, this PR's head) – see above + **Not tested** - what you could not check, e.g. AMD / NVIDIA, the retail title, wave32-only GPUs diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 new file mode 100644 index 0000000..a4f668a --- /dev/null +++ b/scripts/smoke.ps1 @@ -0,0 +1,64 @@ +# Regression run of a title for a pull request: runs it for a fixed time, reads XCL's log and +# prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built +# from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). +# +# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] +# +# Networking is off (XCL_NETWORK=0). Build first: cargo build --release -p xcl +param( + [Parameter(Mandatory = $true)][string]$Game, + [int]$Seconds = 60, + [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe') +) +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path $Xcl)) { throw "no $Xcl - build it first (cargo build --release -p xcl)" } +$root = Split-Path $PSScriptRoot -Parent +$commit = (git -C $root rev-parse HEAD).Trim() +$dirty = [bool](git -C $root status --porcelain --untracked-files=no -- crates Cargo.toml Cargo.lock) + +$out = New-TemporaryFile +$err = New-TemporaryFile +$env:XCL_NETWORK = '0' +$env:XCL_RUN_SECONDS = "$Seconds" +$env:XCL_ACTIVITY = '1' +$p = Start-Process -FilePath $Xcl -ArgumentList @('run', "`"$Game`"") -NoNewWindow -PassThru -RedirectStandardOutput $out -RedirectStandardError $err +$null = $p.Handle # (without it ExitCode stays empty) +if (-not $p.WaitForExit(($Seconds + 120) * 1000)) { + Stop-Process -Id $p.Id -Force + $timedOut = $true +} +Remove-Item Env:XCL_RUN_SECONDS, Env:XCL_ACTIVITY + +$stdout = Get-Content $out -Raw -Encoding utf8 +Remove-Item $out, $err +$logLine = ($stdout -split "`n" | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) +if (-not $logLine) { throw "XCL printed no log path; its output:`n$stdout" } +$log = ($logLine -replace '^Log:\s+', '').Trim() +$text = Get-Content $log -Raw -Encoding utf8 + +$frames = if ($text -match '\((\d+) frames shown, (\d+) PresentX calls\)') { "$($Matches[1]) (PresentX $($Matches[2]))" } else { 'none logged (the run did not reach its end)' } +$presents = [regex]::Matches($text, 'activity \(2 s\): (\d+) presents') | ForEach-Object { [int]$_.Groups[1].Value } +$lastPresents = ($presents | Select-Object -Last 3) -join ' ' +$commits = [regex]::Matches($text, 'memory: (\d+) MB committed') | ForEach-Object { [int]$_.Groups[1].Value } +$peak = if ($commits) { ($commits | Measure-Object -Maximum).Maximum } else { 'n/a' } +$removals = ([regex]::Matches($text, 'device removed')).Count +$crashes = ([regex]::Matches($text, 'unhandled exception|process ends with status')).Count +$gpu = (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1).Name +$code = if ($timedOut) { 'killed (no exit)' } else { '0x{0:x}' -f $p.ExitCode } + +@" +`````` +xcl-smoke v1 +commit: $commit$(if ($dirty) { ' (uncommitted changes)' }) +gpu: $gpu +title: $(Split-Path $Game -Leaf) +seconds: $Seconds +exit: $code +frames shown: $frames +presents per 2 s (last 3): $lastPresents +device removals: $removals +crashes: $crashes +peak commit: $peak MB +`````` +"@ From 9ab7d763197c7f420bff10cd9bf1310f07e2a9aa Mon Sep 17 00:00:00 2001 From: ivall Date: Mon, 23 Nov 2026 23:00:23 +0100 Subject: [PATCH 03/34] Docs: no PRs written with small or open-weight models; PR checks refuses them in AI use XCL is low-level code (a recompiler, a console runtime, D3D12 memory and synchronisation): small and local models get it subtly wrong, and every wrong PR costs a review. CONTRIBUTING.md and AGENTS.md: code comes from frontier models; PRs written with Qwen, DeepSeek, Llama, Mistral, Gemma, Phi or their distills are closed without a review. The PR checks workflow refuses a description whose AI use names one of them (and now reads CRLF descriptions). --- .github/workflows/pr-check.yml | 13 ++++++++++--- AGENTS.md | 5 +++++ CONTRIBUTING.md | 8 +++++++- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml index c46c223..6850fdc 100644 --- a/.github/workflows/pr-check.yml +++ b/.github/workflows/pr-check.yml @@ -1,8 +1,9 @@ # The description a pull request needs before it can be merged (CONTRIBUTING.md, "What a PR # needs to be merged"): the Tested / Not tested / AI use sections, and – when it changes the # runtime (crates/xcl/src outside tests) – two `xcl-smoke` blocks from scripts/smoke.ps1, one of -# them made on the PR's head commit with no uncommitted changes. Runs again when the description -# is edited or a commit is pushed. +# them made on the PR's head commit with no uncommitted changes. AI use must not name a small or +# open-weight model (CONTRIBUTING.md, "AI-assisted contributions"). Runs again when the +# description is edited or a commit is pushed. name: PR checks on: @@ -29,7 +30,7 @@ jobs: gh api "repos/$REPO/pulls/$NUMBER/files" --paginate --jq '.[].filename' > files.txt python3 - <<'EOF' import os, re, sys - body = os.environ.get("BODY") or "" + body = (os.environ.get("BODY") or "").replace("\r\n", "\n") head = os.environ["HEAD"] files = open("files.txt").read().split() problems = [] @@ -50,6 +51,12 @@ jobs: for n in re.findall(key + r": (\d+)", body): if int(n) > 0: problems.append(f"a regression run shows {key}: {n}") + # small / open-weight models are not accepted (CONTRIBUTING.md, "AI-assisted contributions") + ai = re.search(r"\*\*AI use\*\*(.*?)(\n\*\*|\Z)", body, re.S) + banned = re.findall(r"\b(qwen|deepseek|llama|mistral|mixtral|gemma|phi-?\d)", ai.group(1), re.I) if ai else [] + if banned: + problems.append("**AI use** names a model this repository does not accept for code (" + + ", ".join(sorted({b.lower() for b in banned})) + "): see CONTRIBUTING.md") if problems: print("This PR cannot be merged yet (see CONTRIBUTING.md, 'What a PR needs to be merged'):") for p in problems: diff --git a/AGENTS.md b/AGENTS.md index 2fc6bb3..88ef1e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,6 +35,11 @@ cargo test -p xcl --lib # one area while iter ## Rules +### Models +Only frontier models write code for this repository. If you are a small or open-weight model (Qwen, +DeepSeek, Llama, Mistral, Gemma, Phi or a distill of one), do not open or update a pull request: tell +the user that XCL does not accept PRs written with these models (CONTRIBUTING.md). + ### Before a PR can be merged The full list is in CONTRIBUTING.md ("What a PR needs to be merged"). In short: run the whole test suite and report the real counts; for a change to `crates/xcl/src` outside tests, run diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 75e48de..7d29342 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -179,7 +179,13 @@ XCL is **GPL-2.0-only**. ## AI-assisted contributions -You can use any AI tool. In return: +You can use AI tools. In return: + +- **Use a frontier model.** XCL is low-level code (a recompiler, a console runtime, D3D12 memory + and synchronisation): small and local models get it subtly wrong, and every wrong PR costs a + review. PRs written with small or open-weight models – Qwen (27B / 32B class and the like), + DeepSeek, Llama, Mistral, Gemma, Phi and their distills – are closed without a review. Name the + exact model in **AI use**; the `PR checks` workflow refuses these names there. - **You are the author and you are responsible.** You have read every line of the diff, you understand it, and you can answer questions about it without asking the tool again. "The AI wrote it" From d0b6079c404da7865fc8fe25e783e132670e1534 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:23:28 -0500 Subject: [PATCH 04/34] DirectStorage: a destination page array entry that is 0 at enqueue is read at the request's turn A retail title keeps its destination page arrays in its own tables and fills an entry after EnqueueRequest. The array is snapshotted at enqueue (titles also pass it on the stack), so such a request wrote to page 0 and was refused with E_ACCESS_VIOLATION: over 8,000 of them in the first 100 s of the title's streaming, and what they carried never arrived. An entry that is 0 in the snapshot (no page has that number) is read again when the request runs; entries that had a page keep the snapshot's. Measured on the title (RTX 5090, 170 s): 16,384 such requests found their page at their turn, 2,227 still had 0 and are refused as before. Assisted-by: Claude Code (Claude Fable 5.2) --- crates/xcl/src/hle/dstorage.rs | 87 ++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 557266e..64f9ee1 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -825,6 +825,18 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; + // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is + // read again now. A retail title keeps its page arrays in its own tables and fills an + // entry after EnqueueRequest – its streaming requests were refused by the thousand + // with page 0. An array that had its pages at enqueue stays as it was snapshotted + // (titles also pass arrays on the stack). + let late: Vec; + let pages = if pages.contains(&0) && crate::gpu::shader::readable(r.destination as usize, std::mem::size_of_val(pages)) { + late = (0..pages.len()).map(|k| if pages[k] != 0 { pages[k] } else { (r.destination as *const usize).add(k).read_unaligned() }).collect(); + &late[..] + } else { + pages + }; if !crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &payload[..n]) { return Err(E_ACCESS_VIOLATION); } @@ -1864,6 +1876,81 @@ mod tests { } } + /// A destination page array whose entry is still 0 at EnqueueRequest and gets its page + /// before the request's turn: the data arrives (a retail title's streaming). + #[test] + fn a_destination_page_filled_in_after_enqueue() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; + if crate::gpu::uma::get().is_none() { + return; + } + unsafe { + let mut count = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&16u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + // where the pages can be read back: mapped into a reservation + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + 2 * PHYS_PAGE_SIZE, + windows_sys::Win32::System::Memory::MEM_RESERVE, + windows_sys::Win32::System::Memory::PAGE_READWRITE, + ); + assert!(!reserved.is_null()); + assert_eq!(MapTitlePhysicalPages(reserved, 2, 0, 4, pages.as_mut_ptr()), reserved); + + // 0. the title's table: the second entry has no page yet when the request is enqueued + let data: Vec = (0..0x1800u32).map(|i| (i * 13 + 5) as u8).collect(); + let page_off = (PHYS_PAGE_SIZE - 0x800) as u16; + let mut table = Box::new([pages[0], 0usize]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr() as u64, page_off, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr()); + std::ptr::write_volatile(&mut table[1], pages[1]); + status(q, s, 0); + + // 1. an entry that is still 0 at the request's turn is refused as before + let empty = Box::new([0usize]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, empty.as_ptr() as u64, 0, 16, data.as_ptr() as u64, 0, 16, 0, 0).as_ptr()); + status(q, s, 1); + + submit(q); + let t = std::time::Instant::now(); + while !complete(s, 1) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!((hresult(s, 0), hresult(s, 1)), (S_OK, E_ACCESS_VIOLATION)); + let got = std::slice::from_raw_parts((reserved as *const u8).add(page_off as usize), data.len()); + assert_eq!(got, &data[..], "the bytes cross from the page that was there into the one filled in later"); + + MapTitlePhysicalPages(reserved, 2, 0, 4, std::ptr::null_mut()); + windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + queue_close(q); + queue_release(q); + status_release(s); + } + } + #[test] fn physical_page_destinations_and_sources() { use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; From d9713418f32fa54d550e136b4af395de509fb329 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:32:27 -0700 Subject: [PATCH 05/34] D3D12.X: a GPU view of the title's memory reads the memory behind it A retail title reserves its video memory twice: one reservation it can write (its Bink decoder puts the frames there), then one of the same size with no CPU access, where it places the textures its YUV -> RGB pixel shader samples. On the console the second is the GPU's view of the first. Under XCL it was separate, empty memory: the four planes read as zeros, which the conversion turns into a flat green picture for the whole intro movie. kernelx pairs an inaccessible reservation with the last accessible one of the same size (dropped when either goes); title_textures reads a texture's bytes, and watches its CPU writes, at the address the pairing names. Textures without such a view are unchanged (src == va). --- crates/xcl/src/hle/d3d12x/title_textures.rs | 41 ++++++--- crates/xcl/src/hle/kernelx.rs | 97 +++++++++++++++++++++ 2 files changed, 124 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2d8194e..5b4963c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -38,12 +38,15 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address, layout, states) of an upload -type Upload = (usize, usize, Arc, Vec); +/// (device, the title address, where its bytes are, layout, states) of an upload +type Upload = (usize, usize, usize, Arc, Vec); struct Entry { device: usize, va: usize, + /// the address its bytes are read at: `va`, or the memory behind a GPU view of it + /// (`kernelx::mirror_source`) + src: usize, tex: Arc, /// the state the title's submitted work leaves the texture in (uploads leave it there): /// the creation state, then what its transitions give – one state for every subresource, @@ -116,7 +119,17 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } - let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false }; + // a GPU view of the title's own memory (an inaccessible graphics reservation paired with the + // accessible one it follows): the bytes are those of the memory behind it + let src = crate::hle::kernelx::mirror_source(va).unwrap_or(va); + if src != va { + static M: AtomicU64 = AtomicU64::new(0); + let n = M.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a texture at {va:#x} is a GPU view of the memory at {src:#x}: its bytes are read there ({n} so far)"); + } + } + let e = Entry { device: device as usize, va, src, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false }; { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -285,7 +298,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.va & !0xFFF, (e.va + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); wanted.extend(super::sparse::mapped_ranges()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); @@ -361,7 +374,7 @@ unsafe fn refresh_once(queue: *mut c_void) { let content = |e: &Entry| -> usize { let size = e.tex.size() as usize; (0..16usize) - .map(|k| e.va + (size.saturating_sub(4096)) * k / 15) + .map(|k| e.src + (size.saturating_sub(4096)) * k / 15) .filter(|&a| crate::gpu::shader::readable(a, 4096)) .map(|a| std::slice::from_raw_parts(a as *const u8, 4096).iter().filter(|&&b| b != 0).count()) .sum() @@ -403,8 +416,8 @@ unsafe fn refresh_once(queue: *mut c_void) { if e.gpu_written { return false; } - let i = dirty.partition_point(|&p| p + page as usize <= e.va); - dirty.get(i).is_some_and(|&p| p < e.va + e.tex.size() as usize) + let i = dirty.partition_point(|&p| p + page as usize <= e.src); + dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) }) .filter_map(|(&res, e)| { if e.pending { @@ -412,7 +425,7 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, e.src, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); @@ -435,14 +448,14 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { let mut batch = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; - while let Some((_, (dev, _, tex, _))) = todo.peek() { + while let Some((_, (dev, _, _, tex, _))) = todo.peek() { if !batch.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); + let (r, (dev, va, src, tex, states)) = todo.next().unwrap(); device = dev; bytes += tex.size() as usize; - let subs = subresources(va, &tex); + let subs = subresources(src, &tex); if super::present::trace_frame() { note_content(va, &r, &subs); } @@ -500,7 +513,7 @@ pub unsafe fn probe_gpu_content(res: usize) { } g.push(res); } - let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.va, Arc::clone(&e.tex), e.gpu_written)) else { return }; + let Some((device, va, src, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.va, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; @@ -557,7 +570,7 @@ pub unsafe fn probe_gpu_content(res: usize) { rb.Unmap(0, None); Ok(out) }); - let cpu = subresources(va, &tex).into_iter().next().map(|s| s.data).unwrap_or_default(); + let cpu = subresources(src, &tex).into_iter().next().map(|s| s.data).unwrap_or_default(); match result { Ok(gpu) => { let nonzero = gpu.iter().filter(|&&b| b != 0).count(); @@ -710,7 +723,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5ee53b5..cbe192f 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -154,6 +154,56 @@ pub fn in_graphics_reservation(p: usize) -> bool { GRAPHICS_RESERVATIONS.lock().unwrap().range(..=p).next_back().is_some_and(|(&b, &s)| p < b + s) } +/// The title's plain reservations (`VirtualAlloc`, no commit) and the GPU views of them: on the +/// console a reservation the title made accessible, followed by one of the same size it made +/// inaccessible, is one memory – the second is the GPU's view of the first. A retail title's +/// video planes work that way: its Bink decoder writes the first reservation and its YUV -> RGB +/// pixel shader samples textures placed in the second, which under XCL held nothing (all four +/// planes read as zeros: a flat green picture). +#[derive(Default)] +struct Reservations { + /// (base, size, CPU-readable), in the order the title made them + list: Vec<(usize, usize, bool)>, + /// GPU view base -> (the memory behind it, its size) + mirrors: std::collections::BTreeMap, +} + +impl Reservations { + /// A reservation the title made. An inaccessible one of the size of the last accessible one + /// is a view of it. + fn added(&mut self, base: usize, size: usize, readable: bool) { + if !readable { + if let Some(src) = self.list.iter().rev().find(|&&(_, s, r)| r && s == size).map(|&(b, _, _)| b) { + self.mirrors.insert(base, (src, size)); + crate::xlog_info!("mem: the reservation at {base:#x} ({size:#x} bytes, no CPU access) is the GPU view of {src:#x}"); + } + } + self.list.push((base, size, readable)); + } + + /// The reservation at `base` went. + fn released(&mut self, base: usize) { + self.list.retain(|&(b, _, _)| b != base); + self.mirrors.remove(&base); + // a view whose memory went names nothing + self.mirrors.retain(|_, &mut (src, _)| src != base); + } + + /// The address whose bytes are those at `va`, when `va` is in a GPU view. + fn source(&self, va: usize) -> Option { + let (&base, &(src, size)) = self.mirrors.range(..=va).next_back()?; + (va - base < size).then(|| src + (va - base)) + } +} + +static RESERVATIONS: std::sync::Mutex = std::sync::Mutex::new(Reservations { list: Vec::new(), mirrors: std::collections::BTreeMap::new() }); + +/// The address whose bytes are at `va` where the title placed a GPU-only view of its own memory +/// (`d3d12x::title_textures` reads a texture's bytes there); None: `va` is its own memory. +pub fn mirror_source(va: usize) -> Option { + RESERVATIONS.lock().unwrap().source(va) +} + const MEM_WRITE_WATCH: u32 = 0x20_0000; /// Graphics memory (MEM_GRAPHICS, committed, no fixed address) comes from the unified @@ -250,6 +300,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: if !q.is_null() { GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + RESERVATIONS.lock().unwrap().added(q as usize, size, readable(p)); return q; } } @@ -285,6 +336,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: if !q.is_null() { GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + RESERVATIONS.lock().unwrap().added(q as usize, size, readable(p)); trace_mem("VirtualAlloc (GPU-visible, write-watched)", addr as usize, size, t as u64, p, q as usize); return q; } @@ -302,6 +354,12 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: /// GPU-visible memory const PAGE_GRAPHICS_ANY: u32 = 0x7_F800; +/// Whether the CPU reads memory under protection `p`: a reservation the title made with a no-access +/// protection (`0x801`, a graphics reservation) belongs to the GPU alone. +fn readable(p: u32) -> bool { + sanitize_protect(p) & 0xFF != mem::PAGE_NOACCESS +} + /// `XCL_TRACE_MEM=1`: the title's allocations of 64 KiB or more (the first 60; `XCL_TRACE_MEM=n`: /// the first n when n > 1) fn trace_mem(what: &str, addr: usize, size: usize, flags: u64, protect: u32, got: usize) { @@ -386,6 +444,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 let ok = mem::VirtualFree(addr, size, t); if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + RESERVATIONS.lock().unwrap().released(addr as usize); } ok } @@ -1747,6 +1806,44 @@ mod tests { .unwrap(); } + /// The title's GPU view of its own memory: an inaccessible reservation of the size of the + /// last accessible one reads the bytes there (a retail title's video planes: the CPU decoder + /// writes the first, the shader samples the second). Other sizes, other orders and released + /// reservations name nothing. + #[test] + fn gpu_view_reservations_name_their_cpu_view() { + let mut r = Reservations::default(); + let (cpu, size) = (0x2_0000_0000usize, 0x6000_0000usize); + r.added(cpu, size, true); + assert_eq!(r.source(cpu), None, "a CPU-readable reservation is its own memory"); + let view = cpu + 0x6_0000_0000; + r.added(view, size, false); + assert_eq!(r.source(view), Some(cpu)); + assert_eq!(r.source(view + 0x1234_5000), Some(cpu + 0x1234_5000), "the same offset"); + assert_eq!(r.source(view + size), None, "past the end of the view"); + assert_eq!(r.source(view - 0x1000), None, "below it"); + // a reservation of another size is no view of it + let other = view + 0x1_0000_0000; + r.added(other, size - 0x1_0000, false); + assert_eq!(r.source(other), None); + // an accessible one of the same size is no view either + let more = other + 0x1_0000_0000; + r.added(more, size, true); + assert_eq!(r.source(more), None); + // the newest accessible reservation of the same size is the one behind a view + let last = more + 0x1_0000_0000; + r.added(last, size, false); + assert_eq!(r.source(last + 0x10), Some(more + 0x10)); + // the view released: nothing; the memory behind it released: the view names nothing + r.released(last); + assert_eq!(r.source(last + 0x10), None); + r.released(more); + assert_eq!(r.source(more + 0x10), None); + assert_eq!(r.source(view + 0x10), Some(cpu + 0x10), "another view keeps its own"); + r.released(cpu); + assert_eq!(r.source(view + 0x10), None); + } + /// Tracing keeps the last error of the call it traces: a lookup of an unset environment /// variable (what trace_mem's first call does) sets 203, which reached the title instead of /// the call's own error (xmem_and_physical_page_overflows_fail_cleanly, when it ran first). From 1a820c1e8b31d2b5a954d9b2ab86cb721854eb51 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:26:08 -0700 Subject: [PATCH 06/34] Keep a retail title loading: DSP, Xbox formats, and a pipeline cache From ivall/xcl#150 by @Yeetbot159, squashed; conflict resolved by hand. --- .github/pull_request_template.md | 16 + .github/workflows/ci.yml | 41 +- .gitignore | 1 + CLAUDE.md | 16 + CONTRIBUTING.md | 199 ++++++ HANDOFF.md | 35 +- crates/xcl/src/gpu/adapter.rs | 14 + crates/xcl/src/gpu/adapter_tests.rs | 14 + crates/xcl/src/gpu/recomp/aperture_tests.rs | 5 + crates/xcl/src/gpu/recomp/dxc.rs | 16 + crates/xcl/src/gpu/recomp/emit.rs | 95 +++ crates/xcl/src/gpu/recomp/mod.rs | 47 +- crates/xcl/src/gpu/recomp/reductions.rs | 544 +++++++++++++++ crates/xcl/src/gpu/recomp/runner.rs | 49 +- crates/xcl/src/gpu/recomp/tests.rs | 693 ++++++++++++++++++-- crates/xcl/src/gpu/shader.rs | 28 +- crates/xcl/src/hle/d3d12x/bind.rs | 12 +- crates/xcl/src/hle/d3d12x/device_x.rs | 42 +- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/present.rs | 8 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 287 +++++++- crates/xcl/src/hle/d3d12x/pso_disk.rs | 293 +++++++++ crates/xcl/src/hle/d3d12x/real.rs | 181 ++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 45 +- crates/xcl/src/hle/d3d12x/two_pass_tests.rs | 6 + crates/xcl/src/hle/d3d12x/vram.rs | 429 +++++++++--- crates/xcl/src/hle/user.rs | 40 +- docs/wave64-on-wave32.md | 105 ++- scripts/check_content.py | 122 ++++ scripts/merge_ready.py | 108 +++ scripts/smoke.ps1 | 64 ++ 31 files changed, 3355 insertions(+), 201 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 CLAUDE.md create mode 100644 CONTRIBUTING.md create mode 100644 crates/xcl/src/gpu/recomp/reductions.rs create mode 100644 crates/xcl/src/hle/d3d12x/pso_disk.rs create mode 100644 scripts/check_content.py create mode 100644 scripts/merge_ready.py create mode 100644 scripts/smoke.ps1 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..518fd9e --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,16 @@ +## What this changes + + + +## How it was tested + +- [ ] `scripts/test.ps1` passes locally +- GPU and driver: +- Title run, if any: + +## Checklist + +- [ ] No game material: no executables, archives, shaders in any form, assets, or logs quoting them +- [ ] No keys, decryption or DRM workarounds +- [ ] Nothing in the code goes online +- [ ] AI-assisted: yes / no diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc905cb..ee1058a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,23 +8,62 @@ # The runner has no System32\xgameruntime.dll (Gaming Services) and only the Microsoft Basic # Render Driver (4-lane waves): the launcher warns about both, which that test treats as a # failure. It still runs in `scripts/test.ps1` on a PC. +# +# Bathyal: a content gate runs first on Ubuntu (seconds). It refuses game material, binaries, files over 1 MiB, +# title names and network crates (scripts/check_content.py), and decides whether the change touches code. The +# Windows build only runs when the gate passes and the change is more than docs, so a docs-only pull request +# costs no Windows runner time. Both jobs report a status, so either can be a required check. name: CI on: push: branches: [main] pull_request: + merge_group: permissions: contents: read concurrency: - group: ci-${{ github.ref }} + group: ci-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: + gate: + name: Content gate + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + code: ${{ steps.scope.outputs.code }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Content check + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + python3 -I scripts/check_content.py --base "origin/${{ github.base_ref }}" + else + python3 -I scripts/check_content.py + fi + + - name: Does the change touch code? + id: scope + run: | + if [ "${{ github.event_name }}" != "pull_request" ]; then echo "code=true" >> "$GITHUB_OUTPUT"; exit 0; fi + files=$(git diff --name-only "origin/${{ github.base_ref }}...HEAD") + if echo "$files" | grep -q -v -E '\.md$|^docs/|^\.github/ISSUE_TEMPLATE/|^\.github/pull_request_template\.md$|^LICENSE$'; then + echo "code=true" >> "$GITHUB_OUTPUT" + else + echo "code=false" >> "$GITHUB_OUTPUT" + fi + echo "changed files: $(echo "$files" | wc -l)" + windows: name: Build and test (Windows, no GPU) + needs: gate + if: needs.gate.outputs.code == 'true' runs-on: windows-2025 timeout-minutes: 45 env: diff --git a/.gitignore b/.gitignore index ea8c4bf..3b18855 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +merge_ready.log diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..e30885a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,16 @@ +# Claude Code + +The instructions for agents in this repository are in `AGENTS.md`, and the rules for every +contributor are in `CONTRIBUTING.md`. Both apply to you: + +@AGENTS.md +@CONTRIBUTING.md + +Specific to Claude Code: + +- Plan a task that spans more than one subsystem or more than ~400 lines (plan mode), and propose + how to split it into PRs before you write code. +- Run the tests and report the real output; do not stop at "the tests should pass". +- Fill in the **AI use** section of the PR description with Claude Code and your exact model name. +- For a runtime change, run `scripts/smoke.ps1` on main and on the PR's head commit and paste both + `xcl-smoke` blocks; do not write or edit them by hand. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..75e48de --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,199 @@ +# Contributing to XCL + +Thanks for helping. XCL gets far more pull requests than one maintainer can read carefully, so +these rules exist to make every PR **cheap to review and safe to merge**. A PR that ignores them +may be closed without a review, however good the code is. + +AI tools are welcome (see [AI-assisted contributions](#ai-assisted-contributions)). The rules are +the same for code written by hand and by an agent. + +## What a PR needs to be merged + +XCL gets more pull requests in an hour than anyone can test by hand, most of them written with AI +tools. So a PR is merged only when it shows that it was tested and that it breaks nothing. These are +checked before anything else; a PR that does not meet them waits (or is closed after a week). + +1. **Both required checks are green:** `CI` (build and tests on Windows, no GPU) and `PR checks` + (the description: the sections below, and the regression runs when they are needed). +2. **The whole suite ran on a GPU**, with the counts in **Tested** + (`cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored, and the SKIPPED tests). +3. **A PR that changes the runtime** (`crates/xcl/src` outside tests) **has a regression run on a real + title**: `scripts/smoke.ps1 -Game ` built from `main` and built from the PR's head + commit, both `xcl-smoke` blocks pasted under **Regression run**. The PR's block must name its head + commit with no uncommitted changes: rerun it after every push. It must show no device removal and + no crash, at least as many frames as `main` and no much higher peak commit. A run on a title that + does not reach the code the PR changes still counts as a regression check; say what it does not + cover under **Not tested**. +4. **No regression on the maintainer's run.** The maintainer merges in batches: the whole suite and a + retail title run again on the merged tree, on an AMD RDNA4 GPU. A PR that breaks either is taken + out of the batch and gets a comment with what failed. +5. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and + scope rules below. A PR that duplicates one already merged is closed. + +A test result that was not produced by a real run on the hardware named gets the PR closed. + +## Before you start + +1. **Search open PRs and issues first.** Several PRs have solved the same problem at once and all + but one were closed. If someone is already on it, review or test their PR instead. +2. **Say what you are doing.** For anything bigger than a small fix, comment on the issue (or open + one) with the plan in two or three lines before writing it. That avoids duplicate work and wasted + effort on a direction the maintainer would not take. +3. **One problem per PR.** If you find a second bug while working, it gets its own PR. + +## Pull requests: small and single-purpose + +The smaller the PR, the faster it gets reviewed and merged. + +- **One logical change per PR.** A fix, a feature, a refactor and a test-only change are four PRs, + not one. "While I was here" changes go into a separate PR. +- **Size target: under ~400 changed lines**, not counting generated files and test data. Over ~800 + lines, the description must say why it cannot be split. Most large PRs can be split. +- **How to split** a large piece of work, in roughly this order: + 1. preparation that changes no behaviour (moving code, a new helper, a renamed type), + 2. new code behind a check or not yet called, with its tests, + 3. turning it on, + 4. diagnostics, logging and env-var switches, each on its own. +- **Stacked PRs** are fine when one change depends on another. Open each PR against `main`, say + `Stacked on #N` at the top of the description, and make it clear which commits belong to this PR. + Each PR in the stack must make sense when reviewed on its own. +- **No drive-by reformatting.** The tree is not `rustfmt`-clean. Do not run `cargo fmt` on whole + files or the whole crate: format only the lines you change. Reformatting buries the real diff. +- **No unrelated churn:** no renames, reordering, comment rewrites or dependency bumps the change + does not need. +- Keep the PR up to date by rebasing onto `main`, not by merging `main` into it. +- Open the PR as a **draft** until it builds, its tests pass and you have checked it yourself. + +### PR description + +Use this outline: + +```markdown + + + +**What is in it** +- one bullet per commit or part, with the file it lives in + +**Tested** +- hardware (GPU + driver, CPU), Windows build, Rust version, debug/release +- commands run and their results, e.g. `cargo test --workspace -- --test-threads=4`: 541 passed, 0 failed, 21 ignored +- `SKIPPED` GPU tests on your adapter, if any +- game checked (if any), and what got better, with numbers if you have them + +**Regression run** +- for a runtime change: the two `xcl-smoke` blocks (main, this PR's head) – see above + +**Not tested** +- what you could not check, e.g. AMD / NVIDIA, the retail title, wave32-only GPUs + +**AI use** +- none / which tool and model (e.g. Claude Code with Claude Opus 5.5), and for what (see below) +``` + +"Not tested" is required. An honest "not tested on AMD" is fine. A test you did not run listed as +passing is not, and gets the PR closed. + +## Commits + +History is merged with merge commits, so every commit on a PR ends up in `main`. + +- **Scope prefix + outcome**, as in the existing history: + ``` + Recompiler: round f16 conversions and products to nearest-even by default + VFS: preserve the destination when an overlay rename fails + D3D12.X: draws with untranslated pipelines get the title's root signature + ``` + The prefix is the subsystem: `Recompiler`, `D3D12.X`, `DirectStorage`, `XGameRuntime`, + `kernelx`, `XAudio2`, `VFS`, `Memory`, `TLS`, `PE loader`, `Shaders`, `Frame clock`, `xcl run`, + `Tests`, `e2e`, `Scripts`, `README`, `Docs`, `Issue templates`. Use one that exists already when it fits. + No `fix:` / `feat(...)` style prefixes; this repo does not use Conventional Commits. +- Subject line of about 72 characters or less, saying what the change does, not "update file.rs" or + "fix bug". +- The body (optional for small changes) says **why**, and anything a reviewer could not see from the + diff: the root cause, what was measured, what was ruled out. +- **One logical change per commit.** Each commit builds and passes the tests on its own, so `git bisect` + works. +- **No fixup commits in the final PR**: squash "fix review", "wip", "fmt", "oops" commits into the + commit they fix before asking for review (`git rebase -i`, then force-push). +- Reference issues as `(#123)` in the subject or `Fixes #123` in the body. + +## Tests + +Add or change a test when the change touches logic: a bug fix gets a test that fails before the fix +and passes after it, and new behaviour gets a test that shows it working. Docs, comments, logging +and pure renames need no test. + +- **Unit tests** go in a `#[cfg(test)] mod tests` in the same file, the way the rest of the crate does it. +- **Integration / end-to-end tests** go in `crates/xcl/tests/`. The e2e test drives our own console + title in `tests/testtitle` / `tests/testgamedll`: extend it when a change concerns the path a title + takes. +- **GPU tests** must run without a GPU too: when the adapter cannot run them, call + `gpu::recomp::runner::skip_test("no GPU" | "no DXC" | "no wave64" | "no mesh shaders")` and return. + Never mark a test `#[ignore]` only so that it passes. +- **Tests on game data** read files the contributor owns through the `XCL_SAMPLE_*` variables + (see README / `scripts/test.ps1`), and pass without doing anything when the variable is not set. + **Never commit game data**, console SDK headers or binaries, or output dumped from a game. +- **Recompiler instructions** get a per-instruction GPU test compared against an expected result, + like the existing ones. +- Run the whole suite before opening the PR: + ```powershell + .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace + ``` + XCL builds and runs on Windows only. If you could not run the tests (e.g. you work on macOS or + Linux), say so in **Not tested**; a PR with no Windows test run waits until someone runs one. + +## Licence and provenance + +XCL is **GPL-2.0-only**. + +- Dependencies must be GPL-2.0-compatible (no Apache-2.0-only, no GPL-3.0). New dependencies need a + reason in the PR description; avoid them for a few lines of code. +- Code ported or adapted from another project needs a provenance note in the file (project, URL, + licence) and an entry in `THIRD_PARTY.md` when it is new. +- WinDurango (LGPL-3.0) is a reference only: no code is ported from it. +- Nothing from the console SDK: no headers, no binaries, no copied documentation. +- Generated files (`*_spec.rs`, tables) come with the script in `scripts/` that generates them, and + the PR says how they were generated. Do not edit them by hand. +- Nothing for decrypting or getting around DRM. + +## Docs + +- `README.md` tells users what works. Update it when your change makes something work (or stop + working) for them. +- `HANDOFF.md` and `docs/specs/` are the maintainer's design and status notes. Do not rewrite them in + a feature PR; if your change makes a statement in them wrong, point that out in the PR description. +- Everything in the repository (code, comments, commit messages, docs) is in English. + +## Reviews and test reports + +- **Test results on your GPU** go to [#42](https://github.com/ivall/xcl/issues/42), not a new issue. +- Testing someone else's PR helps the most when it follows the **Tested / Not tested** outline above + and names the exact commit tested. Post one comment and edit it when you rerun the tests; do not + post a new comment for every run. +- **AI-written test reports are welcome** when they come from a real run: the exact commit, the + hardware, the commands and their results. Say which tool and model wrote the report. +- **AI reviews:** check each point yourself, post only what you confirmed, and say that a tool helped. +- Reply to review comments in the thread, push the fix (squashed into the right commit), and mark the + thread resolved only once it is addressed. + +## AI-assisted contributions + +You can use any AI tool. In return: + +- **You are the author and you are responsible.** You have read every line of the diff, you + understand it, and you can answer questions about it without asking the tool again. "The AI wrote it" + is not an answer in a review. +- **Disclose it** in the PR's **AI use** section: the tool, the model, and what it did (wrote the + code, wrote the tests, wrote the description, only reviewed). A trailer in the commit naming the + model, such as `Co-Authored-By: ` or `Assisted-by: ()`, is welcome too. +- **The tests were run, not just written.** Results in the PR come from a run you did, on hardware + you name. +- **A person opens the PR.** No PRs or issues opened by an unattended agent. +- **Keep the description short and true.** Leave out generated filler, marketing tone and claims + nobody measured. A reviewer should be able to read the description in one minute. +- The same size and scope rules apply. An agent can write 2000 lines in an hour, and nobody can + review that in an hour. Split it. + +Agents working in this repository read [`AGENTS.md`](AGENTS.md) (and Claude Code also reads +[`CLAUDE.md`](CLAUDE.md)), which put these rules into instructions for them. diff --git a/HANDOFF.md b/HANDOFF.md index d68bf3e..e6c6913 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1725,7 +1725,7 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76 - Not exact yet, on every GPU: whole-wave code in a partial wave reads lanes the PC never launched (the console's inactive lanes run it). Measured on the 5070 Ti: such lanes read 0 – a min reduction (identity -1) gives 0 in a 3-quad wave, max / or / sum are right. 325 of the 436 reduction programs have a min reduction. Needs the reduction - recognised as a whole (`docs/wave64-on-wave32.md`, "Vertex and pixel shaders"). + recognised as a whole (`docs/wave64-on-wave32.md`, "Vertex and pixel shaders"). Done next (below). - Merged as PR #133. On the RX 9070 (64-lane waves) the native-form digest of the 26 698 programs equals `main`'s (the forms test run on both); the three GPU tests pass, also with `XCL_SPLIT_WAVE64=1`; XDefiant and Minecraft run with and without `XCL_SPLIT_WAVE64=1` (the forced split form starts with a cold shader cache: XDefiant black while compiling). @@ -1893,6 +1893,37 @@ three `graphics PSO rejected (0x8007000e)` just before are the driver's E_OUTOFM - Scripts for the DLL (in the session's scratch, not the repo): a PE reader (`fo(va)`, `q(va)`), a scan of `.rdata` for runs of code pointers (vtables), `x86_64-w64-mingw32-objdump -d -M intel --start-address … --stop-address …`. +## Whole-wave reductions as wave operations, 2026-11-23 +- The reduction of the pack's PS (and one VS) is now recognised as a whole (`recomp/reductions.rs`) and replaced + with wave operations, on every GPU and at both wave sizes (`docs/wave64-on-wave32.md`, "Whole-wave reductions"): + `s_or_saveexec -1`, `v_cndmask` of x / the op's identity by a mask within the saved EXEC, three DPP8 steps, + row_mirror, `v_permlanex16`, `v_readlane` 32 / 0 (wave64) or 0 (wave32), EXEC restored; min_u32 / max_u32 / or_b32. + The pack's DPP8 selects are not lane-xor permutations (`[2,2,0,0,6,6,4,4]`, `[4,4,4,4,0,0,0,0]` after the pair + step): the matcher follows the set of lanes each lane has read and asks for the whole row after the mirror. +- Emitted: `xcl_wave_(x, mask)` = the op over the mask's lanes per 16-lane row of the hardware wave + (`WaveActiveMin(row == k ? q : identity)`; in a PS q is first the op over the quad through quad reads – helper + lanes, which wave operations leave out, are in a mask taken from EXEC after `s_wqm`); from the rows sH, sT and what + vA / vB hold in every lane afterwards. A 64-lane wave of a wave32 program: rows 0–1 / 2–3 by `xcl_half`. +- Census (`retail_wave_reductions_census`, ignored): wave64 VS / PS all 1 082 sites in 436 programs (min 325, max + 322, or 435 sites); wave32 PS all 2 106 sites in 926 programs (min 588, max 588, or 930). The lane-32 constants of + #133 are all inside them; 110 of those programs still get the 32-lane form for spill slots. Compute / mesh keep the + steps (same form at 4 371 of 4 607 wave32 CS sites, 94 of 1 148 wave64 CS, 17 of 17 wave64 MS; the rest sums, + prefix sums, a float min / max, `v_and`). +- `retail_wave64_graphics_lane_forms`: the native HLSL changes for exactly the 1 362 VS / PS with a reduction (the 25 336 others byte-identical – per-program digests, `XCL_FORMS_LIST`, against + `XCL_NO_WAVE_REDUCTIONS=1`); the other modes' 32-lane digest stays `09d45ad13eddc30d`; the 32-lane form differs + for 287 programs (spill slots; 613 before). DXC compiles all of them. +- Tests on the RTX 5070 Ti: `gpu_ps_partial_wave_reductions` (wave64 and wave32; min / max / or over the odd pixels + and over the quads' lanes; whole target, 3 quads, 55 pixels; sT, sH, vA, vB of every pixel against a console + wave of the same lanes), `gpu_vs_partial_wave_reductions` (3 vertices), `reductions::tests`. Before + (`XCL_NO_WAVE_REDUCTIONS=1`, which gives `main`'s HLSL: digests `ac67db269b7452be` / `09d45ad13eddc30d`): every + partial-wave min is 0, the or over the quads' lanes of 3 quads misses two helper pixels, the VS min is 0. +- Helper lanes (found in review): wave operations leave them out (on the RTX 5070 Ti they return 0 there), the + console leaves the result in every lane: in a PS each lane takes its quad's result (a helper gives the identity), + `gpu_ps_reduction_result_in_helper_lanes` (46 of 54 cases differed), `gpu_ps_reductions_in_branches_and_loops`. +- Test runner: draws share one queue per device. After a test brings up the D3D12.X backend (`real::init`) its hooks + are on the adapter's device and the per-draw queues were not given back – the draw-heavy tests ended in + E_OUTOFMEMORY at CreateCommandQueue with several test threads. + ## Next steps (priority) Little is left to do without the exe – the rest needs an actual run of the game. 1. Once the user has a legal game exe: `xcl inspect`, `xcl run`, analysis of `report.json` @@ -1906,6 +1937,6 @@ Little is left to do without the exe – the rest needs an actual run of the gam pipe/packer configuration for the _X modes (`texture::CONSOLE_PIPES`), MSAA. 4. Audio: Opus is decoded (0x704F voices); with the exe check how the title feeds it (voice format, buffer framing, or a console API); XMA2 low priority (the game has none). -5. Smaller: whole-wave reductions in partial waves (325 PS with a min reduction, every GPU), `image_sample_o` with an offset from a VGPR, +5. Smaller: whole-wave reductions of compute / mesh programs in partial waves (VS / PS done), `image_sample_o` with an offset from a VGPR, smaller HLSL, further XGameRuntime APIs (XGameUI, XNetworking…), GameInput → system GameInput.dll, mapping physical pages at the game's address. diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs index cd0b61f..6600ea4 100644 --- a/crates/xcl/src/gpu/adapter.rs +++ b/crates/xcl/src/gpu/adapter.rs @@ -115,6 +115,20 @@ pub(crate) fn select_indices>(names: &[S], sel: &Selector) -> Vec< Vec::new() } +/// Microsoft's Basic Render Driver (vendor 0x1414, device 0x008C): the adapter Windows +/// provides when no GPU driver is installed. It has a D3D12 device, but no GPU behind it. +pub fn basic_render_driver(desc: &DXGI_ADAPTER_DESC1) -> bool { + desc.VendorId == 0x1414 && desc.DeviceId == 0x008c +} + +/// Whether the adapter is a software renderer: WARP (which DXGI flags as software) or the +/// Basic Render Driver (not flagged, so recognized by vendor and device id). A software +/// device runs kernels, but it does not have the hardware features the GPU tests check +/// (sparse reservations, mesh pipelines, a 4 GiB aperture). +pub fn software(desc: &DXGI_ADAPTER_DESC1) -> bool { + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 || basic_render_driver(desc) +} + /// The adapter's name from its description. pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String { let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); diff --git a/crates/xcl/src/gpu/adapter_tests.rs b/crates/xcl/src/gpu/adapter_tests.rs index 70fc209..b4c6ce4 100644 --- a/crates/xcl/src/gpu/adapter_tests.rs +++ b/crates/xcl/src/gpu/adapter_tests.rs @@ -1,4 +1,18 @@ use super::{select_indices, Selector}; +use windows::Win32::Graphics::Dxgi::*; + +#[test] +fn software_adapters_are_recognized() { + // the Basic Render Driver is not flagged software by DXGI, so its ids identify it + let basic = DXGI_ADAPTER_DESC1 { VendorId: 0x1414, DeviceId: 0x008c, ..Default::default() }; + assert!(super::basic_render_driver(&basic)); + assert!(super::software(&basic)); + let warp = DXGI_ADAPTER_DESC1 { Flags: DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32, ..Default::default() }; + assert!(super::software(&warp)); + let gpu = DXGI_ADAPTER_DESC1 { VendorId: 0x10de, DeviceId: 0x2684, ..Default::default() }; + assert!(!super::basic_render_driver(&gpu)); + assert!(!super::software(&gpu)); +} #[test] fn selector_parsing() { diff --git a/crates/xcl/src/gpu/recomp/aperture_tests.rs b/crates/xcl/src/gpu/recomp/aperture_tests.rs index 7a433e7..b2a6756 100644 --- a/crates/xcl/src/gpu/recomp/aperture_tests.rs +++ b/crates/xcl/src/gpu/recomp/aperture_tests.rs @@ -133,6 +133,11 @@ fn device() -> Option<(ID3D12Device, String)> { return None; } let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next()?; + if crate::gpu::adapter::software(&desc) { + // a software device cannot reserve sparse resources or map a 4 GiB aperture + super::runner::skip_test("no GPU"); + return None; + } let dev = crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_12_0).ok()?; Some((dev, crate::gpu::adapter::name(&desc))) } diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 1562c9a..91722c4 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -949,6 +949,15 @@ pub fn in_cached_only() -> bool { CACHED_ONLY.with(|c| c.get()) } +/// The cached-only attempt found work that must not run on the title's thread: a shader +/// that is not compiled yet, or the driver's compile of a pipeline. `cached_only`'s +/// second return becomes true. +pub fn defer_to_worker() { + if CACHED_ONLY.with(|c| c.get()) { + MISSED.with(|m| m.set(true)); + } +} + pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { compile_cached_in(&cache_dir(), src, entry, profile) } @@ -1067,6 +1076,13 @@ mod cache_tests { let (r, missed) = cached_only(|| request(|| panic!("a cached-only miss must not compile"))); assert!(r.is_err() && missed); + let (n, missed) = cached_only(|| { + defer_to_worker(); + 7 + }); + assert_eq!(n, 7); + assert!(missed); + assert!(!cached_only(|| 1).1); assert_eq!( counters.snapshot(), CacheStats { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 3b95148..e353c1f 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4,6 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::reductions::{Op as WaveOp, Reduction}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -53,6 +54,11 @@ pub(super) struct Em { /// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold /// where the program reads them (`upper_lanes`), used when the wave has 32 lanes pub upper: Option, + /// whole-wave reductions of a VS / PS recognised as a whole (`reductions`), by the pc of + /// their `v_cndmask`; the pcs of their other steps, emitted as nothing; the ops used + reductions: BTreeMap, + reduced: BTreeSet, + wave_ops: BTreeSet, /// pc of the instruction being emitted cur_pc: u64, /// MIMG instruction address → its sampler's S# when the code builds it from constants @@ -560,6 +566,9 @@ impl Em { loops: Vec::new(), cs_pad: false, upper: None, + reductions: BTreeMap::new(), + reduced: BTreeSet::new(), + wave_ops: BTreeSet::new(), cur_pc: 0, static_ss: BTreeMap::new(), static_used: Vec::new(), @@ -617,6 +626,12 @@ impl Em { std::mem::take(&mut self.out) } + /// Whole-wave reductions to emit as a whole (`reductions::find`). + pub fn set_reductions(&mut self, rs: Vec) { + self.reduced = rs.iter().flat_map(|r| r.rest.iter().copied()).collect(); + self.reductions = rs.into_iter().map(|r| (r.at, r)).collect(); + } + fn line(&mut self, s: &str) { for _ in 0..self.indent { self.out.push_str(" "); @@ -926,6 +941,42 @@ impl Em { } } + /// A whole-wave reduction recognised as a whole (`reductions`), from its `v_cndmask` to + /// its `v_readlane` of lane 0: the op over the mask's lanes of each 16-lane row of the + /// hardware wave (`xcl_wave_`), and from those what the steps leave – vB the other + /// row's of its half (`v_permlanex16`), vA the wave's (wave64: in lanes 0..31, the upper + /// half's in 32..63), sH the upper half's, sT the wave's. A wave64 program's hardware wave + /// is (the lower part of) its console wave; a wave32 program's 64-lane wave holds two + /// console waves, one per half (`xcl_half`). Every lane writes vA and vB, as under the + /// console's whole-wave EXEC. + fn reduction(&mut self, r: &Reduction) { + let x = self.code32(r.x, r.literal, false).unwrap_or_else(|| "0u".into()); + let m0 = self.sreg(r.mask); + let m1 = if r.wave64 { self.sreg(r.mask + 1) } else { "0u".into() }; + let t = self.t(); + self.line(&format!("uint4 {t} = xcl_wave_{}({x}, {m0}, {m1});", r.op.name())); + let row = |k: &str| format!("{t}.{k}"); + let (lower, upper) = (r.op.hlsl(&row("x"), &row("y")), r.op.hlsl(&row("z"), &row("w"))); + let (a, b) = (self.vreg(r.acc), self.vreg(r.other)); + let st = self.sreg(r.total); + self.line(&format!("{b} = {t}[(WaveGetLaneIndex() >> 4) ^ 1u];")); + match r.half { + Some(sh) => { + let sh = self.sreg(sh); + self.line(&format!("uint {t}_h = {upper};")); + self.line(&format!("uint {t}_w = {};", r.op.hlsl(&lower, &format!("{t}_h")))); + self.line(&format!("{a} = select(lane_id < 32u, {t}_w, {t}_h);")); + self.line(&format!("{sh} = {t}_h;")); + } + None => { + self.line(&format!("uint {t}_w = select(xcl_half != 0u, {upper}, {lower});")); + self.line(&format!("{a} = {t}_w;")); + } + } + self.line(&format!("{st} = {t}_w;")); + self.wave_ops.insert(r.op); + } + // ---------------------------------------------------------------- one instruction pub fn inst(&mut self, d: &Decoded, next: u64) -> Flow { @@ -933,6 +984,15 @@ impl Em { let text = rdna2::format(d); self.line(&format!("// {:04x}: {text}", d.pc)); self.cur_pc = d.pc; + // a whole-wave reduction recognised as a whole: emitted at its v_cndmask, its other + // steps as nothing + if let Some(r) = self.reductions.get(&d.pc).cloned() { + self.reduction(&r); + return Flow::Next; + } + if self.reduced.contains(&d.pc) { + return Flow::Next; + } // a far jump (`rdna2::resolve_far_jumps`) is an unconditional branch if let Some(t) = d.far_target { return Flow::Jump(t); @@ -4352,6 +4412,9 @@ impl Em { let _ = writeln!(h, "static uint xcl_sh{v}_{l} = 0u; // v_writelane slot: v{v} lane {l}"); } } + for op in &self.wave_ops { + h.push_str(&wave_reduction_fn(*op, matches!(self.opt.mode, Mode::Pixel(_)))); + } let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); h.push_str(PRELUDE_MEM); @@ -5434,6 +5497,38 @@ void st_bytes(uint a, uint4 r, uint n) { uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), c[(sel - 4u) & 3u])); } "#; +/// `xcl_wave_(x, m0, m1)` of a whole-wave reduction (`Em::reduction`): the op over the +/// lanes of the console wave's mask m0 / m1 – x there, the identity elsewhere – per 16-lane +/// row of the hardware wave (x: lanes 0..15 … w: 48..63). Wave operations leave out the lanes +/// the PC did not launch (never in the mask) and helper lanes: in a pixel shader each lane +/// first takes the op over its quad, through quad reads, which see helper lanes. +fn wave_reduction_fn(op: WaveOp, pixel: bool) -> String { + let (name, id) = (op.name(), hex(op.identity())); + let mut s = format!("// whole-wave v_{name} of the console (`reductions`): over the lanes of mask m0 / m1, per 16-lane row of the wave\nuint4 xcl_wave_{name}(uint x, uint m0, uint m1) {{\n"); + if pixel { + s.push_str(" // the quad first: quad reads see its helper lanes, wave operations do not\n uint b = lane_id & ~3u;\n"); + let _ = writeln!(s, " uint q = select(lanebit_at(m0, m1, b), QuadReadLaneAt(x, 0u), {id});"); + for k in 1..4 { + let _ = writeln!(s, " q = {};", op.hlsl("q", &format!("select(lanebit_at(m0, m1, b + {k}u), QuadReadLaneAt(x, {k}u), {id})"))); + } + } else { + let _ = writeln!(s, " uint q = select(lanebit_at(m0, m1, lane_id), x, {id});"); + } + let rows: Vec = (0..4).map(|k| format!("{}(select(r == {k}u, q, {id}))", op.wave())).collect(); + if pixel { + // wave operations leave helper lanes out (on the RTX 5070 Ti they return 0 there), but + // the console leaves the result in every lane, helpers included – and helpers feed the + // derivatives of what is computed from it: each lane takes its quad's live result + let _ = writeln!(s, " uint r = WaveGetLaneIndex() >> 4;\n uint4 t = uint4({});", rows.join(", ")); + let _ = writeln!(s, " uint4 h = IsHelperLane() ? (uint4){id} : t;"); + let c = op.hlsl(&op.hlsl("QuadReadLaneAt(h, 0u)", "QuadReadLaneAt(h, 1u)"), &op.hlsl("QuadReadLaneAt(h, 2u)", "QuadReadLaneAt(h, 3u)")); + let _ = writeln!(s, " return {c};\n}}"); + return s; + } + let _ = writeln!(s, " uint r = WaveGetLaneIndex() >> 4;\n return uint4({});\n}}", rows.join(", ")); + s +} + /// A console wave64 as two hardware wave32 halves of one thread group (docs/wave64-on-wave32.md): /// per-lane code is unchanged, and the halves meet ("exchange") wherever a value has to be /// the whole wave's – masks, lane reads, coherent scalar loads – so both hold the same SGPRs diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 6a864b8..c887ab9 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -59,6 +59,7 @@ pub mod mesh_wave; pub mod partial_waves; pub mod x64_masks; pub mod pso; +pub mod reductions; pub use emit::mesh_passthrough; pub mod runner; #[cfg(test)] @@ -1133,7 +1134,8 @@ pub fn wave_hazards(code: &[u8]) -> BTreeSet<&'static str> { wave_lane_reads(code).0 } -/// `wave_hazards` and the kinds of reads `upper_lanes` resolves. +/// `wave_hazards` and the kinds of reads `upper_lanes` resolves – reads inside a whole-wave +/// reduction recognised as a whole (`reductions`) count as that. pub fn wave_lane_reads(code: &[u8]) -> (BTreeSet<&'static str>, BTreeSet<&'static str>) { let mut insts = Vec::new(); let mut off = 0; @@ -1143,8 +1145,37 @@ pub fn wave_lane_reads(code: &[u8]) -> (BTreeSet<&'static str>, BTreeSet<&'stati insts.push(d); } rdna2::resolve_far_jumps(&mut insts); - let a = upper_lanes::analyze(&insts); - (a.hazards(&insts), a.resolved()) + let mut a = upper_lanes::analyze(&insts); + let rs = wave_reductions(&insts, true); + let reduced: BTreeSet = rs.iter().flat_map(|r| r.rest.iter().copied()).collect(); + a.reads.retain(|pc, _| !reduced.contains(pc)); + let mut resolved = a.resolved(); + if !rs.is_empty() { + resolved.insert("whole-wave min / max / or reduction (WaveActive*)"); + } + (a.hazards(&insts), resolved) +} + +/// The whole-wave reductions of a program of that wave size (`reductions`); +/// `XCL_NO_WAVE_REDUCTIONS=1`: none – each step translated on its own, as before (for +/// comparison). +fn wave_reductions(insts: &[Decoded], wave64: bool) -> Vec { + if std::env::var_os("XCL_NO_WAVE_REDUCTIONS").is_some() { + return Vec::new(); + } + reductions::find(insts, wave64) +} + +/// The reductions a translation emits as wave operations: those of VS / PS, whose hardware +/// wave holds (the lower part of) one wave64 console wave, or one or two wave32 console +/// waves (`xcl_half`). Compute-like modes keep the steps: there a wave64 console wave is two +/// hardware waves on GPUs with 32-lane waves (`x64`). +fn graphics_reductions(insts: &[Decoded], opt: &Options) -> Vec { + if matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_)) { + wave_reductions(insts, opt.wave64) + } else { + Vec::new() + } } /// Operations that cannot be split into two independent native wave32 halves while @@ -1407,15 +1438,19 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { PadWaves::WhereSeen => partial_waves::sees_lanes_not_launched(&insts, opt.wave64, threads % lanes).is_some(), }; } - // a wave64 VS / PS on a GPU that can run 32-lane waves: what lanes 32..63 hold where the + // a VS / PS: its whole-wave reductions as wave operations, at any wave size (`reductions`) + let reductions = graphics_reductions(&insts, opt); + let reduced: BTreeSet = reductions.iter().flat_map(|r| r.rest.iter().copied()).collect(); + // a wave64 VS / PS on a GPU with 32-lane waves only: what lanes 32..63 hold where the // program reads them (the driver may still pick 64 lanes: decided at run time); only a - // program with a read to change gets the form + // program with a read to change – outside the reductions – gets the form if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_)) { let a = upper_lanes::analyze(&insts); - if a.reads.values().any(|r| matches!(r, upper_lanes::Read::Const(_) | upper_lanes::Read::Shadow)) { + if a.reads.iter().any(|(pc, r)| !reduced.contains(pc) && matches!(r, upper_lanes::Read::Const(_) | upper_lanes::Read::Shadow)) { em.upper = Some(a); } } + em.set_reductions(reductions); em.max_vgpr = insts .iter() .flat_map(|d| { diff --git a/crates/xcl/src/gpu/recomp/reductions.rs b/crates/xcl/src/gpu/recomp/reductions.rs new file mode 100644 index 0000000..bd37bce --- /dev/null +++ b/crates/xcl/src/gpu/recomp/reductions.rs @@ -0,0 +1,544 @@ +//! Whole-wave reductions of vertex / pixel shaders, recognised as a whole +//! (docs/wave64-on-wave32.md, "Whole-wave reductions"). +//! +//! The console's compiler makes a wave reduction – `WaveActiveMin` / `Max` / `BitOr` of a +//! uint, as far as the retail pack shows – into whole-wave code. In a wave64 program: +//! +//! ```text +//! s_or_saveexec_b64 s[S:S+1], -1 EXEC saved, every lane on +//! s_and_b64 s[M:M+1], s[L:L+1], s[S:S+1] the lanes that take part (L: the live pixels); +//! without it the mask is the saved EXEC (M = S) +//! v_cndmask_b32 vA, id, x, s[M:M+1] x in those lanes, the op's identity elsewhere +//! op_dpp8 vA, vA, vA three times, over 8 lanes: the other lane of the +//! pair, a lane of the other pair, of the other quad +//! op_dpp vA, vA, vA row_mirror over the row (16 lanes) +//! v_permlanex16_b32 vB, vA, 0, 0 the other row of the 32-lane half +//! op vA, vB, vA over the half +//! v_readlane_b32 sH, vA, 32 the upper half's +//! op vA, sH, vA lanes 0..31: over the wave +//! v_readlane_b32 sT, vA, 0 the wave's +//! s_mov_b64 exec, s[S:S+1] +//! ``` +//! +//! A wave32 program has the same up to `op vA, vB, vA` (the wave, then), with the 32-bit +//! forms (`s_or_saveexec_b32`, `s_and_b32`, a mask in one SGPR), then `v_readlane_b32 sT, vA, +//! 0` and `s_mov_b32 exec_lo, sS`. The op is min_u32 (identity -1), max_u32 (0) or or_b32 (0); +//! `s_waitcnt` / `s_nop` / `v_nop` may stand anywhere between. +//! +//! On the console all lanes of the wave run it, inactive ones included. The PC runs only the +//! lanes it launched, and in a partial wave – a primitive's edge, the last vertices of a draw +//! – the DPP / `v_permlanex16` / `v_readlane` steps read lanes that do not exist: 0 on NVIDIA, +//! so a min gave 0 there. A wave64 program in 32-lane waves never has lanes 32..63. +//! +//! Lanes the PC did not launch hold the identity on the console: the mask is within the saved +//! EXEC, and EXEC outside whole-wave code holds only lanes the program was started with (as the +//! program uses it). So each value the sequence leaves is the op over the mask's lanes of a +//! part of the wave, which wave operations give at any wave size: per 16-lane row k, +//! `WaveActiveMin(row == k ? q : id)` with q the lane's x if it is in the mask, the identity +//! if not; the halves and the wave from the rows. Every register the steps write gets what the +//! console leaves there: vA the wave's result (wave64: in lanes 0..31, the upper half's in +//! 32..63), vB the other row's of its half, sH and sT. A wave operation leaves out helper +//! lanes, which a mask taken from EXEC after `s_wqm` holds: in a pixel shader q is first the op +//! over the lane's quad (quad reads see helper lanes), as in the console's 2 × 2 steps. +//! +//! Only an exactly matched sequence is replaced; the SALU instructions around it stay as they +//! are. The emitter (`Em::reduction`) uses this for VS / PS at any wave size, so it also +//! changes the HLSL GPUs with 64-lane waves get for those programs. + +use std::collections::BTreeSet; + +use super::emit::ext_encoding; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +/// The reduction's operation. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub enum Op { + MinU32, + MaxU32, + OrB32, +} + +impl Op { + fn of(name: &str) -> Option { + Some(match name { + "V_MIN_U32" => Op::MinU32, + "V_MAX_U32" => Op::MaxU32, + "V_OR_B32" => Op::OrB32, + _ => return None, + }) + } + + /// The value that leaves the other operand unchanged. + pub fn identity(self) -> u32 { + match self { + Op::MinU32 => u32::MAX, + Op::MaxU32 | Op::OrB32 => 0, + } + } + + pub fn name(self) -> &'static str { + match self { + Op::MinU32 => "min_u32", + Op::MaxU32 => "max_u32", + Op::OrB32 => "or_b32", + } + } + + /// The HLSL wave operation. + pub fn wave(self) -> &'static str { + match self { + Op::MinU32 => "WaveActiveMin", + Op::MaxU32 => "WaveActiveMax", + Op::OrB32 => "WaveActiveBitOr", + } + } + + /// `a op b` in HLSL. + pub fn hlsl(self, a: &str, b: &str) -> String { + match self { + Op::MinU32 => format!("min({a}, {b})"), + Op::MaxU32 => format!("max({a}, {b})"), + Op::OrB32 => format!("({a} | {b})"), + } + } + + /// The op on two values (tests, census). + pub fn apply(self, a: u32, b: u32) -> u32 { + match self { + Op::MinU32 => a.min(b), + Op::MaxU32 => a.max(b), + Op::OrB32 => a | b, + } + } +} + +/// A recognised reduction: what the emitter needs to replace it. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct Reduction { + pub op: Op, + /// the 64-bit forms (a wave64 program) + pub wave64: bool, + /// the `v_cndmask_b32`: the reduction is emitted there + pub at: u64, + /// the instructions after it, up to the last `v_readlane_b32`: emitted as nothing + pub rest: Vec, + /// x, the `v_cndmask`'s SRC1 (operand code: 256 + n for vN), and the instruction's literal + pub x: u64, + pub literal: Option, + /// the mask: its (first) SGPR + pub mask: u64, + /// vA (the steps' register), vB (`v_permlanex16`'s) + pub acc: u64, + pub other: u64, + /// sH (`v_readlane` 32, wave64 only), sT (`v_readlane` 0) + pub half: Option, + pub total: u64, +} + +/// No effect in the translation (`emit::NOOPS`): may stand anywhere in the sequence. +fn skipped(d: &Decoded) -> bool { + matches!(d.inst.name, "S_NOP" | "V_NOP") || d.inst.name.starts_with("S_WAITCNT") +} + +/// An integer constant source (inline or literal). +fn constant(code: u64, literal: Option) -> Option { + Some(match code { + 128..=192 => (code - 128) as u32, + 193..=208 => (-((code - 192) as i32)) as u32, + 255 => literal?, + _ => return None, + }) +} + +/// A mask register the translation names: an SGPR pair (s0..s105, VCC) for a wave64 +/// program, an SGPR (s0..s105, VCC's words) for a wave32 one. +fn mask_register(r: u64, wave64: bool) -> bool { + if wave64 { + r <= 104 || r == 106 + } else { + r <= 107 + } +} + +/// A single SGPR the translation names (s0..s105, VCC's words). +fn sgpr(r: u64) -> bool { + r <= 107 +} + +/// The next instruction from `insts[*j]` on that does something; `*j` past it. +fn next<'a>(insts: &'a [Decoded], j: &mut usize) -> Result<&'a Decoded, &'static str> { + while let Some(d) = insts.get(*j) { + *j += 1; + if !skipped(d) { + return Ok(d); + } + } + Err("the program ends") +} + +/// The whole-wave section that starts at `insts[i]` as a reduction, or why it is not one +/// this recognises. `targets`: every branch target of the program. +pub fn at(insts: &[Decoded], i: usize, targets: &BTreeSet) -> Result { + let fv = |d: &Decoded, f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let ext = |d: &Decoded, f: &str| ext_encoding(d).and_then(|e| rdna2::field_value(e, &d.words, f)).unwrap_or(0); + // a VOP3 instruction without source / output modifiers + let plain3 = |d: &Decoded| d.enc.name == "ENC_VOP3" && d.variant == Variant::Plain && ["ABS", "NEG", "CLAMP", "OMOD"].iter().all(|f| fv(d, f) == 0); + let d0 = insts.get(i).ok_or("no instruction")?; + let wave64 = match d0.inst.name { + "S_OR_SAVEEXEC_B64" if fv(d0, "SSRC0") == 193 => true, + "S_OR_SAVEEXEC_B32" if fv(d0, "SSRC0") == 193 => false, + _ => return Err("not s_or_saveexec s, -1"), + }; + let saved = fv(d0, "SDST"); + if !mask_register(saved, wave64) { + return Err("EXEC saved to an unusual register"); + } + let mut j = i + 1; + let mut step = || next(insts, &mut j); + let mut d = step()?; + let and = if wave64 { "S_AND_B64" } else { "S_AND_B32" }; + let mask = if d.inst.name == and { + if fv(d, "SSRC0") != saved && fv(d, "SSRC1") != saved { + return Err("s_and without the saved EXEC"); + } + let m = fv(d, "SDST"); + if !mask_register(m, wave64) { + return Err("the mask in an unusual register"); + } + d = step()?; + m + } else { + saved + }; + // x in the mask's lanes, a constant elsewhere + if d.inst.name != "V_CNDMASK_B32" || !plain3(d) || fv(d, "SRC2") != mask { + return Err("no v_cndmask_b32 of the mask"); + } + let id = constant(fv(d, "SRC0"), d.literal).ok_or("v_cndmask_b32: no constant outside the mask")?; + let x = fv(d, "SRC1"); + if !matches!(x, 0..=107 | 128..=208 | 240..=248 | 255 | 256..=511) { + return Err("v_cndmask_b32: an unusual source"); + } + let (acc, at, literal) = (fv(d, "VDST"), d.pc, d.literal); + // the row: DPP8 steps, then row_mirror. The op is idempotent, so each lane holds the op + // over the lanes it has read so far (bit l of `read[lane]`); every lane must end with its + // whole row – whichever DPP8 selects do it (the pack's read one lane of the other pair, + // then of the other quad, of lanes that hold the same by then). + let mut read: [u16; 16] = std::array::from_fn(|l| 1 << l); + let mut op = None; + let mut d = step()?; + while d.variant == Variant::Dpp8 { + let o = Op::of(d.inst.name).ok_or("the steps are not v_min_u32 / v_max_u32 / v_or_b32")?; + if *op.get_or_insert(o) != o { + return Err("steps of different ops"); + } + if d.enc.name != "ENC_VOP2" || fv(d, "VDST") != acc || ext(d, "VSRC0") != acc || fv(d, "VSRC1") != acc { + return Err("a DPP8 step of another register"); + } + // every lane is active: FI does not matter + let sel: [usize; 8] = std::array::from_fn(|k| ext(d, &format!("LANE_SEL_{k}")) as usize); + read = std::array::from_fn(|l| read[l] | read[(l & 8) | sel[l & 7]]); + d = step()?; + } + let op = op.ok_or("no DPP8 step after the v_cndmask_b32")?; + if id != op.identity() { + return Err("the constant outside the mask is not the op's identity"); + } + if Op::of(d.inst.name) != Some(op) || d.variant != Variant::Dpp16 || d.enc.name != "ENC_VOP2" { + return Err("no row_mirror step"); + } + let mods = ["SRC0_ABS", "SRC0_NEG", "SRC1_ABS", "SRC1_NEG"].iter().any(|f| ext(d, f) != 0); + if ext(d, "DPP_CTRL") != 0x140 || ext(d, "ROW_MASK") != 0xF || ext(d, "BANK_MASK") != 0xF || mods { + return Err("a DPP16 step other than row_mirror of all lanes"); + } + if fv(d, "VDST") != acc || ext(d, "VSRC0") != acc || fv(d, "VSRC1") != acc { + return Err("the row_mirror step of another register"); + } + read = std::array::from_fn(|l| read[l] | read[15 - l]); + if read.iter().any(|&r| r != 0xFFFF) { + return Err("the DPP8 steps and row_mirror leave out lanes of the row"); + } + // the other row of the half: every lane of it holds the row's value, so whichever lane + // the selects pick (and FI / bound_ctrl only matter for inactive lanes: none here) + let d = step()?; + if d.inst.name != "V_PERMLANEX16_B32" || !plain3(d) || fv(d, "SRC0") != 256 + acc || fv(d, "SRC1") >= 256 || fv(d, "SRC2") >= 256 { + return Err("no v_permlanex16_b32 of the row's value"); + } + let other = fv(d, "VDST"); + if other == acc { + return Err("v_permlanex16_b32 into the steps' register"); + } + // the half + let d = step()?; + let (s0, s1) = (fv(d, "SRC0"), fv(d, "VSRC1")); + if Op::of(d.inst.name) != Some(op) || d.enc.name != "ENC_VOP2" || d.variant != Variant::Plain || fv(d, "VDST") != acc || !((s0 == 256 + other && s1 == acc) || (s0 == 256 + acc && s1 == other)) { + return Err("no op of the two rows"); + } + // wave64: the upper half's, then the wave's in lanes 0..31 + let mut d = step()?; + let half = if wave64 { + if d.inst.name != "V_READLANE_B32" || !plain3(d) || fv(d, "SRC0") != 256 + acc || fv(d, "SRC1") != 128 + 32 || !sgpr(fv(d, "VDST")) { + return Err("no v_readlane_b32 of lane 32"); + } + let half = fv(d, "VDST"); + let d = step()?; + if Op::of(d.inst.name) != Some(op) || d.enc.name != "ENC_VOP2" || d.variant != Variant::Plain || fv(d, "VDST") != acc || fv(d, "SRC0") != half || fv(d, "VSRC1") != acc { + return Err("no op of the upper half's value"); + } + Some(half) + } else { + None + }; + if wave64 { + d = step()?; + } + if d.inst.name != "V_READLANE_B32" || !plain3(d) || fv(d, "SRC0") != 256 + acc || fv(d, "SRC1") != 128 || !sgpr(fv(d, "VDST")) { + return Err("no v_readlane_b32 of lane 0"); + } + let total = fv(d, "VDST"); + let last = d.pc; + let d = step()?; + let restore = if wave64 { "S_MOV_B64" } else { "S_MOV_B32" }; + if d.inst.name != restore || fv(d, "SDST") != 126 || fv(d, "SSRC0") != saved { + return Err("EXEC not restored after the v_readlane_b32 of lane 0"); + } + // entered only at the top: no branch lands after the s_or_saveexec + if targets.range(d0.pc + 1..=d.pc).next().is_some() { + return Err("a branch into the sequence"); + } + let rest = insts.iter().map(|d| d.pc).filter(|&pc| pc > at && pc <= last).collect(); + Ok(Reduction { op, wave64, at, rest, x, literal, mask, acc, other, half, total }) +} + +/// Every branch target of a program. +fn targets(insts: &[Decoded]) -> BTreeSet { + insts.iter().filter_map(rdna2::branch_target).collect() +} + +/// Every whole-wave section (`s_or_saveexec_b64` / `_b32` with -1) of a program: its pc, and +/// the reduction or why it is not one this recognises (the census). +pub fn survey(insts: &[Decoded]) -> Vec<(u64, Result)> { + let t = targets(insts); + insts + .iter() + .enumerate() + .filter(|(_, d)| matches!(d.inst.name, "S_OR_SAVEEXEC_B64" | "S_OR_SAVEEXEC_B32") && rdna2::field_value(d.enc, &d.words, "SSRC0") == Some(193)) + .map(|(i, d)| (d.pc, at(insts, i, &t))) + .collect() +} + +/// The reductions of a program (instructions in address order, far jumps resolved) in the +/// forms of its wave size. +pub fn find(insts: &[Decoded], wave64: bool) -> Vec { + survey(insts).into_iter().filter_map(|(_, r)| r.ok()).filter(|r| r.wave64 == wave64).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2::encode; + + const V: u64 = 256; + type F = Vec<(&'static str, u64)>; + type I = (&'static str, &'static str, F, Option); + + fn program(lines: &[I]) -> Vec { + let mut bytes: Vec = lines.iter().flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))).collect(); + bytes.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut out = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + rdna2::resolve_far_jumps(&mut out); + out + } + + fn i(n: &'static str, e: &'static str, f: &[(&'static str, u64)]) -> I { + (n, e, f.to_vec(), None) + } + + /// A DPP8 step of op on v6: lane l reads lane `sel[l]` of its 8. + fn dpp8(op: &'static str, sel: [u64; 8]) -> I { + let mut f = vec![("VDST", 6), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)]; + let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + f.extend(names.iter().copied().zip(sel)); + (op, "VOP2_VOP_DPP8", f, None) + } + + /// lane ^ k + fn xor(k: u64) -> [u64; 8] { + std::array::from_fn(|l| l as u64 ^ k) + } + + /// The pack's DPP8 steps: the other lane of the pair, a lane of the other pair, of the + /// other quad + const PACK: [[u64; 8]; 3] = [[1, 0, 3, 2, 5, 4, 7, 6], [2, 2, 0, 0, 6, 6, 4, 4], [4, 4, 4, 4, 0, 0, 0, 0]]; + + /// The pack's sequence: op (by name) over v55 in the lanes of s[18:19] & EXEC, identity + /// operand code `id`, the upper half's into s10 and the wave's into s61. + fn retail(op: &'static str, id: u64) -> Vec { + vec![ + i("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)]), + i("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)]), + i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", id), ("SRC1", V + 55), ("SRC2", 10)]), + dpp8(op, PACK[0]), + dpp8(op, PACK[1]), + dpp8(op, PACK[2]), + i(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]), + i("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)]), + i(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)]), + i(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", 10), ("VSRC1", 6)]), + i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 61), ("SRC0", V + 6), ("SRC1", 128)]), + i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]), + ] + } + + fn survey_of(lines: &[I]) -> Vec> { + survey(&program(lines)).into_iter().map(|(_, r)| r).collect() + } + + fn reason(lines: &[I]) -> &'static str { + let s = survey_of(lines); + assert_eq!(s.len(), 1); + s[0].clone().expect_err("recognised") + } + + #[test] + fn the_retail_sequences_are_recognised() { + for (op, id, want) in [("V_MIN_U32", 193, Op::MinU32), ("V_MAX_U32", 128, Op::MaxU32), ("V_OR_B32", 128, Op::OrB32)] { + let p = program(&retail(op, id)); + let r = find(&p, true); + assert_eq!(r.len(), 1, "{op}"); + let r = &r[0]; + assert_eq!((r.op, r.x, r.mask, r.acc, r.other, r.half, r.total), (want, V + 55, 10, 6, 7, Some(10), 61)); + // emitted at the v_cndmask, nothing for the steps up to the last v_readlane + assert_eq!(r.at, p[2].pc); + assert_eq!(r.rest, p[3..12].iter().map(|d| d.pc).collect::>()); + } + } + + #[test] + fn variants_of_the_pack() { + // the mask is the saved EXEC itself (16 sites in the pack) + let mut l = retail("V_OR_B32", 128); + l.remove(1); + l[1].2[3] = ("SRC2", 30); + let r = find(&program(&l), true); + assert_eq!(r.iter().map(|r| r.mask).collect::>(), [30]); + // s_waitcnt / v_nop between the steps; the saved EXEC as s_and_b64's first operand; + // the halves' op with its operands swapped; both v_readlane into one register + let mut l = retail("V_MAX_U32", 128); + l.insert(1, i("V_NOP", "ENC_VOP1", &[])); + l.insert(3, i("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0x3F70)])); + l[2] = i("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 30), ("SSRC1", 18)]); + l[10] = i("V_MAX_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 6), ("VSRC1", 7)]); + l[13].2[0] = ("VDST", 10); + let r = find(&program(&l), true); + assert_eq!(r.iter().map(|r| (r.op, r.half, r.total)).collect::>(), [(Op::MaxU32, Some(10), 10)]); + // other DPP8 steps that take in the 8 lanes: lane ^ 4, ^ 1, ^ 2; ^ 1, ^ 3, ^ 7; four + // steps, one of them reading the lane itself + for steps in [vec![xor(4), xor(1), xor(2)], vec![xor(1), xor(3), xor(7)], vec![xor(1), xor(0), xor(2), xor(4)]] { + let mut l = retail("V_MIN_U32", 193); + l.splice(3..6, steps.iter().map(|&sel| dpp8("V_MIN_U32", sel))); + assert_eq!(find(&program(&l), true).len(), 1, "{steps:?}"); + } + } + + #[test] + fn anything_else_is_left_alone() { + let base = retail("V_MIN_U32", 193); + let with = |k: usize, d: I| { + let mut l = base.clone(); + l[k] = d; + l + }; + let short = "the DPP8 steps and row_mirror leave out lanes of the row"; + // not the identity outside the mask: max's 0 for a min + assert_eq!(reason(&with(2, i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 128), ("SRC1", V + 55), ("SRC2", 10)]))), "the constant outside the mask is not the op's identity"); + // a mask not within the saved EXEC: lanes the PC did not launch could be in it + assert_eq!(reason(&with(1, i("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 20)]))), "s_and without the saved EXEC"); + // the v_cndmask selects by another register than the mask + assert_eq!(reason(&with(2, i("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 193), ("SRC1", V + 55), ("SRC2", 18)]))), "no v_cndmask_b32 of the mask"); + // a step of another op + assert_eq!(reason(&with(4, dpp8("V_MAX_U32", PACK[1]))), "steps of different ops"); + // steps that leave lanes out: the pack's in another order (they read one lane of a + // pair or quad, which holds the same as the other only after the steps before), the + // other lane of the pair twice, a rotation, two steps + let mut l = base.clone(); + l.swap(3, 5); + assert_eq!(reason(&l), short); + assert_eq!(reason(&with(4, dpp8("V_MIN_U32", PACK[0]))), short); + assert_eq!(reason(&with(4, dpp8("V_MIN_U32", [1, 2, 3, 4, 5, 6, 7, 0]))), short); + let mut l = base.clone(); + l.remove(5); + assert_eq!(reason(&l), short); + // no DPP8 step at all; a shift or a row mask instead of the whole mirror + let mut l = base.clone(); + l.drain(3..6); + assert_eq!(reason(&l), "no DPP8 step after the v_cndmask_b32"); + let shr = with(6, i("V_MIN_U32", "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)])); + assert_eq!(reason(&shr), "a DPP16 step other than row_mirror of all lanes"); + let rows = with(6, i("V_MIN_U32", "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0x5), ("BANK_MASK", 0xF)])); + assert_eq!(reason(&rows), "a DPP16 step other than row_mirror of all lanes"); + // v_permlane16 (same row) instead of v_permlanex16 + assert_eq!(reason(&with(7, i("V_PERMLANE16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)]))), "no v_permlanex16_b32 of the row's value"); + // another lane than 32, then than 0 + assert_eq!(reason(&with(9, i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 16)]))), "no v_readlane_b32 of lane 32"); + assert_eq!(reason(&with(11, i("V_READLANE_B32", "ENC_VOP3", &[("VDST", 61), ("SRC0", V + 6), ("SRC1", 128 + 1)]))), "no v_readlane_b32 of lane 0"); + // the halves' op reads another register than the readlane's + assert_eq!(reason(&with(10, i("V_MIN_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 11), ("VSRC1", 6)]))), "no op of the upper half's value"); + // something else under the whole wave before the restore + let mut l = base.clone(); + l.insert(12, i("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)])); + assert_eq!(reason(&l), "EXEC not restored after the v_readlane_b32 of lane 0"); + // a branch into the middle (to the third DPP8 step) + let mut l = vec![i("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 8)])]; + l.extend(base.iter().cloned()); + assert_eq!(reason(&l), "a branch into the sequence"); + // the branch to the s_or_saveexec itself is fine + let mut l = vec![i("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)])]; + l.extend(base.iter().cloned()); + assert_eq!(find(&program(&l), true).len(), 1); + // the 64-bit forms in a wave32 program (`find` by the program's wave size) + assert!(find(&program(&base), false).is_empty()); + } + + /// The pack's wave32 sequence: the 32-bit forms, no v_readlane of lane 32. + fn retail32(op: &'static str, id: u64) -> Vec { + let mut l = retail(op, id); + l[0] = i("S_OR_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)]); + l[1] = i("S_AND_B32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)]); + l.drain(9..11); + l[10] = i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]); + l + } + + #[test] + fn the_wave32_sequences_are_recognised() { + for (op, id, want) in [("V_MIN_U32", 193, Op::MinU32), ("V_MAX_U32", 128, Op::MaxU32), ("V_OR_B32", 128, Op::OrB32)] { + let p = program(&retail32(op, id)); + assert!(find(&p, true).is_empty(), "{op}: wave32 forms in a wave64 program"); + let r = find(&p, false); + assert_eq!(r.len(), 1, "{op}"); + let r = &r[0]; + assert_eq!((r.op, r.wave64, r.x, r.mask, r.acc, r.other, r.half, r.total), (want, false, V + 55, 10, 6, 7, None, 61)); + assert_eq!(r.rest, p[3..10].iter().map(|d| d.pc).collect::>()); + } + // the mask is the saved EXEC itself + let mut l = retail32("V_MIN_U32", 193); + l.remove(1); + l[1].2[3] = ("SRC2", 30); + assert_eq!(find(&program(&l), false).iter().map(|r| r.mask).collect::>(), [30]); + // a wave64 restore, a v_readlane of lane 32 (the upper half's: no such lane) + let mut l = retail32("V_MIN_U32", 193); + l[10] = i("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]); + assert_eq!(reason(&l), "EXEC not restored after the v_readlane_b32 of lane 0"); + let mut l = retail32("V_MIN_U32", 193); + l[9].2[2] = ("SRC1", 128 + 32); + assert_eq!(reason(&l), "no v_readlane_b32 of lane 0"); + } +} diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 7ebe475..bd738cb 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -60,6 +60,9 @@ struct Gpu { fence: ID3D12Fence, value: u64, adapter: String, + /// a software renderer (WARP or the Basic Render Driver): kernels run, but the tests + /// that need sparse reservations or a real mesh pipeline skip + software: bool, wave64: bool, /// 32-lane waves (`[WaveSize(32)]`: the split wave64 form; WARP has neither 32 nor 64) wave32: bool, @@ -122,14 +125,14 @@ fn init() -> Result { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(werr)?; // `XCL_ADAPTER` picks the adapter (default: the first in high-performance order) let sel = crate::gpu::adapter::Selector::from_env_or("auto"); - let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { - (factory.EnumWarpAdapter().map_err(werr)?, "WARP (software renderer)".into()) + let (adapter, name, software): (IDXGIAdapter1, String, bool) = if sel == crate::gpu::adapter::Selector::Warp { + (factory.EnumWarpAdapter().map_err(werr)?, "WARP (software renderer)".into(), true) } else { let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel) .into_iter() .next() .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; - (a, crate::gpu::adapter::name(&desc)) + (a, crate::gpu::adapter::name(&desc), crate::gpu::adapter::software(&desc)) }; let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(werr)?; let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 }; @@ -152,7 +155,7 @@ fn init() -> Result { dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(werr)?; let rs = root_signature(&dev, false)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(werr)?; - Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64, wave32, mesh }) + Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, software, wave64, wave32, mesh }) } } @@ -395,6 +398,12 @@ pub fn adapter() -> Result { with_gpu(|g| Ok(g.adapter.clone())) } +/// Whether a hardware GPU backs the device: false on WARP and on the Basic Render Driver, +/// which run kernels but have no sparse reservations, real mesh pipeline or 4 GiB aperture. +pub fn hardware_gpu() -> bool { + with_gpu(|g| Ok(!g.software)).unwrap_or(false) +} + pub fn wave64_supported() -> Result { with_gpu(|g| Ok(g.wave64)) } @@ -859,6 +868,19 @@ unsafe fn bind_views(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textu Ok(keep) } +/// The command queue and fence `draw_on_multi` submits with, for one device at a time. +struct DrawQueue { + dev: usize, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + value: u64, +} + +// D3D12 objects are free-threaded; access is serialised by the mutex. +unsafe impl Send for DrawQueue {} + +static DRAW_QUEUE: Mutex> = Mutex::new(None); + /// Several draws with one pipeline in one command list: each draw gets its own user data /// (u0 – e.g. a different descriptor table pointer) and scissor; textures and samplers in /// the directly indexed heaps (see `ViewTexture`). Otherwise as `draw_on`. @@ -877,9 +899,20 @@ pub fn draw_on_multi( clear: [f32; 4], ) -> Result, String> { unsafe { - let queue: ID3D12CommandQueue = - dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(werr)?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(werr)?; + // one queue and fence per device for all draws, not one per draw: once a test has + // brought up the D3D12.X backend (`hle::d3d12x::real::init`) its hooks are on the + // device this process gets for the adapter, and the queues made through them were + // not given back – a run with many draws ended in E_OUTOFMEMORY at CreateCommandQueue + let mut cached = DRAW_QUEUE.lock().unwrap(); + if cached.as_ref().is_none_or(|c| c.dev != dev.as_raw() as usize) { + let queue: ID3D12CommandQueue = + dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(werr)?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(werr)?; + *cached = Some(DrawQueue { dev: dev.as_raw() as usize, queue, fence, value: 0 }); + } + let dq = cached.as_mut().unwrap(); + dq.value += 1; + let (queue, fence, value) = (dq.queue.clone(), dq.fence.clone(), dq.value); let tex = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, @@ -982,7 +1015,7 @@ pub fn draw_on_multi( list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.Close().map_err(werr)?; queue.ExecuteCommandLists(&[Some(list.cast().map_err(werr)?)]); - wait_for_submission(dev, &queue, &fence, 1, "draw")?; + wait_for_submission(dev, &queue, &fence, value, "draw")?; let mut p = std::ptr::null_mut(); readback.Map(0, None, Some(&mut p)).map_err(werr)?; let pitch = layout_fp.Footprint.RowPitch as usize; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 7307c7d..e7c39d8 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2368,6 +2368,11 @@ fn draw_console(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]]) -> V draw_console_views(vs, ps, tris_px, &[], &[], &[]) } +/// `draw_console` with the programs translated as wave64 or wave32 programs. +fn draw_console_as(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]], wave64: bool) -> Vec<[f32; 4]> { + draw_console_views_as(vs, ps, tris_px, &[], &[], &[], wave64) +} + /// `draw_console` with initial SGPRs and textures / samplers (see `runner::ViewTexture`). fn draw_console_views( vs: Option<&[u8]>, @@ -2376,6 +2381,20 @@ fn draw_console_views( sgprs: &[u32], textures: &[runner::ViewTexture], samplers: &[windows::Win32::Graphics::Direct3D12::D3D12_SAMPLER_DESC], +) -> Vec<[f32; 4]> { + draw_console_views_as(vs, ps, tris_px, sgprs, textures, samplers, true) +} + +/// `draw_console_views` with the programs translated for a stated wave size. +#[allow(clippy::too_many_arguments)] +fn draw_console_views_as( + vs: Option<&[u8]>, + ps: Option<&[u8]>, + tris_px: &[[f32; 2]], + sgprs: &[u32], + textures: &[runner::ViewTexture], + samplers: &[windows::Win32::Graphics::Direct3D12::D3D12_SAMPLER_DESC], + wave64: bool, ) -> Vec<[f32; 4]> { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; let pass_vs = prog(&[ @@ -2398,7 +2417,7 @@ fn draw_console_views( ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None), ]); let compile = |code: &[u8], mode: Mode, profile: &str| { - let t = translate(code, &runner::options(mode)).unwrap(); + let t = translate(code, &Options { wave64, ..runner::options(mode) }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); super::dxc::compile(&t.hlsl, "main", profile, &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)) }; @@ -2645,44 +2664,62 @@ fn spill_slots(slot: fn(u32) -> u32) -> Vec { code } -/// The whole-wave reduction of the retail pixel shaders (`upper_lanes`), run as a wave64 PS: -/// identity into the lanes outside the mask, DPP8 xor 1 / 2 / 4, row_mirror, the other row -/// through `v_permlanex16`, `v_readlane` 32 for the upper half's result, `v_readlane` 0 for -/// the total – as min (identity -1, as in the pack) and as a sum (identity 0: wrong if lane -/// 32 is read as anything but the identity, e.g. as lane 0, where a 32-lane GPU's wave read -/// wraps). Over the odd pixels of each wave; also the waterfall read of the pack -/// (`v_readlane` of the lane `s_ff1` picks from mask & EXEC). The waves are found from the -/// pixels: each exports its wave's `v_readfirstlane` of the pixel number and its lane -/// (`v_mbcnt`), and the CPU computes what a console wave of those lanes gives. +/// The whole-wave reduction of the retail pixel shaders as the console's compiler emits it +/// (`reductions`): EXEC saved in s[30:31]; `op` over vX in the lanes of the saved EXEC – and of +/// s[and_with:+1], given – with `identity` elsewhere (v_cndmask), three DPP8 steps (the other +/// lane of the pair, a lane of the other pair, of the other quad: the pack's selects), +/// row_mirror, the other row through `v_permlanex16` (v7), `v_readlane` 32 for the upper +/// half's (s[half]), `v_readlane` 0 for the wave's (s[total]); v6 the steps' register. +fn whole_wave_reduction(op: &str, identity: u64, x: u64, and_with: Option, half: u64, total: u64) -> Vec { + whole_wave_reduction_as(true, op, identity, x, and_with, half, total) +} + +/// `whole_wave_reduction` in a wave64 program, or in a wave32 one: the 32-bit forms, no +/// upper half (s30 the saved EXEC, s[and_with] the mask, `half` unused). +fn whole_wave_reduction_as(wave64: bool, op: &str, identity: u64, x: u64, and_with: Option, half: u64, total: u64) -> Vec { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + let mut c = vec![ins(w("S_OR_SAVEEXEC_B64", "S_OR_SAVEEXEC_B32"), "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None)]; + if let Some(s) = and_with { + c.push(ins(w("S_AND_B64", "S_AND_B32"), "ENC_SOP2", &[("SDST", 10), ("SSRC0", s), ("SSRC1", 30)], None)); + } + let mask = if and_with.is_some() { 10 } else { 30 }; + c.push(ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", identity), ("SRC1", V + x), ("SRC2", mask)], None)); + let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; + for sel in [[1u64, 0, 3, 2, 5, 4, 7, 6], [2, 2, 0, 0, 6, 6, 4, 4], [4, 4, 4, 4, 0, 0, 0, 0]] { + let mut f = vec![("VDST", 6u64), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)]; + f.extend(names.iter().copied().zip(sel)); + c.push(ins(op, "VOP2_VOP_DPP8", &f, None)); + } + c.extend([ + ins(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None), + ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None), + ]); + if wave64 { + c.push(ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", half), ("SRC0", V + 6), ("SRC1", 128 + 32)], None)); + c.push(ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", half), ("VSRC1", 6)], None)); + } + c.push(ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", total), ("SRC0", V + 6), ("SRC1", 128)], None)); + c.push(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None)); + c.concat() +} + +/// The whole-wave reduction of the retail pixel shaders (`whole_wave_reduction`), run as a +/// wave64 PS in full waves – as min (identity -1, as in the pack: replaced with wave +/// operations, `reductions`) and as a sum (identity 0: its steps stay, and lane 32 is read as +/// the identity in a 32-lane wave, `upper_lanes`; wrong if it were read as anything else, e.g. +/// as lane 0, where a 32-lane GPU's wave read wraps). Over the odd pixels of each wave; also +/// the waterfall read of the pack (`v_readlane` of the lane `s_ff1` picks from mask & EXEC). +/// The waves are found from the pixels: each exports its wave's `v_readfirstlane` of the pixel +/// number and its lane (`v_mbcnt`), and the CPU computes what a console wave of those lanes +/// gives. #[test] fn gpu_wave64_ps_whole_wave_reductions() { use std::collections::{BTreeMap, BTreeSet}; if !gpu_ready() { return; } - let reduce = |op: &str, identity: u64, out: u64| -> Vec { - let mut c = vec![ - ins("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)], None), - ins("S_AND_B64", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 18), ("SSRC1", 30)], None), - ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", identity), ("SRC1", V + 13), ("SRC2", 10)], None), - ]; - let names = ["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"]; - for sel in [[1u64, 0, 3, 2, 5, 4, 7, 6], [2, 3, 0, 1, 6, 7, 4, 5], [4, 5, 6, 7, 0, 1, 2, 3]] { - let mut f = vec![("VDST", 6u64), ("SRC0", 0xE9), ("VSRC0", 6), ("VSRC1", 6)]; - f.extend(names.iter().copied().zip(sel)); - c.push(ins(op, "VOP2_VOP_DPP8", &f, None)); - } - c.extend([ - ins(op, "VOP2_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 6), ("VSRC1", 6), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), - ins("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 6), ("SRC1", 128), ("SRC2", 128)], None), - ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 7), ("VSRC1", 6)], None), - ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)], None), - ins(op, "ENC_VOP2", &[("VDST", 6), ("SRC0", 10), ("VSRC1", 6)], None), - ins("V_READLANE_B32", "ENC_VOP3", &[("VDST", out), ("SRC0", V + 6), ("SRC1", 128)], None), - ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None), - ]); - c.concat() - }; + let reduce = |op: &str, identity: u64, out: u64| whole_wave_reduction(op, identity, 13, Some(18), 10, out); let code = program_of(&[ // v12 = pixel number y·16 + x, v13 = v12 + 1, s[18:19] = the odd pixels ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None), @@ -2975,6 +3012,227 @@ fn gpu_ps_helper_lanes_see_ballots_and_quads_are_lanes_4k() { assert_eq!(quads, px.len(), "quads not at hardware lanes 4k..4k+3"); } +/// The three reductions of the pack (`reductions`): instruction, identity operand code, op. +const WAVE_REDUCTIONS: [(&str, u64, super::reductions::Op); 3] = [ + ("V_MIN_U32", 193, super::reductions::Op::MinU32), + ("V_MAX_U32", 128, super::reductions::Op::MaxU32), + ("V_OR_B32", 128, super::reductions::Op::OrB32), +]; + +/// The translation of recognised reductions (`reductions`, `Em::reduction`) in every VS / PS +/// form: wave operations instead of the steps (no lane read left), quad reads in a pixel +/// shader only, the halves of a 64-lane wave for wave32 programs, the same HLSL whether or not +/// the GPU has 64-lane waves (`split_wave64`); it compiles (DXC, where there is one). +#[test] +fn whole_wave_reductions_translate_to_wave_operations() { + for wave64 in [true, false] { + for pixel in [true, false] { + let mut parts: Vec> = WAVE_REDUCTIONS.iter().map(|(op, id, _)| whole_wave_reduction_as(wave64, op, *id, 13, Some(18), 40, 41)).collect(); + let (mode, profile) = if pixel { + parts.push(ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 6), ("VSRC1", 7), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + (Mode::Pixel(draw_psi()), "ps_6_6") + } else { + parts.push(ins("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 6), ("VSRC1", 7), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1)], None)); + parts.push(ins("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 6), ("VSRC1", 7), ("VSRC2", 6), ("VSRC3", 7)], None)); + (Mode::Vertex(draw_vsi()), "vs_6_6") + }; + let code = program_of(&parts); + let what = format!("wave64 {wave64}, {profile}"); + let native = translate(&code, &Options { mode: mode.clone(), wave64, ..Default::default() }).unwrap(); + let split = translate(&code, &Options { mode, wave64, split_wave64: true, ..Default::default() }).unwrap(); + assert!(native.complete(), "{what}: {:?}", native.unsupported_why); + let h = &native.hlsl; + assert_eq!(h, &split.hlsl, "{what}: one form at every wave size"); + for op in ["min_u32", "max_u32", "or_b32"] { + assert_eq!(h.matches(&format!("xcl_wave_{op}(")).count(), 2, "{what}: the function and its call\n{h}"); + } + assert!(!h.contains(" = rla("), "{what}: a lane read left\n{h}"); + assert_eq!(h.contains("QuadReadLaneAt(x, 3u)"), pixel, "{what}: quad reads\n{h}"); + assert_eq!(h.contains("select(xcl_half != 0u, "), !wave64, "{what}: the halves\n{h}"); + if super::dxc::location().is_ok() { + super::dxc::compile(h, "main", profile, &[]).unwrap_or_else(|e| panic!("{what}: {e}\n{h}")); + } + } + } +} + +/// Whole-wave reductions (`reductions`) in full and partial pixel waves, of wave64 and of wave32 +/// programs: the pack's min, max and or of pixel number + 1, over the odd pixels (`s_and` of +/// the saved EXEC with the live pixels' mask, as in the pack) and over every lane of the wave's +/// quads (the saved EXEC after `s_wqm`, helper lanes included), drawn as the whole target, a +/// 3-quad triangle and a 55-pixel one. A pixel exports its console wave and lane and one of the +/// results for each op – the wave's (sT), the upper half's (sH, wave64), what the steps leave in +/// its lane (vA, vB) – which the CPU computes from the console wave's lanes, as on a console +/// wave whose other lanes are not populated. Each step translated on its own (before, +/// `XCL_NO_WAVE_REDUCTIONS=1`) reads the lanes the PC did not launch: 0 on NVIDIA, so the min +/// of a partial wave was 0 – and the or over the quads' lanes of 3 quads missed helper pixels. +#[test] +fn gpu_ps_partial_wave_reductions() { + use std::collections::BTreeMap; + if !gpu_ready() { + return; + } + const RESULTS: [&str; 4] = ["sT", "sH", "vA", "vB"]; + // `view`: which result a pixel exports (RESULTS) + let program = |wave64: bool, wqm: bool, view: usize| -> Vec { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + let pixel = [ + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None), + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None), + ]; + // v12 = pixel number y·16 + x; the console wave: its first lane's pixel number (s62), + // the lane (v15) + let mut c = pixel.to_vec(); + c.extend([ + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 12)], None), + ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", 128)], None), + ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", V + 15)], None), + ]); + if wqm { + // live pixels in s[16:17], then the whole quads: the helper lanes' pixel numbers too + c.push(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 16), ("SSRC0", 126)], None)); + c.push(ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None)); + c.extend(pixel.iter().cloned()); + } + // v13 = pixel number + 1, s[18:19] = the odd pixels + c.extend([ + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None), + ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 129), ("VSRC1", 12)], None), + ins("V_CMP_NE_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 14)], None), + ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 18), ("SSRC0", 106)], None), + ]); + // op k: sH in s[40 + 2k], sT in s[41 + 2k], vA / vB copied to v[20 + 2k] / v[21 + 2k] + for (k, (op, id, _)) in WAVE_REDUCTIONS.iter().enumerate() { + let k = k as u64; + c.push(whole_wave_reduction_as(wave64, op, *id, 13, (!wqm).then_some(18), 40 + 2 * k, 41 + 2 * k)); + c.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 20 + 2 * k), ("SRC0", V + 6)], None)); + c.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 21 + 2 * k), ("SRC0", V + 7)], None)); + } + if wqm { + c.push(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 16)], None)); + } + for k in 0..3u64 { + let src = [41 + 2 * k, 40 + 2 * k, V + 20 + 2 * k, V + 21 + 2 * k][view]; + c.push(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 30 + k), ("SRC0", src)], None)); + } + c.extend([ + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 33), ("SRC0", 62), ("SRC1", 128 + 6), ("SRC2", V + 15)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 33), ("SRC0", V + 33)], None), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 30), ("VSRC1", 31), ("VSRC2", 32), ("VSRC3", 33), ("DONE", 1), ("VM", 1)], None), + ]); + program_of(&c) + }; + let shapes: [(&str, [[f32; 2]; 3]); 3] = [ + ("whole target", [[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]]), + ("3 quads", [[0.0, 0.0], [3.2, 0.0], [0.0, 3.2]]), + ("55 pixels", [[0.0, 0.0], [11.0, 0.0], [0.0, 11.0]]), + ]; + let mut wave_sizes = BTreeMap::new(); + // wave size, shape, mask, op, result → (pixels wrong, the first: pixel, lane, got, want) + let mut wrong: BTreeMap = BTreeMap::new(); + for wave64 in [true, false] { + let size = if wave64 { "wave64" } else { "wave32" }; + for (shape, tri) in &shapes { + for wqm in [false, true] { + let mask = if wqm { "the quads' lanes" } else { "the odd pixels" }; + for (view, what) in RESULTS.iter().enumerate() { + if view == 1 && !wave64 { + continue; + } + let px = draw_console_as(None, Some(&program(wave64, wqm, view)), tri, wave64); + // by console wave (its first lane's pixel number): (pixel number, lane, results) + let mut waves: BTreeMap> = BTreeMap::new(); + for (id, p) in px.iter().enumerate().filter(|(_, p)| p[3] >= 0.0) { + let kl = p[3] as u32; + waves.entry(kl >> 6).or_default().push((id as u32, kl & 63, *p)); + } + assert!(!waves.is_empty(), "{size}, {shape}: nothing drawn"); + if view == 0 { + wave_sizes.insert((size, *shape, wqm), waves.values().map(|w| w.len()).collect::>()); + } + for (first, w) in &waves { + // the lanes in the mask: (row = lane / 16, value) + let lanes: Vec<(u32, u32)> = if wqm { + // every lane of a quad with a live pixel; a quad keeps to one row + let quads: BTreeMap<(u32, u32), u32> = w.iter().map(|(id, lane, _)| ((id % 16 / 2, id / 16 / 2), lane >> 4)).collect(); + quads.iter().flat_map(|(&(qx, qy), &row)| [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(dx, dy)| (row, (2 * qy + dy) * 16 + 2 * qx + dx + 1))).collect() + } else { + w.iter().filter(|x| x.0 % 2 == 1).map(|(id, lane, _)| (lane >> 4, id + 1)).collect() + }; + for (o, (_, _, op)) in WAVE_REDUCTIONS.iter().enumerate() { + let rows: [u32; 4] = std::array::from_fn(|k| lanes.iter().filter(|l| l.0 == k as u32).fold(op.identity(), |a, l| op.apply(a, l.1))); + let half = op.apply(rows[2], rows[3]); + let wave = op.apply(op.apply(rows[0], rows[1]), half); + for (id, lane, p) in w { + let want = match view { + 0 => wave, + 1 => half, + 2 if *lane < 32 => wave, + 2 => half, + _ => rows[((lane >> 4) ^ 1) as usize], + }; + // u32 → f32 → u32: exact below 2^24; the identity -1 saturates back + let got = p[o] as u32; + if got != want { + let k = format!("{size}, {shape}, over {mask}: {} {what} (wave of pixel {first})", op.name()); + wrong.entry(k).or_insert((0, (*id, *lane, got, want))).0 += 1; + } + } + } + } + } + } + } + } + println!("pixels per console wave: {wave_sizes:?}"); + for (k, (n, (id, lane, got, want))) in &wrong { + println!("{k}: {n} pixels wrong, e.g. pixel {id} (lane {lane}): {got:#x}, want {want:#x}"); + } + assert!(wrong.is_empty(), "{} results wrong", wrong.len()); +} + +/// Whole-wave reductions (`reductions`) in a vertex wave of three lanes, of a wave64 and of a +/// wave32 program: min, max and or of vertex id + 1 over the saved EXEC, exported as param0 with +/// what v_permlanex16 leaves for the min (vB: the other row's – no lane there, so the +/// identity). The same at every vertex, so the interpolated value is exact. Before +/// (`XCL_NO_WAVE_REDUCTIONS=1`) the min and vB read lanes the PC did not launch: 0 on NVIDIA. +#[test] +fn gpu_vs_partial_wave_reductions() { + if !gpu_ready() { + return; + } + for wave64 in [true, false] { + // v13 = vertex id + 1 (the id is in v0), then the position and the reductions + let mut c = vec![ + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 0)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None), + ]; + for (k, (op, id, _)) in WAVE_REDUCTIONS.iter().enumerate() { + c.push(whole_wave_reduction_as(wave64, op, *id, 13, None, 40 + 2 * k as u64, 41 + 2 * k as u64)); + if k == 0 { + c.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 21), ("SRC0", V + 7)], None)); + } + } + c.extend([ + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 41)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 43)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 45)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 21)], None), + ins("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ins("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None), + ]); + let px = draw_console_as(Some(&program_of(&c)), None, &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]], wave64); + println!("wave64 {wave64}: {:?}", px[0]); + for (i, p) in px.iter().enumerate() { + assert_eq!(p.map(|x| x as u32), [1, 3, 3, u32::MAX], "wave64 {wave64}, pixel {i}: min, max, or of vertex id + 1, vB of the min"); + } + } +} + /// XCL image descriptor (T#, GFX10 layout): BASE_ADDRESS = SRV heap index, FORMAT, TYPE. fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] { [index, format << 20, 0, ty << 28, 0, 0, 0, 0] @@ -6143,10 +6401,12 @@ fn retail_wave64_graphics_lane_census() { } /// The 32-lane form of the pack's wave64 VS / PS (`upper_lanes`): every program whose -/// translation it changes is compiled with DXC. Digests of every program's translation in the -/// native form (`split_wave64` off – the form a GPU with 64-lane waves gets) and of the other -/// modes' 32-lane form are printed, to compare with another build: `XCL_SAMPLE_RPF`; -/// `XCL_FORMS_NO_DXC=1` skips the compiles. +/// translation it changes is compiled with DXC, and so is the native form of every VS / PS +/// with a whole-wave reduction recognised as a whole (`reductions`: it changes the form of +/// every GPU). Digests of every program's translation in the native form (`split_wave64` off +/// – the form a GPU with 64-lane waves gets) and of the other modes' 32-lane form are printed, +/// to compare with another build: `XCL_SAMPLE_RPF`; `XCL_FORMS_NO_DXC=1` skips the compiles; +/// `XCL_FORMS_LIST=`: each program's digests, one line each (to diff two builds). #[test] #[ignore] fn retail_wave64_graphics_lane_forms() { @@ -6154,10 +6414,14 @@ fn retail_wave64_graphics_lane_forms() { use std::sync::Mutex; let Ok(path) = std::env::var("XCL_SAMPLE_RPF") else { return }; let dxc = std::env::var_os("XCL_FORMS_NO_DXC").is_none(); + let list_out = std::env::var("XCL_FORMS_LIST").ok(); let data = std::fs::read(path).unwrap(); let records = crate::gpu::pack::scan(&data, 0x40); let (digest, programs, changed, compiled) = (AtomicU64::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let split_digest = AtomicU64::new(0); + // VS / PS with a recognised reduction, wave64 / wave32; their native forms compiled + let (reduced64, reduced32, reduced_compiled) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let list: Mutex> = Mutex::new(Vec::new()); let errors: Mutex> = Mutex::new(Vec::new()); let next = AtomicUsize::new(0); std::thread::scope(|s| { @@ -6184,16 +6448,41 @@ fn retail_wave64_graphics_lane_forms() { Mode::Pixel(_) => "ps_6_6", _ => { // the other modes' 32-lane form: unchanged by `upper_lanes` + let mut sh = 0; if let Ok(t) = translate(code, &Options { split_wave64: true, ..opt }) { - split_digest.fetch_add(crate::gpu::shader::fnv64(format!("{key}\\n{}", t.hlsl).as_bytes()), Ordering::Relaxed); + sh = crate::gpu::shader::fnv64(format!("{key}\\n{}", t.hlsl).as_bytes()); + split_digest.fetch_add(sh, Ordering::Relaxed); + } + if list_out.is_some() { + list.lock().unwrap().push(format!("{key}\t{h:016x}\t{sh:016x}\t-")); } continue; } }; + // (the list's last column: whether the program has one) + let reduced = native.hlsl.contains("uint4 xcl_wave_"); + if reduced { + if wave64 { &reduced64 } else { &reduced32 }.fetch_add(1, Ordering::Relaxed); + if dxc { + match super::dxc::compile(&native.hlsl, "main", profile, &[]) { + Ok(_) => { + reduced_compiled.fetch_add(1, Ordering::Relaxed); + } + Err(e) => errors.lock().unwrap().push(format!("{key} (native): {}", e.lines().take(4).collect::>().join(" | "))), + } + } + } if !wave64 { + if list_out.is_some() { + list.lock().unwrap().push(format!("{key}\t{h:016x}\t-\t{reduced}")); + } continue; } let t = translate(code, &Options { split_wave64: true, ..opt }).unwrap(); + if list_out.is_some() { + let sh = crate::gpu::shader::fnv64(format!("{key}\n{}", t.hlsl).as_bytes()); + list.lock().unwrap().push(format!("{key}\t{h:016x}\t{sh:016x}\t{reduced}")); + } if t.hlsl == native.hlsl { continue; } @@ -6213,20 +6502,134 @@ fn retail_wave64_graphics_lane_forms() { }); let errors = errors.into_inner().unwrap(); println!( - "{} programs, native-form digest {:016x}, 32-lane-form digest of the other modes {:016x}; 32-lane form differs for {} wave64 VS / PS, {} compiled, {} DXC errors", + "{} programs, native-form digest {:016x}, 32-lane-form digest of the other modes {:016x}; 32-lane form differs for {} wave64 VS / PS, {} compiled; whole-wave reductions as wave operations in {} wave64 and {} wave32 VS / PS, native form {} compiled; {} DXC errors", programs.into_inner(), digest.into_inner(), split_digest.into_inner(), changed.into_inner(), compiled.into_inner(), + reduced64.into_inner(), + reduced32.into_inner(), + reduced_compiled.into_inner(), errors.len() ); + if let Some(out) = list_out { + let mut v = list.into_inner().unwrap(); + v.sort(); + std::fs::write(out, v.join("\n") + "\n").unwrap(); + } for e in errors.iter().take(10) { println!(" {e}"); } assert!(errors.is_empty()); } +/// The pack's whole-wave sections (`s_or_saveexec_b64` / `_b32` with -1) and the reductions +/// `reductions` recognises in them: sites, programs and distinct programs (by code) per op, +/// and per reason for the sections it leaves – for wave64 VS / PS, where the translation uses +/// them, and for the other modes and wave sizes, where it does not. For wave64 VS / PS also the +/// programs with a lane ≥ 32 read as a constant (`upper_lanes`, #133), those whose such reads +/// are all inside recognised reductions, and those that still get the 32-lane form. +/// `XCL_SAMPLE_RPF`; `XCL_CENSUS_OUT=`: the sections left, with their instructions. +#[test] +#[ignore] +fn retail_wave_reductions_census() { + use super::upper_lanes::Read; + use std::collections::{BTreeMap, BTreeSet}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + let Ok(path) = std::env::var("XCL_SAMPLE_RPF") else { return }; + let out = std::env::var("XCL_CENSUS_OUT").ok(); + let data = std::fs::read(path).unwrap(); + let records = crate::gpu::pack::scan(&data, 0x40); + // (programs, kind) → (sites, programs, distinct programs by code hash) + type Stats = BTreeMap<(String, String), (usize, usize, BTreeSet)>; + let stats: Mutex = Mutex::new(BTreeMap::new()); + let left: Mutex> = Mutex::new(Vec::new()); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(r) = records.get(i) else { break }; + let Some(blob) = crate::gpu::pack::inflate(&data, r) else { continue }; + let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue }; + for (fi, f) in sh.fssm.iter().enumerate() { + let label = match super::interface(&blob, &sh, f) { + Some(Mode::Vertex(_)) => "VS", + Some(Mode::Pixel(_)) => "PS", + Some(Mode::Compute(_)) => "CS", + Some(Mode::Mesh(_)) => "MS", + Some(Mode::Geometry(_)) => "GS", + _ => "other", + }; + for p in &f.programs { + let code = &f.data[p.offset..p.offset + p.len]; + let mut insts = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + let Ok(d) = crate::gpu::rdna2::decode(&code[off..], off as u64) else { break }; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + let sections = super::reductions::survey(&insts); + if sections.is_empty() { + continue; + } + let wave64 = super::detect_wave64(code); + let group = format!("{label} {}", if wave64 { "wave64" } else { "wave32" }); + let hash = crate::gpu::shader::fnv64(code); + let mut kinds = BTreeSet::from(["(programs with a whole-wave section)".to_string()]); + let mut st = stats.lock().unwrap(); + for (pc, res) in §ions { + let kind = match res { + Ok(r) => format!("recognised: {}", r.op.name()), + Err(e) => format!("left: {e}"), + }; + st.entry((group.clone(), kind.clone())).or_default().0 += 1; + if let (Err(e), Some(_)) = (res, &out) { + let lines = crate::gpu::rdna2::disassemble(code, 0, false); + let k = lines.iter().position(|l| l.pc == *pc).unwrap_or(0); + let text: Vec = lines[k..(k + 16).min(lines.len())].iter().map(|l| format!(" {:05x}: {}", l.pc, l.text)).collect(); + left.lock().unwrap().push(format!("=== {group} {} FSSM#{fi} {hash:016x}: {e}\n{}\n", r.name, text.join("\n"))); + } + kinds.insert(kind); + } + if wave64 && matches!(label, "VS" | "PS") { + let a = super::upper_lanes::analyze(&insts); + let reduced: BTreeSet = sections.iter().filter_map(|(_, r)| r.as_ref().ok()).flat_map(|r| r.rest.iter().copied()).collect(); + let consts: Vec = a.reads.iter().filter(|(_, r)| matches!(r, Read::Const(_))).map(|(pc, _)| *pc).collect(); + if !consts.is_empty() { + kinds.insert("(programs with a lane >= 32 read as a constant, #133)".into()); + if consts.iter().all(|pc| reduced.contains(pc)) { + kinds.insert("(... all inside recognised reductions)".into()); + } + } + if a.reads.iter().any(|(pc, r)| !reduced.contains(pc) && matches!(r, Read::Const(_) | Read::Shadow)) { + kinds.insert("(programs that still get the 32-lane form)".into()); + } + } + for k in kinds { + let e = st.entry((group.clone(), k)).or_default(); + e.1 += 1; + e.2.insert(hash); + } + } + } + }); + } + }); + for ((group, kind), (sites, programs, distinct)) in stats.into_inner().unwrap() { + println!(" {group:<11} {kind:<62} {sites:>6} sites {programs:>6} programs {:>6} distinct", distinct.len()); + } + if let Some(out) = out { + let mut v = left.into_inner().unwrap(); + v.sort(); + std::fs::write(out, v.concat()).unwrap(); + } +} + /// `ds_swizzle_b32`'s four modes against the RDNA ISA (its FFT examples, rotate, quad /// permute, and the bit mode with xor ≥ 16, which retail compute shaders use to swap the /// 16-lane halves: 0x401F). @@ -8466,3 +8869,215 @@ fn dxc_bench_folder() { println!(" peak commit {} MB", c.PeakPagefileUsage >> 20); } } + +/// After a pixel shader's reduction, what the helper lanes of a quad hold (sT copied to a +/// VGPR, vA, vB), read by the live pixels through DPP quad_perm (the console: every lane holds +/// the result). +#[test] +fn gpu_ps_reduction_result_in_helper_lanes() { + if !gpu_ready() { + return; + } + let mut bad = 0; + for wave64 in [true, false] { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + for (op, id, rop) in WAVE_REDUCTIONS.iter() { + for view in 0..3u64 { + // view 0: sT (as a VGPR), 1: vA, 2: vB + let mut c = vec![ + ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 16), ("SSRC0", 126)], None), + ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None), + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None), + ]; + c.push(whole_wave_reduction_as(wave64, op, *id, 13, Some(16), 40, 41)); + let src = [41, V + 6, V + 7][view as usize]; + c.extend([ + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 20), ("SRC0", src)], None), + ins("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 21), ("SRC0", 0xFA), ("VSRC0", 20), ("DPP_CTRL", 0xB1), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 22), ("SRC0", 0xFA), ("VSRC0", 20), ("DPP_CTRL", 0x4E), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 23), ("SRC0", 0xFA), ("VSRC0", 20), ("DPP_CTRL", 0x1B), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None), + ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 16)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 30), ("SRC0", V + 20)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 31), ("SRC0", V + 21)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 32), ("SRC0", V + 22)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 33), ("SRC0", V + 23)], None), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 30), ("VSRC1", 31), ("VSRC2", 32), ("VSRC3", 33), ("DONE", 1), ("VM", 1)], None), + ]); + let code = program_of(&c); + for (shape, tri) in [("3 quads", [[0.0f32, 0.0], [3.2, 0.0], [0.0, 3.2]]), ("55 pixels", [[0.0, 0.0], [11.0, 0.0], [0.0, 11.0]]), ("sliver", [[1.0, 1.0], [15.0, 2.2], [1.0, 2.2]])] { + let px = draw_console_as(None, Some(&code), &tri, wave64); + let live: Vec<(usize, [u32; 4])> = px.iter().enumerate().filter(|(_, p)| p[0] >= 0.0).map(|(i, p)| (i, p.map(|x| x as u32))).collect(); + let wrong: Vec<&(usize, [u32; 4])> = live.iter().filter(|(_, p)| p[1] != p[0] || p[2] != p[0] || p[3] != p[0]).collect(); + if !wrong.is_empty() { + bad += 1; + println!( + "wave64 {wave64} {} view {} {shape}: {} of {} live pixels see another value in their quad, e.g. pixel {} own {:#x} h {:#x} v {:#x} d {:#x}", + rop.name(), + ["sT", "vA", "vB"][view as usize], + wrong.len(), + live.len(), + wrong[0].0, + wrong[0].1[0], + wrong[0].1[1], + wrong[0].1[2], + wrong[0].1[3] + ); + } + } + } + } + } + println!("gpu_ps_reduction_result_in_helper_lanes: {bad} cases differ"); + assert_eq!(bad, 0); +} + +enum RvIt { + L(&'static str), + I(Vec), + B(&'static str, &'static str), +} + +/// Assemble items with labels and branches; ends in s_endpgm. +fn rv_assemble(items: &[RvIt]) -> Vec { + let mut at = std::collections::BTreeMap::new(); + let mut pc = 0usize; + for it in items { + match it { + RvIt::L(l) => { + at.insert(*l, pc); + } + RvIt::I(b) => pc += b.len(), + RvIt::B(..) => pc += 4, + } + } + let mut code = Vec::new(); + for it in items { + match it { + RvIt::L(_) => {} + RvIt::I(b) => code.extend(b.iter().copied()), + RvIt::B(n, l) => { + let rel = (at[l] as i64 - (code.len() as i64 + 4)) / 4; + code.extend(ins(n, "ENC_SOPP", &[("SIMM16", (rel as i16 as u16) as u64)], None)); + } + } + } + code.extend(ins("S_ENDPGM", "ENC_SOPP", &[], None)); + code +} + +/// Reductions as the retail pixel shaders place them - live pixels saved, s_wqm, a kill (cmpx, live &= ~exec), +/// a region under s_and_saveexec / s_cbranch_execz with a min reduction and a loop of two or +/// reductions (mask = live & saved EXEC). +#[test] +fn gpu_ps_reductions_in_branches_and_loops() { + use std::collections::BTreeMap; + use RvIt::*; + if !gpu_ready() { + return; + } + let mut bad = 0; + for wave64 in [true, false] { + let w = |b64: &'static str, b32: &'static str| if wave64 { b64 } else { b32 }; + let items = vec![ + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None)), + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None)), + I(ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None)), + I(ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 12)], None)), + I(ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", 128)], None)), + I(ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 15), ("SRC0", 193), ("SRC1", V + 15)], None)), + I(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 43), ("SSRC0", 128)], None)), + I(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 50), ("SSRC0", 128)], None)), + I(ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 51), ("SSRC0", 128)], None)), + I(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 16), ("SSRC0", 126)], None)), + I(ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None)), + // the helper lanes' pixel numbers too + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)], None)), + I(ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None)), + I(ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 11), ("SRC1", 128 + 4), ("SRC2", V + 10)], None)), + I(ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 129), ("VSRC1", 12)], None)), + // kill the pixels with (number & 3) == 3 + I(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)], None)), + I(ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 131), ("VSRC1", 12)], None)), + I(ins("V_CMPX_EQ_U32", "ENC_VOPC", &[("SRC0", 131), ("VSRC1", 14)], None)), + I(ins(w("S_ANDN2_B64", "S_ANDN2_B32"), "ENC_SOP2", &[("SDST", 16), ("SSRC0", 16), ("SSRC1", 126)], None)), + B("S_CBRANCH_SCC0", "end"), + I(ins(w("S_WQM_B64", "S_WQM_B32"), "ENC_SOP1", &[("SDST", 2), ("SSRC0", 16)], None)), + I(ins(w("S_AND_B64", "S_AND_B32"), "ENC_SOP2", &[("SDST", 126), ("SSRC0", 0), ("SSRC1", 2)], None)), + // the region: pixels with (number & 4) == 0 + I(ins("V_AND_B32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 132), ("VSRC1", 12)], None)), + I(ins("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 14)], None)), + I(ins(w("S_AND_SAVEEXEC_B64", "S_AND_SAVEEXEC_B32"), "ENC_SOP1", &[("SDST", 60), ("SSRC0", 106)], None)), + B("S_CBRANCH_EXECZ", "skip"), + I(whole_wave_reduction_as(wave64, "V_MIN_U32", 193, 13, Some(16), 40, 43)), + L("loop"), + I(ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 19), ("SRC0", 51), ("VSRC1", 13)], None)), + I(whole_wave_reduction_as(wave64, "V_OR_B32", 128, 19, Some(16), 40, 41)), + I(ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 50), ("SSRC0", 50), ("SSRC1", 41)], None)), + I(ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 51), ("SSRC0", 51), ("SSRC1", 129)], None)), + I(ins("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 51), ("SSRC1", 130)], None)), + B("S_CBRANCH_SCC1", "loop"), + L("skip"), + I(ins(w("S_MOV_B64", "S_MOV_B32"), "ENC_SOP1", &[("SDST", 126), ("SSRC0", 16)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 30), ("SRC0", 43)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 50)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 32), ("SRC0", 51)], None)), + I(ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 33), ("SRC0", 62), ("SRC1", 128 + 6), ("SRC2", V + 15)], None)), + I(ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 33), ("SRC0", V + 33)], None)), + I(ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 30), ("VSRC1", 31), ("VSRC2", 32), ("VSRC3", 33), ("DONE", 1), ("VM", 1)], None)), + L("end"), + ]; + let code = rv_assemble(&items); + { + let mut insts = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + assert_eq!(super::reductions::find(&insts, wave64).len(), 2, "both recognised"); + } + let shapes: [(&str, [[f32; 2]; 3]); 5] = [ + ("whole target", [[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]]), + ("3 quads", [[0.0, 0.0], [3.2, 0.0], [0.0, 3.2]]), + ("55 pixels", [[0.0, 0.0], [11.0, 0.0], [0.0, 11.0]]), + ("sliver", [[1.0, 1.0], [15.0, 2.2], [1.0, 2.2]]), + ("right", [[9.0, 9.0], [16.0, 9.0], [16.0, 16.0]]), + ]; + for (shape, tri) in shapes { + let px = draw_console_as(None, Some(&code), &tri, wave64); + let mut waves: BTreeMap> = BTreeMap::new(); + for (id, p) in px.iter().enumerate().filter(|(_, p)| p[3] >= 0.0) { + let kl = p[3] as u32; + waves.entry(kl >> 6).or_default().push((id as u32, kl & 63, *p)); + } + let mut wrong = 0; + let mut eg = String::new(); + for (first, wv) in &waves { + assert!(wv.iter().all(|x| x.0 & 3 != 3), "a killed pixel was drawn"); + let m: Vec = wv.iter().filter(|x| x.0 & 4 == 0).map(|x| x.0 + 1).collect(); + let want = if m.is_empty() { + [0, 0, 0] + } else { + let or = m.iter().fold(0, |a, b| a | b); + [*m.iter().min().unwrap(), or + (or << 1), 2] + }; + for (id, lane, p) in wv { + let got = [p[0] as u32, p[1] as u32, p[2] as u32]; + if got != want { + wrong += 1; + if eg.is_empty() { + eg = format!("pixel {id} lane {lane} wave of {first} ({} pixels): got {got:x?} want {want:x?}", wv.len()); + } + } + } + } + println!("wave64 {wave64} {shape}: waves {:?}, {wrong} wrong {eg}", waves.values().map(|w| w.len()).collect::>()); + bad += (wrong != 0) as usize; + } + } + assert_eq!(bad, 0); +} diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index ab0b43a..e29d8c5 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -1,10 +1,10 @@ //! Shader capture and classification. //! //! Every shader blob a title hands to D3D12.X (pipeline state creation, root -//! signatures) is classified and – once per unique hash – written to -//! `\shaders\`. Unknown formats are scanned for RDNA2 programs and a -//! disassembly is written next to the blob. This is how we learn, per title, whether -//! shaders still carry DXIL/DXBC or only console GPU microcode. +//! signatures) is classified once per unique hash. Writing the blob, the RDNA2 +//! disassembly and a second translation to `\shaders\` is `XCL_SHADER_DUMP=1`: +//! that work repeats the pipeline's own translation and is what a cold load spends +//! its time on. use std::collections::{BTreeMap, HashSet}; use std::path::PathBuf; @@ -201,6 +201,16 @@ fn dump_dir() -> PathBuf { crate::state::data_dir().join("shaders") } +/// Disk dumps and the extra translation that produces them. Off unless asked: the +/// pipeline path already translates each shader, and doing it again here serialises +/// the load on the title's thread. +fn dump_shaders() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1") || std::env::var("XCL_SHADER_DUMP").is_ok_and(|v| v == "1") + }) +} + /// Is `[p, p+len)` committed, readable memory? (Game-provided pointers may be garbage /// when our guess of a console struct layout is wrong.) pub fn readable(p: usize, len: usize) -> bool { @@ -228,9 +238,11 @@ pub fn readable(p: usize, len: usize) -> bool { } /// Record a shader blob submitted by the title. Safe on garbage pointers. +/// Without `XCL_SHADER_DUMP=1` this returns immediately: copying, hashing and +/// translating every shader here runs on the title thread, ahead of the real pipeline. pub fn capture(stage: &str, ptr: usize, len: usize) { - if ptr == 0 && len == 0 { - return; // unused stage + if !dump_shaders() || (ptr == 0 && len == 0) { + return; } let mut g = STATE.lock().unwrap(); let st = g.get_or_insert_with(|| State { seen: HashSet::new(), stats: ShaderStats::default(), insts: xbox::InstStats::default() }); @@ -287,7 +299,9 @@ pub fn capture(stage: &str, ptr: usize, len: usize) { /// program at every start. fn dumps_enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1")) + *ON.get_or_init(|| { + std::env::var("XCL_DUMP_SHADERS").is_ok_and(|v| v == "1") || std::env::var("XCL_SHADER_DUMP").is_ok_and(|v| v == "1") + }) } /// Console container without dumps: its FSSM variants and instructions accounted. diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 45d5185..f62009c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -214,7 +214,7 @@ pub(super) fn note_root_changing_signature(sig: usize) { pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let pso = super::pso_async::resolve_for_draw(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if let Some(tp) = super::real::two_pass_of(pso) { @@ -380,15 +380,17 @@ pub(super) unsafe fn emit_prepared_indexed_draw( unsafe fn graphics_bound(this: *mut c_void) -> Option { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); - // a pipeline still being built in the background is waited for (its stand-in draws nothing) - if super::real::two_pass_of(super::pso_async::resolve_wait(pso)).is_some() { + // a pipeline still being built in the background is waited for (its stand-in draws + // nothing), within a limit: past it the title's thread goes on (`resolve_for_draw`) + let real = super::pso_async::resolve_for_draw(pso); + if super::real::two_pass_of(real).is_some() { // a draw XCL does not run in two passes (DrawIndexedX): a mesh pipeline draws no // vertices on the PC count(DRAWS_SKIPPED); note_skipped(format_args!("a draw with a pipeline in two passes that is not run that way (DrawIndexedX) skipped")); return None; } - if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { + if !super::real::is_translated_graphics(real) { count(DRAWS_PC); if super::present::trace_frame() { // which pipelines draw without a translation (first 12 distinct) @@ -396,7 +398,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let mut g = SEEN.lock().unwrap(); if !g.contains(&pso) && g.len() < 12 { g.push(pso); - let real = super::pso_async::resolve_wait(pso); + let real = super::pso_async::resolve(pso); crate::xlog_info!( "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", super::pso_async::is_pending(pso), diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index aee3d02..0a9dfdb 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -645,6 +645,25 @@ pub(super) unsafe extern "system" fn create_sampler_x(this: *mut c_void, x: *con real::dev_create_sampler_x(this, &d, dest); } +/// Xbox colour formats a PC driver rejects. +pub fn pc_color_format(format: u32) -> u32 { + match format { + 116 | 117 => 10, // R10G10B10_*E*_A2_FLOAT → R16G16B16A16_FLOAT + // A8_UNORM is not a render-target format on this GPU. R8_UNORM still removed the + // device (the translated pixel shader writes float4). R8G8B8A8_UNORM matches that. + 65 => 28, + other => other, + } +} + +/// Xbox depth formats. 118 is `D16_UNORM_S8_UINT`; the PC depth format with stencil is D24. +pub fn pc_dsv_format(format: u32) -> u32 { + match format { + 118 | 119 => 45, // D16_UNORM_S8_UINT / its depth read → D24_UNORM_S8_UINT + other => other, + } +} + /// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts /// and console flag bits mean nothing to a PC driver pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { @@ -899,11 +918,32 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, return hr; } } + // a texture the CPU fills: on the title's pages of such textures (`vram`), shared with the + // ones placed there before as on the console, else a committed texture of its own + let mut kept = if buffer { Err(String::new()) } else { super::title_textures::layout(&x) }; + let on_pages = kept.as_ref().ok().map(|t| t.size()).filter(|_| !super::vram::gpu_owned(flags)); + if let Some(console_bytes) = on_pages { + let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); + if let Some(hr) = super::vram::place_title_texture(this, va as usize, &pc, state, console_bytes, riid, ppv) { + let res = *ppv; + let tex = std::mem::replace(&mut kept, Err(String::new())); + if tex.and_then(|t| super::title_textures::register(this, res, va as usize, t, D3D12_RESOURCE_STATES(state as i32))).is_ok() { + real::note_title_address(res as usize, va as usize); + return hr; + } + // (not kept in step: the pages are not its own – a resource of its own instead) + if !res.is_null() { + drop(windows::core::IUnknown::from_raw(res)); + } + *ppv = std::ptr::null_mut(); + kept = super::title_textures::layout(&x); + } + } let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv); if hr >= 0 && !buffer && !(*ppv).is_null() { static M: AtomicU64 = AtomicU64::new(0); - match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { + match kept.and_then(|tex| super::title_textures::register(this, *ppv, va as usize, tex, D3D12_RESOURCE_STATES(state as i32))) { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); return hr; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 9c8b2fe..4aa8198 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -23,6 +23,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +mod pso_disk; pub mod real; pub mod sparse; pub mod title_list; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 3f5c77f..30a84c5 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -372,15 +372,15 @@ const COMPILE_TIMER: usize = 0x5C0; /// While XCL compiles shaders (DXC, programs the disk cache did not have – the title draws /// nothing with those pipelines meanwhile: after an XCL update the screen stays black while /// thousands recompile), the window's title says so: -/// "XCL – | compiling shaders: N running, M done[, Q pipelines queued][, F failed]". +/// "XCL – | compiling shaders: N running, M done[, Q pipelines active][, F failed]". /// It stays 2 s after the last compile (compiles in the title's own calls come one by one), /// then the plain title comes back. unsafe fn show_compiling(hwnd: HWND) { static SHOWN: Mutex> = Mutex::new(None); static LAST_ACTIVE: Mutex> = Mutex::new(None); - let (_, failed, queued) = super::pso_async::counts(); + let (failed, pipelines) = super::pso_async::activity(); let (running, done) = crate::gpu::recomp::dxc::compile_counts(); - let active = running > 0 || queued > 0; + let active = running > 0 || pipelines > 0; let recent = { let mut last = LAST_ACTIVE.lock().unwrap(); if active { @@ -390,7 +390,7 @@ unsafe fn show_compiling(hwnd: HWND) { }; let title = window_name(); let text = if recent { - let queued = if queued > 0 { format!(", {queued} pipelines queued") } else { String::new() }; + let queued = if pipelines > 0 { format!(", {pipelines} pipelines active") } else { String::new() }; let failed = if failed > 0 { format!(", {failed} failed") } else { String::new() }; format!("XCL – {title} | compiling shaders: {running} running, {done} done{queued}{failed}") } else { diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e4769de..54ef6ae 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -3,13 +3,15 @@ //! it loads. When a pipeline's DXIL is not in the disk cache yet, the title gets a stand-in //! pipeline (shaders that draw nothing) at once and the real one is built on a worker; binding //! (`SetPipelineState`, console list replay, the two-pass lookups) uses the real one as soon -//! as it is there. A graphics pipeline draws nothing until then; a compute pipeline is waited +//! as it is there. A draw waits for its graphics pipeline only so long between presents +//! (`resolve_for_draw`), then draws nothing until it is built; a compute pipeline is waited //! for at its first bind (a skipped dispatch would corrupt what it computes). //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it @@ -25,6 +27,12 @@ struct Pending { orphan: std::sync::atomic::AtomicBool, } +impl Pending { + fn is_active(&self) -> bool { + self.sent.load(Ordering::Acquire) && !*self.done.lock().unwrap() + } +} + /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); @@ -153,7 +161,10 @@ pub fn resolve(pso: usize) -> usize { /// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + let start = Instant::now(); + p.sent.store(true, Ordering::Release); let job = p.job.lock().unwrap().take(); + let here = job.is_some(); if let Some(job) = job { complete(&p, job()); } @@ -161,7 +172,110 @@ pub fn resolve_wait(pso: usize) -> usize { while !*done { done = p.cv.wait(done).unwrap(); } - match p.real.load(Ordering::Acquire) { + let real = p.real.load(Ordering::Acquire); + drop(done); + note_long_wait(pso, p.compute, here, start.elapsed()); + match real { + 0 => pso, + r => r, + } +} + +/// A title's thread held this long in one pipeline wait is logged: a retail game's hang +/// watchdog ends the process (`mov dword [0], 0` at title+0x2215c35, #156 / #232) when its +/// threads stop for long, and an NVIDIA driver takes 10 - 17 s for one big translated pixel +/// shader, minutes for a big compute program (#156). +const LONG_WAIT: Duration = Duration::from_secs(2); + +fn note_long_wait(pso: usize, compute: bool, here: bool, took: Duration) { + static N: AtomicUsize = AtomicUsize::new(0); + if took >= LONG_WAIT && N.fetch_add(1, Ordering::Relaxed) < 32 { + crate::xlog_warn!( + "D3D12.X: thread '{}' waited {:.1} s for {} pipeline {pso:#x} ({})", + std::thread::current().name().unwrap_or("title"), + took.as_secs_f32(), + if compute { "compute" } else { "graphics" }, + if here { "built in this thread" } else { "built on a worker" } + ); + } +} + +/// The longest a draw holds the title's threads, between two presents, for graphics pipelines +/// still being built (`XCL_PSO_WAIT_MS`, default 4000; 0: no limit, as before). Past it a draw +/// goes on with its stand-in (draws nothing) and the pipeline is built on a worker. +fn draw_wait_limit() -> Option { + static L: OnceLock> = OnceLock::new(); + *L.get_or_init(|| match std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()) { + Some(0) => None, + Some(ms) => Some(Duration::from_millis(ms)), + None => Some(Duration::from_secs(4)), + }) +} + +/// Time spent in `resolve_for_draw` waits since present number `epoch`. +struct DrawWait { + epoch: u64, + spent: Duration, +} + +static DRAW_WAIT: Mutex = Mutex::new(DrawWait { epoch: 0, spent: Duration::ZERO }); + +/// For a draw (or ExecuteIndirect) of console code: a compute pipeline is waited for +/// (`resolve_wait`); a graphics one only within what is left of `draw_wait_limit` until the +/// next present, and never built in the title's thread, where a driver compile cannot be cut +/// short. A draw past the limit goes on with the stand-in, logged. +pub fn resolve_for_draw(pso: usize) -> usize { + resolve_within(pso, draw_wait_limit(), super::present::activity().0, &DRAW_WAIT) +} + +fn resolve_within(pso: usize, limit: Option, epoch: u64, budget: &Mutex) -> usize { + let Some(p) = entry(pso) else { return pso }; + let Some(limit) = limit.filter(|_| !p.compute) else { return resolve_wait(pso) }; + let left = { + let mut b = budget.lock().unwrap(); + if b.epoch != epoch { + *b = DrawWait { epoch, spent: Duration::ZERO }; + } + limit.saturating_sub(b.spent) + }; + // to the workers (a lazy one has not gone yet) + if !p.sent.swap(true, Ordering::AcqRel) { + let _ = queue().lock().unwrap().send(p.clone()); + } + let start = Instant::now(); + let deadline = start + left; + let mut done = p.done.lock().unwrap(); + while !*done { + let now = Instant::now(); + if now >= deadline { + break; + } + done = p.cv.wait_timeout(done, deadline - now).unwrap().0; + } + let (finished, real) = (*done, p.real.load(Ordering::Acquire)); + drop(done); + let waited = start.elapsed(); + { + let mut b = budget.lock().unwrap(); + if b.epoch == epoch { + b.spent += waited; + } + } + if !finished { + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: graphics pipeline {pso:#x} not built after {:.1} s of waiting since present {epoch} (limit {} ms, XCL_PSO_WAIT_MS) – drawn with its stand-in, still building on a worker ({} such draws)", + waited.as_secs_f32(), + limit.as_millis(), + n + 1 + ); + } + } else { + note_long_wait(pso, false, false, waited); + } + match real { 0 => pso, r => r, } @@ -196,8 +310,177 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } +/// How many uncached driver compiles may run at once. Each one fans out across the GPU +/// driver's own compiler, so a few of them already fill the machine; more of them fight +/// over the same cores and the load takes longer. `XCL_PSO_COMPILES` overrides it. +fn driver_compile_limit() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + std::env::var("XCL_PSO_COMPILES").ok().and_then(|v| v.parse().ok()).unwrap_or((cores / 4).clamp(2, 4)) + }) +} + +struct DriverGate { + /// compiles in the driver, and whether a resource create wants the driver to itself + running: Mutex<(usize, bool)>, + cv: Condvar, +} + +fn driver_gate() -> &'static DriverGate { + static G: OnceLock = OnceLock::new(); + G.get_or_init(|| DriverGate { running: Mutex::new((0, false)), cv: Condvar::new() }) +} + +/// Hold the driver until the in-flight pipeline compiles finish, and keep new ones from +/// starting. A resource create overlapping a pipeline compile removes the device on this GPU. +pub struct DriverQuiet; + +impl Drop for DriverQuiet { + fn drop(&mut self) { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.1 = false; + g.cv.notify_all(); + } +} + +pub fn quiet_driver() -> DriverQuiet { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.1 = true; + if n.0 > 0 { + crate::xlog_info!("D3D12.X: waiting for {} pipeline compile(s) before creating a resource", n.0); + } + while n.0 > 0 { + n = g.cv.wait(n).unwrap(); + } + DriverQuiet +} + +/// Held across one driver compile of a pipeline the cache did not have. +pub struct DriverGuard; + +impl Drop for DriverGuard { + fn drop(&mut self) { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.0 = n.0.saturating_sub(1); + g.cv.notify_all(); + } +} + +/// Block until fewer than `driver_compile_limit` uncached driver compiles are running. +pub fn uncached_compile() -> DriverGuard { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!("D3D12.X: up to {} new pipelines compile in the driver at once", driver_compile_limit()); + }); + let g = driver_gate(); + let limit = driver_compile_limit(); + let mut n = g.running.lock().unwrap(); + while n.1 || n.0 >= limit { + n = g.cv.wait(n).unwrap(); + } + n.0 += 1; + DriverGuard +} + /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } + +/// Failed builds and builds actually started or sent to workers, excluding dormant lazy pipelines. +pub fn activity() -> (usize, usize) { + let active = PENDING.lock().unwrap().as_ref().map_or(0, |m| { + m.values().filter(|p| p.is_active()).count() + }); + (FAILED.load(Ordering::Relaxed), active) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn budget() -> Mutex { + Mutex::new(DrawWait { epoch: 0, spent: Duration::ZERO }) + } + + /// A graphics build that does not finish (an NVIDIA driver compile of minutes, #156) holds a + /// draw only up to the limit, once until the next present, and runs on a worker. With + /// `resolve_wait` the draw waited for it without limit (building it itself when no worker + /// had taken it), which held the title past its hang watchdog. + #[test] + fn a_draw_waits_for_a_graphics_build_only_within_the_limit_and_never_builds_it_itself() { + let (standin, real) = (0x7410_0001usize, 0x7410_0002usize); + let (go_tx, go_rx) = mpsc::channel::<()>(); + let (who_tx, who_rx) = mpsc::channel::>(); + submit_lazy( + standin, + false, + Box::new(move || { + let _ = who_tx.send(std::thread::current().name().map(str::to_string)); + let _ = go_rx.recv(); + real + }), + ); + let b = budget(); + let limit = Some(Duration::from_millis(300)); + let t = Instant::now(); + assert_eq!(resolve_within(standin, limit, 1, &b), standin, "drawn with the stand-in"); + let took = t.elapsed(); + assert!(took >= Duration::from_millis(290) && took < Duration::from_secs(5), "waited {took:?}"); + let who = who_rx.recv_timeout(Duration::from_secs(5)).expect("the build went to a worker"); + assert!(who.as_deref().is_some_and(|n| n.starts_with("xcl-pso")), "built on {who:?}"); + // the limit is spent until the next present: the next draw does not wait + let t = Instant::now(); + assert_eq!(resolve_within(standin, limit, 1, &b), standin); + assert!(t.elapsed() < Duration::from_millis(200), "waited {:?} with the limit spent", t.elapsed()); + assert!(is_pending(standin)); + // after the next present, once built: the real pipeline + go_tx.send(()).unwrap(); + assert_eq!(resolve_within(standin, Some(Duration::from_secs(10)), 2, &b), real); + assert!(!is_pending(standin)); + let _ = released(standin); + } + + /// Compute pipelines are still waited for (a skipped dispatch corrupts its results), and + /// `XCL_PSO_WAIT_MS=0` (no limit) waits for graphics ones as before. + #[test] + fn compute_pipelines_and_no_limit_wait_as_before() { + let b = budget(); + let (c, c_real) = (0x7410_0011usize, 0x7410_0012usize); + submit_lazy( + c, + true, + Box::new(move || { + std::thread::sleep(Duration::from_millis(100)); + c_real + }), + ); + assert_eq!(resolve_within(c, Some(Duration::ZERO), 1, &b), c_real); + let (g, g_real) = (0x7410_0021usize, 0x7410_0022usize); + submit_lazy(g, false, Box::new(move || g_real)); + assert_eq!(resolve_within(g, None, 1, &b), g_real); + assert_eq!(resolve_within(0x7410_0031, Some(Duration::ZERO), 1, &b), 0x7410_0031, "not a stand-in"); + let _ = released(c); + let _ = released(g); + } + + #[test] + fn lazy_pipeline_is_active_only_after_its_build_starts() { + let standin = usize::MAX - 1000; + submit_lazy(standin, true, Box::new(move || { + let p = entry(standin).unwrap(); + assert!(p.is_active()); + 0 + })); + let p = entry(standin).unwrap(); + assert!(!p.is_active()); + assert_eq!(resolve_wait(standin), standin); + assert!(!p.is_active()); + assert_eq!(released(standin), 0); + } +} diff --git a/crates/xcl/src/hle/d3d12x/pso_disk.rs b/crates/xcl/src/hle/d3d12x/pso_disk.rs new file mode 100644 index 0000000..7d1d2ea --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_disk.rs @@ -0,0 +1,293 @@ +//! Driver pipeline blobs (`ID3D12PipelineState::GetCachedBlob`). +//! +//! Translating a console shader is cached as DXIL. The driver then compiles that DXIL again +//! on every launch. A blob from `GetCachedBlob` is that compile: the next +//! `Create*PipelineState` passes it in `CachedPSO` and the driver skips the work when the +//! blob still matches this device. A driver update rejects the blob; the caller drops the +//! file and compiles again. + +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; + +const MAGIC: &[u8; 4] = b"XPSO"; +const VERSION: u32 = 1; + +fn dir() -> PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + if let Ok(d) = std::env::var("XCL_PSO_CACHE") { + return PathBuf::from(d); + } + let base = std::env::var("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(|_| std::env::temp_dir()); + base.join("xcl").join("pso") + }) + .clone() +} + +fn memory() -> &'static Mutex>>> { + static M: OnceLock>>>> = OnceLock::new(); + M.get_or_init(|| Mutex::new(std::collections::HashMap::new())) +} + +fn path_for(dir: &Path, key: u64) -> PathBuf { + dir.join(format!("{key:016x}.blob")) +} + +fn payload(file: &[u8]) -> Option<&[u8]> { + if file.len() < 8 || &file[..4] != MAGIC || u32::from_le_bytes(file[4..8].try_into().ok()?) != VERSION { + return None; + } + let blob = &file[8..]; + (!blob.is_empty() && blob.len() <= 32 << 20).then_some(blob) +} + +/// A blob saved for `key`, from this process or from disk. +pub fn load(key: u64) -> Option>> { + if let Some(hit) = memory().lock().unwrap().get(&key).cloned() { + return Some(hit); + } + let bytes = std::fs::read(path_for(&dir(), key)).ok()?; + let blob = payload(&bytes)?.to_vec(); + let blob = std::sync::Arc::new(blob); + memory().lock().unwrap().insert(key, blob.clone()); + Some(blob) +} + +fn write_file(key: u64, blob: &[u8]) { + let dir = dir(); + if std::fs::create_dir_all(&dir).is_err() { + return; + } + let path = path_for(&dir, key); + if std::fs::read(&path).ok().and_then(|b| payload(&b).map(|p| p == blob)).unwrap_or(false) { + return; + } + let mut body = Vec::with_capacity(8 + blob.len()); + body.extend_from_slice(MAGIC); + body.extend_from_slice(&VERSION.to_le_bytes()); + body.extend_from_slice(blob); + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + if std::fs::write(&tmp, &body).is_ok() && std::fs::rename(&tmp, &path).is_err() { + let _ = std::fs::remove_file(&tmp); + } +} + +fn writer() -> &'static std::sync::mpsc::SyncSender<(u64, std::sync::Arc>)> { + static W: OnceLock>)>> = OnceLock::new(); + W.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::sync_channel::<(u64, std::sync::Arc>)>(64); + let _ = std::thread::Builder::new().name("xcl-pso-cache".into()).spawn(move || { + while let Ok((key, blob)) = rx.recv() { + write_file(key, &blob); + } + }); + tx + }) +} + +/// Remember `blob` now and write it on a side thread, so a driver compile is not stuck on disk. +pub fn store(key: u64, blob: &[u8]) { + if blob.is_empty() || blob.len() > 32 << 20 { + return; + } + let owned = std::sync::Arc::new(blob.to_vec()); + memory().lock().unwrap().insert(key, owned.clone()); + if let Err(std::sync::mpsc::TrySendError::Full((_, blob))) = writer().try_send((key, owned)) { + write_file(key, &blob); + } +} + +/// The driver refused this blob (a new driver, or a different pipeline). Do not try it again. +pub fn forget(key: u64) { + memory().lock().unwrap().remove(&key); + let _ = std::fs::remove_file(path_for(&dir(), key)); +} + +fn mix(h: &mut u64, bytes: &[u8]) { + for &b in bytes { + *h ^= b as u64; + *h = h.wrapping_mul(0x100_0000_01b3); + } +} + +fn mix_u32(h: &mut u64, v: u32) { + mix(h, &v.to_le_bytes()); +} + +fn mix_shader(h: &mut u64, s: &D3D12_SHADER_BYTECODE) { + let n = s.BytecodeLength; + let p = s.pShaderBytecode as usize; + if n == 0 || !crate::gpu::shader::readable(p, n) { + mix_u32(h, 0); + return; + } + mix_u32(h, n as u32); + mix(h, unsafe { std::slice::from_raw_parts(p as *const u8, n) }); +} + +fn mix_input(h: &mut u64, layout: &D3D12_INPUT_LAYOUT_DESC) { + let n = layout.NumElements as usize; + mix_u32(h, layout.NumElements); + if n == 0 || n > 32 || layout.pInputElementDescs.is_null() { + return; + } + let bytes = n * std::mem::size_of::(); + if !crate::gpu::shader::readable(layout.pInputElementDescs as usize, bytes) { + return; + } + let elems = unsafe { std::slice::from_raw_parts(layout.pInputElementDescs, n) }; + for e in elems { + if !e.SemanticName.is_null() { + let mut k = 0usize; + while k < 64 { + let c = unsafe { *e.SemanticName.0.add(k) }; + mix(h, &[c]); + if c == 0 { + break; + } + k += 1; + } + } + mix_u32(h, e.SemanticIndex); + mix_u32(h, e.Format.0 as u32); + mix_u32(h, e.InputSlot); + mix_u32(h, e.AlignedByteOffset); + mix_u32(h, e.InputSlotClass.0 as u32); + mix_u32(h, e.InstanceDataStepRate); + } +} + +fn mix_blend(h: &mut u64, b: &D3D12_BLEND_DESC) { + mix_u32(h, b.AlphaToCoverageEnable.0 as u32); + mix_u32(h, b.IndependentBlendEnable.0 as u32); + for rt in &b.RenderTarget { + mix_u32(h, rt.BlendEnable.0 as u32); + mix_u32(h, rt.LogicOpEnable.0 as u32); + mix_u32(h, rt.SrcBlend.0 as u32); + mix_u32(h, rt.DestBlend.0 as u32); + mix_u32(h, rt.BlendOp.0 as u32); + mix_u32(h, rt.SrcBlendAlpha.0 as u32); + mix_u32(h, rt.DestBlendAlpha.0 as u32); + mix_u32(h, rt.BlendOpAlpha.0 as u32); + mix_u32(h, rt.LogicOp.0 as u32); + mix_u32(h, rt.RenderTargetWriteMask as u32); + } +} + +fn mix_op(h: &mut u64, o: &D3D12_DEPTH_STENCILOP_DESC) { + mix_u32(h, o.StencilFailOp.0 as u32); + mix_u32(h, o.StencilDepthFailOp.0 as u32); + mix_u32(h, o.StencilPassOp.0 as u32); + mix_u32(h, o.StencilFunc.0 as u32); +} + +fn mix_depth(h: &mut u64, z: &D3D12_DEPTH_STENCIL_DESC) { + mix_u32(h, z.DepthEnable.0 as u32); + mix_u32(h, z.DepthWriteMask.0 as u32); + mix_u32(h, z.DepthFunc.0 as u32); + mix_u32(h, z.StencilEnable.0 as u32); + mix(h, &[z.StencilReadMask, z.StencilWriteMask]); + mix_op(h, &z.FrontFace); + mix_op(h, &z.BackFace); +} + +fn mix_raster(h: &mut u64, r: &D3D12_RASTERIZER_DESC) { + mix_u32(h, r.FillMode.0 as u32); + mix_u32(h, r.CullMode.0 as u32); + mix(h, &r.FrontCounterClockwise.0.to_le_bytes()); + mix(h, &r.DepthBias.to_le_bytes()); + mix(h, &r.DepthBiasClamp.to_le_bytes()); + mix(h, &r.SlopeScaledDepthBias.to_le_bytes()); + mix_u32(h, r.DepthClipEnable.0 as u32); + mix_u32(h, r.MultisampleEnable.0 as u32); + mix_u32(h, r.AntialiasedLineEnable.0 as u32); + mix_u32(h, r.ForcedSampleCount); + mix_u32(h, r.ConservativeRaster.0 as u32); +} + +fn mix_samplers(h: &mut u64, samplers: &[([u32; 4], bool)]) { + mix_u32(h, samplers.len() as u32); + for (words, comparison) in samplers { + for w in words { + mix_u32(h, *w); + } + mix(h, &[*comparison as u8]); + } +} + +/// Identity of a graphics pipeline the driver compiled. The root signature pointer is not +/// part of it; `samplers` is, because that is what the XCL root signature was built from. +pub fn graphics_key(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, samplers: &[([u32; 4], bool)]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + mix(&mut h, b"gfx1"); + mix_shader(&mut h, &d.VS); + mix_shader(&mut h, &d.PS); + mix_shader(&mut h, &d.DS); + mix_shader(&mut h, &d.HS); + mix_shader(&mut h, &d.GS); + mix_blend(&mut h, &d.BlendState); + mix_u32(&mut h, d.SampleMask); + mix_raster(&mut h, &d.RasterizerState); + mix_depth(&mut h, &d.DepthStencilState); + mix_input(&mut h, &d.InputLayout); + mix_u32(&mut h, d.IBStripCutValue.0 as u32); + mix_u32(&mut h, d.PrimitiveTopologyType.0 as u32); + mix_u32(&mut h, d.NumRenderTargets); + for f in &d.RTVFormats { + mix_u32(&mut h, f.0 as u32); + } + mix_u32(&mut h, d.DSVFormat.0 as u32); + mix_u32(&mut h, d.SampleDesc.Count); + mix_u32(&mut h, d.SampleDesc.Quality); + mix_u32(&mut h, d.NodeMask); + mix_u32(&mut h, d.Flags.0 as u32); + mix_samplers(&mut h, samplers); + h +} + +pub fn compute_key(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, samplers: &[([u32; 4], bool)]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + mix(&mut h, b"cs1"); + mix_shader(&mut h, &d.CS); + mix_u32(&mut h, d.NodeMask); + mix_u32(&mut h, d.Flags.0 as u32); + mix_samplers(&mut h, samplers); + h +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shader_bytes_change_the_key_and_the_blob_round_trips() { + let vs = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let mut g = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g.VS = D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const _, BytecodeLength: vs.len() }; + g.NumRenderTargets = 1; + g.RTVFormats[0] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + let k1 = graphics_key(&g, &[]); + let vs2 = [1u8, 2, 3, 4, 5, 6, 7, 9]; + g.VS.pShaderBytecode = vs2.as_ptr() as *const _; + assert_ne!(k1, graphics_key(&g, &[])); + g.VS.pShaderBytecode = vs.as_ptr() as *const _; + assert_eq!(k1, graphics_key(&g, &[])); + assert_ne!(k1, graphics_key(&g, &[([1, 2, 3, 4], false)])); + + let dir = std::env::temp_dir().join(format!("xcl-pso-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = path_for(&dir, k1); + let blob = b"driver-blob-bytes"; + let mut body = Vec::new(); + body.extend_from_slice(MAGIC); + body.extend_from_slice(&VERSION.to_le_bytes()); + body.extend_from_slice(blob); + std::fs::write(&file, &body).unwrap(); + let read = std::fs::read(&file).unwrap(); + assert_eq!(payload(&read), Some(blob.as_slice())); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 7d20879..9b17b71 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -411,10 +411,19 @@ pub fn stats() -> D3d12Stats { static DEVICE: AtomicUsize = AtomicUsize::new(0); +/// The backend device runs on a software adapter (WARP or the Basic Render Driver). +static SOFTWARE_ADAPTER: AtomicBool = AtomicBool::new(false); + pub fn device_raw() -> *mut c_void { DEVICE.load(Ordering::Acquire) as *mut c_void } +/// Whether the backend device is a software renderer: it draws, but it has no sparse +/// reservations, real mesh pipeline or 4 GiB aperture, so tests that check those skip. +pub fn software_adapter() -> bool { + SOFTWARE_ADAPTER.load(Ordering::Relaxed) +} + /// The process's video memory on the device's adapter: (local, non-local) bytes in use. pub fn video_memory() -> Option<(u64, u64)> { use windows::Win32::Graphics::Dxgi::*; @@ -517,6 +526,7 @@ pub fn init() -> Result { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { device = Some(dev); name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); + SOFTWARE_ADAPTER.store(crate::gpu::adapter::software(&desc), Ordering::Relaxed); break; } } @@ -528,6 +538,7 @@ pub fn init() -> Result { let d = crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0) .map_err(|e| format!("D3D12 device (WARP): {e}"))?; name = "WARP (software renderer)".into(); + SOFTWARE_ADAPTER.store(true, Ordering::Relaxed); d } }; @@ -3228,6 +3239,105 @@ fn with_switch_fallback(mut build: impl FnMut() -> R) -> R { crate::gpu::recomp::pso::in_switch_form(build) } +fn cached_pso(blob: &[u8]) -> D3D12_CACHED_PIPELINE_STATE { + D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: if blob.is_empty() { std::ptr::null() } else { blob.as_ptr() as *const c_void }, + CachedBlobSizeInBytes: blob.len(), + } +} + +unsafe fn driver_blob(pso: *mut c_void) -> Option> { + let pso = ID3D12PipelineState::from_raw_borrowed(&pso)?; + let blob = pso.GetCachedBlob().ok()?; + let n = blob.GetBufferSize(); + if n == 0 || n > 32 << 20 { + return None; + } + Some(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, n).to_vec()) +} + +fn note_driver_cache(saved: bool) { + static SAVED: AtomicU64 = AtomicU64::new(0); + static USED: AtomicU64 = AtomicU64::new(0); + let (n, word) = if saved { (SAVED.fetch_add(1, Ordering::Relaxed), "saved") } else { (USED.fetch_add(1, Ordering::Relaxed), "reused") }; + if n < 3 || n % 500 == 0 { + crate::xlog_info!("D3D12.X: driver pipeline cache: {} pipelines {word}", n + 1); + } +} + +static PSO_DEVICE_REMOVED: AtomicBool = AtomicBool::new(false); + +fn device_is_removed(_this: *mut c_void) -> bool { + PSO_DEVICE_REMOVED.load(Ordering::Acquire) +} + +fn note_device_removed() { + PSO_DEVICE_REMOVED.store(true, Ordering::Release); +} + +/// Create `desc` (a graphics or compute pipeline desc). A blob saved for `key` is tried +/// first; the driver's own blob is written when this compile is new. A cache hit does not +/// take a driver-compile slot. A miss does, so only a few new pipelines compile at once. +unsafe fn finish_pso_cached(this: *mut c_void, f: PsoFn, desc: *mut c_void, graphics: bool, key: u64, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let loaded = super::pso_disk::load(key); + let apply = |blob: &[u8]| { + let cached = cached_pso(blob); + if graphics { + (*(desc as *mut D3D12_GRAPHICS_PIPELINE_STATE_DESC)).CachedPSO = cached; + } else { + (*(desc as *mut D3D12_COMPUTE_PIPELINE_STATE_DESC)).CachedPSO = cached; + } + }; + if let Some(blob) = &loaded { + apply(blob); + let hr = finish_pso(this, f, desc, riid, ppv); + if hr >= 0 { + note_driver_cache(false); + return hr; + } + if (hr as u32) & 0xFFFF_0000 == 0x887A_0000 { + note_device_removed(); + return hr; + } + super::pso_disk::forget(key); + apply(&[]); + } + if device_is_removed(this) { + return 0x887A_0005u32 as HRESULT; + } + // This graphics pipeline removes the device from inside the driver's compile. Cached + // pipelines still load above. Compute pipelines are built (big ones in the background). + if graphics && key == 0x94a63ac3f96c98ac { + crate::xlog_warn!("D3D12.X: pipeline {key:016x} is not compiled: it removes the device"); + return E_INVALIDARG; + } + let _guard = super::pso_async::uncached_compile(); + if graphics { + let g = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + let n = (g.NumRenderTargets as usize).min(8); + crate::xlog_info!( + "D3D12.X: driver compile {key:016x} RTs {} {:?} DSV {} samples {}", + g.NumRenderTargets, + &g.RTVFormats[..n].iter().map(|f| f.0).collect::>(), + g.DSVFormat.0, + g.SampleDesc.Count + ); + } else { + crate::xlog_info!("D3D12.X: driver compile {key:016x} compute"); + } + let hr = finish_pso(this, f, desc, riid, ppv); + if (hr as u32) & 0xFFFF_0000 == 0x887A_0000 { + note_device_removed(); + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(blob) = driver_blob(*ppv) { + super::pso_disk::store(key, &blob); + note_driver_cache(true); + } + } + hr +} + thread_local! { /// translation errors noted during a cached-only attempt (`attempt`) static ATTEMPT_NOTES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; @@ -3437,13 +3547,15 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(&dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let key = super::pso_disk::compute_key(©, &compiled.samplers); // in the background, one at a time and within the commit left (each ~1.5 GB in the driver) let _slot = (big && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso"))).then(|| { let slot = BIG_COMPILES.acquire(); wait_for_commit(); slot }); - let hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); + // a driver blob saved for this pipeline skips the driver's compile (`pso_disk`) + let hr = finish_pso_cached(this, f, &mut copy as *mut _ as *mut c_void, false, key, riid, ppv); if hr < 0 { note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); return Some(Err(())); @@ -3528,6 +3640,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.GS = bytecode(gs); } pc_topology_type(&mut copy); + pc_pso_formats(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); @@ -3535,7 +3648,10 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - let hr = retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv)); + let hr = retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| { + let key = super::pso_disk::graphics_key(c, &samplers); + finish_pso_cached(this, f, c as *mut _ as *mut c_void, true, key, riid, ppv) + }); if hr < 0 { note_translation_error(format!( "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -4331,7 +4447,7 @@ const RECT_LIST_TYPE: i32 = 19; /// `create(copy)`, and once more without the generated rect list GS (`rect_gs`) when the driver /// refuses the pipeline with it: each rect is then drawn as the triangle of its three vertices, /// as without the GS, rather than not at all (the untranslated fallback's dummy shaders). -fn retry_without_rect_gs(copy: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool, mut create: impl FnMut(&D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> HRESULT) -> HRESULT { +fn retry_without_rect_gs(copy: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool, mut create: impl FnMut(&mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> HRESULT) -> HRESULT { let hr = create(copy); if hr >= 0 || !rect_gs { return hr; @@ -4386,6 +4502,64 @@ fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { } } +fn dxgi(format: u32) -> windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT { + windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(format as i32) +} + +fn pc_pso_formats(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { + // A typeless format, or an Xbox-only one, in a pipeline is an invalid call. On this GPU + // that removes the device (0x887A0001) instead of returning E_INVALIDARG, and every later + // create fails the same way. Only illegal formats change, so a pipeline the driver already + // accepted keeps its cache key. + g.DSVFormat = dxgi(typed_dsv(super::device_x::pc_dsv_format(g.DSVFormat.0 as u32))); + let n = (g.NumRenderTargets as usize).min(g.RTVFormats.len()); + for f in &mut g.RTVFormats[..n] { + *f = dxgi(typed_rtv(super::device_x::pc_color_format(f.0 as u32))); + } + if g.SampleDesc.Count == 0 { + g.SampleDesc.Count = 1; + g.SampleDesc.Quality = 0; + } +} + +/// A render-target format the PC accepts. Typeless and the Xbox depth family are not. +fn typed_rtv(format: u32) -> u32 { + match format { + 1 => 2, // R32G32B32A32 + 5 => 6, // R32G32B32 + 9 => 10, // R16G16B16A16 + 15 => 16, // R32G32 + 23 => 24, // R10G10B10A2 + 27 => 28, // R8G8B8A8 + 33 => 35, // R16G16 + 39 => 40, // R32 + 44 | 118 | 119 | 120 => 28, + 48 => 49, // R8G8 + 53 => 54, // R16 + 60 => 61, // R8 + 70 => 71, // BC1 + 73 => 74, // BC2 + 76 => 77, // BC3 + 79 => 80, // BC4 + 82 => 83, // BC5 + 95 => 96, // BC6H + 98 => 99, // BC7 + other => other, + } +} + +/// A depth format the PC accepts. Anything else is no depth view, which the driver allows. +fn typed_dsv(format: u32) -> u32 { + match format { + 0 => 0, + 19 | 20 => 20, // D32_FLOAT_S8X24 + 39 | 41 => 41, // D32_FLOAT + 44 | 45 | 118 | 119 => 45, // D24_UNORM_S8 + 53 | 55 => 55, // D16_UNORM + other => other, + } +} + enum StreamPipeline { Graphics(Box), Compute(Box), @@ -4517,6 +4691,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { pc_topology_type(&mut g); } + pc_pso_formats(&mut g); StreamPipeline::Graphics(Box::new(g)) } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2d8194e..1e170a5 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -19,6 +19,11 @@ //! transitions of these textures are noted per PC command list as they are recorded //! (`note_transitions`) and applied, in submission order, when the list is submitted //! (`submitted`) – per subresource once a transition names one. +//! +//! The PC texture is a reserved resource on 64 KiB pages of video memory, one per page of the +//! title's address, shared by every such texture placed there (`vram::place_title_texture`) – +//! a title streaming its world places new textures over the old ones' memory; where it cannot +//! be (an address not 64 KiB aligned, a texture the driver does not reserve) it is committed. use std::collections::BTreeMap; use std::ffi::c_void; @@ -54,8 +59,15 @@ struct Entry { /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from /// then on and no longer uploaded gpu_written: bool, + /// the order it was placed in: textures placed over the same memory share its video memory + /// (`vram::place_title_texture`), and as on the console the newest one's texels are what it + /// holds – uploads go oldest first + seq: u64, } +/// the next texture's `Entry::seq` +static SEQ: AtomicU64 = AtomicU64::new(0); + /// textures waiting for their first upload static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -80,8 +92,9 @@ pub fn counts() -> (usize, u64) { (TEXTURES.lock().unwrap().len(), UPLOADS.load(Ordering::Relaxed)) } -/// A texture the title placed at `va` (its console desc `desc`): kept in step with the memory. -pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, desc: &[u8; 0x38], state: D3D12_RESOURCE_STATES) -> Result<(), String> { +/// The console layout of a texture the title places (its console desc `desc`) when it can be +/// kept in step with the memory (`register`); Err: why not. +pub(super) fn layout(desc: &[u8; 0x38]) -> Result { let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; // the console's 32-bit 116 / 117 floats are half floats on the PC (`pc_resource_desc`): the // title's bytes are not the resource's texels @@ -110,13 +123,20 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 2 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a small render target at {va:#x} ({} planes) is kept in step with the title's memory – a glyph cache the CPU fills ({n} so far)", tex.planes.len()); + crate::xlog_info!("D3D12.X: a small render target ({} planes) is kept in step with the title's memory – a glyph cache the CPU fills ({n} so far)", tex.planes.len()); } } + Ok(tex) +} + +/// A texture the title placed at `va` (its console layout `tex`, from `layout`): kept in step +/// with the memory. +pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, tex: xg::Texture, state: D3D12_RESOURCE_STATES) -> Result<(), String> { if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } - let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false }; + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, seq }; { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -392,7 +412,7 @@ unsafe fn refresh_once(queue: *mut c_void) { } // textures made since the last submit and those with a written page; a reference each // while they are uploaded - let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { + let mut todo: Vec<(u64, ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); t.iter_mut() @@ -412,11 +432,18 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (e.seq, r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); - upload_all(todo); + upload_all(in_placement_order(&mut todo)); +} + +/// The uploads `todo` (placement order, PC texture, upload) oldest placement first: where +/// textures share video memory the newest one's upload is the last word. +fn in_placement_order(todo: &mut Vec<(u64, R, U)>) -> Vec<(R, U)> { + todo.sort_unstable_by_key(|t| t.0); + todo.drain(..).map(|(_, r, u)| (r, u)).collect() } /// staging bytes of one batch at most @@ -457,6 +484,8 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { continue; } }; + // textures on pages: their tiles' mappings come first + super::vram::before_execute(&queue); match own_work(|| texture::upload_batch(dev, &queue, &batch)) { Ok(failed) => { for (_, e) in failed { @@ -710,7 +739,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, seq: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); diff --git a/crates/xcl/src/hle/d3d12x/two_pass_tests.rs b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs index 941f21a..aa9fd15 100644 --- a/crates/xcl/src/hle/d3d12x/two_pass_tests.rs +++ b/crates/xcl/src/hle/d3d12x/two_pass_tests.rs @@ -39,6 +39,12 @@ fn ready() -> Option { println!("no real D3D12 device – skipping"); return None; } + if real::software_adapter() { + // WARP / the Basic Render Driver report mesh shaders but reject the translated pipelines + println!("software adapter (no GPU) – skipping"); + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } if real::uma_window_vas().is_empty() { println!("unified memory is not open on the GPU – skipping"); return None; diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index dcca9ec..9b6c058 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -22,6 +22,11 @@ //! Arenas remain for what cannot be tiled (an address not 64 KiB aligned, a resource the //! driver does not make reserved: D32S8, MSAA): heaps of the placement's size, shared by //! placements inside them, let go 2 s after their last resource (256 MiB ones: 2.8 GB of D32S8). +//! +//! Textures the CPU fills (kept in step with the title's memory, `title_textures`) go on pages +//! the same way, in a space of their own (`Space`): a title streaming its world places new +//! textures over memory it used before and lets few of the old ones go, and a committed texture +//! per placement held the sum of every texture ever placed (#248). use std::collections::HashSet; use std::ffi::c_void; @@ -170,28 +175,133 @@ const COOL: std::time::Duration = std::time::Duration::from_secs(2); /// A pool tile: (pool heap, tile in it). type Tile = (u32, u32); +/// Which resources share a title page's video memory. GPU-owned targets share with targets, +/// textures kept in step with the title's memory (`title_textures`) with such textures: their +/// uploads are the CPU's view of the memory, which over a target's page would overwrite what +/// the GPU rendered there (on the console the memory holds it; here the CPU's view does not). +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Space { + Targets, + Textures, +} + struct Page { tile: Tile, - /// targets using the page + /// resources using the page users: u32, /// when the last of them went idle_since: Option, } -/// The title's pages of video memory for GPU-owned textures (see the module's comment). +/// Which pool tile backs which title page, and which resource uses which pages – apart from +/// D3D12 (a new pool heap is the `grow` callback's). +struct Book { + free: Vec, + /// tiles given back, reusable after `COOL` + cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, + /// (space, title page address) → its video memory + pages: std::collections::HashMap<(Space, usize), Page>, + /// resource → (its space, the title pages it uses, tiles of its own past the title's memory) + users: std::collections::HashMap, Vec)>, +} + +impl Book { + fn new() -> Book { + Book { free: Vec::new(), cooling: std::collections::VecDeque::new(), pages: std::collections::HashMap::new(), users: std::collections::HashMap::new() } + } + + /// Pages no resource used for `IDLE` go back to the pools. + fn sweep(&mut self, now: std::time::Instant) { + let old: Vec<(Space, usize)> = self.pages.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&a, _)| a).collect(); + for a in old { + if let Some(p) = self.pages.remove(&a) { + self.cooling.push_back((p.tile, now)); + } + } + } + + /// A tile: a free one, one cooled down, else the first of a new pool heap (`grow`: its + /// index; None: no video memory). + fn take_tile(&mut self, now: std::time::Instant, grow: &mut impl FnMut() -> Option) -> Option { + if let Some(t) = self.free.pop() { + return Some(t); + } + if self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + return self.cooling.pop_front().map(|(t, _)| t); + } + let h = grow()?; + self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); + Some((h, 0)) + } + + /// The tiles of resource `res` at title address `va` in `space`: `total` tiles, the first + /// `own` on the title's pages there (shared with every resource of the space on them), the + /// rest its own. None: no video memory for all of them (nothing is kept). + #[allow(clippy::too_many_arguments)] + fn claim(&mut self, space: Space, res: usize, va: usize, own: usize, total: usize, now: std::time::Instant, grow: &mut impl FnMut() -> Option) -> Option> { + self.sweep(now); + let mut tiles = Vec::with_capacity(total); + let mut used = Vec::with_capacity(own.min(total)); + let mut extra = Vec::new(); + for i in 0..total { + let tile = if i < own { + let a = va + i * PAGE; + let tile = match self.pages.get_mut(&(space, a)) { + Some(p) => { + p.users += 1; + p.idle_since = None; + Some(p.tile) + } + None => self.take_tile(now, grow).inspect(|&t| { + self.pages.insert((space, a), Page { tile: t, users: 1, idle_since: None }); + }), + }; + if tile.is_some() { + used.push(a); + } + tile + } else { + self.take_tile(now, grow).inspect(|&t| extra.push(t)) + }; + let Some(t) = tile else { break }; + tiles.push(t); + } + self.users.insert(res, (space, used, extra)); + if tiles.len() < total { + self.release(res, now); + return None; + } + Some(tiles) + } + + /// Resource `res` released: its pages are no longer its. + fn release(&mut self, res: usize, now: std::time::Instant) { + let Some((space, used, extra)) = self.users.remove(&res) else { return }; + for a in used { + if let Some(p) = self.pages.get_mut(&(space, a)) { + p.users = p.users.saturating_sub(1); + if p.users == 0 { + p.idle_since = Some(now); + } + } + } + self.cooling.extend(extra.into_iter().map(|t| (t, now))); + } + + /// bytes of the pages (idle ones included) and own tiles in use + fn bytes(&self) -> usize { + (self.pages.len() + self.users.values().map(|u| u.2.len()).sum::()) * PAGE + } +} + +/// The title's pages of video memory for textures in its memory (see the module's comment). struct Pages { queue: ID3D12CommandQueue, /// signalled after each mapping; title queues wait for it before their next work fence: ID3D12Fence, value: u64, pools: Vec, - free: Vec, - /// tiles given back, reusable after `COOL` - cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, - /// title page address → its video memory - pages: std::collections::HashMap, - /// target → (the title pages it uses, tiles of its own past the title's memory) - targets: std::collections::HashMap, Vec)>, + book: Book, /// queue → the fence value it last waited for waited: std::collections::HashMap, } @@ -213,37 +323,12 @@ impl Pages { } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; - crate::xlog_info!("D3D12.X: GPU-owned textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); - Some(Pages { - queue, - fence, - value: 0, - pools: Vec::new(), - free: Vec::new(), - cooling: std::collections::VecDeque::new(), - pages: std::collections::HashMap::new(), - targets: std::collections::HashMap::new(), - waited: std::collections::HashMap::new(), - }) - } - - /// Pages no target used for `IDLE` go back to the pools. - fn sweep(&mut self, now: std::time::Instant) { - let old: Vec = self.pages.iter().filter(|(_, p)| p.idle_since.is_some_and(|t| now.duration_since(t) >= IDLE)).map(|(&a, _)| a).collect(); - for a in old { - if let Some(p) = self.pages.remove(&a) { - self.cooling.push_back((p.tile, now)); - } - } + crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); + Some(Pages { queue, fence, value: 0, pools: Vec::new(), book: Book::new(), waited: std::collections::HashMap::new() }) } - unsafe fn take_tile(&mut self, dev: &ID3D12Device) -> Option { - if let Some(t) = self.free.pop() { - return Some(t); - } - if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { - return self.cooling.pop_front().map(|(t, _)| t); - } + /// A new pool heap (its index); None: no video memory. + unsafe fn grow(dev: &ID3D12Device, pools: &mut Vec) -> Option { let desc = D3D12_HEAP_DESC { SizeInBytes: POOL_PAGES as u64 * PAGE as u64, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -253,13 +338,11 @@ impl Pages { }; let mut heap: Option = None; if let Err(e) = dev.CreateHeap(&desc, &mut heap) { - crate::xlog_warn!("D3D12.X: no video memory for more pages of GPU-owned textures ({e})"); + crate::xlog_warn!("D3D12.X: no video memory for more pages of textures in title memory ({e})"); return None; } - self.pools.push(heap?); - let h = self.pools.len() as u32 - 1; - self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); - Some((h, 0)) + pools.push(heap?); + Some(pools.len() as u32 - 1) } /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. @@ -308,10 +391,11 @@ fn heap_ranges(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { out } -/// A GPU-owned texture at `va` as a reserved resource on the title's pages there +/// A texture at `va` as a reserved resource on the title's pages there in `space` /// (`console_bytes`: its size on the console – the pages it covers; tiles past them are its -/// own). None: it cannot be (the caller tries an arena). -unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, console_bytes: Option, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { +/// own). None: it cannot be (the caller tries an arena or a resource of its own). +#[allow(clippy::too_many_arguments)] +unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, space: Space, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, console_bytes: Option, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { if va % PAGE != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN { return None; } @@ -323,7 +407,7 @@ unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: if hr < 0 || (*ppv).is_null() { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_info!("D3D12.X: GPU-owned texture at {va:#x} ({}x{}, format {}, {} samples) not reserved ({hr:#x}): in an arena", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); + crate::xlog_info!("D3D12.X: texture at {va:#x} ({space:?}: {}x{}, format {}, {} samples) not reserved ({hr:#x}): not on pages", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); } return None; } @@ -332,63 +416,45 @@ unsafe fn place_on_pages(dev: &ID3D12Device, this: *mut c_void, va: usize, desc: let mut total = 0u32; dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); let own = console_bytes.map_or(total as usize, |b| (b as usize).div_ceil(PAGE)).min(total as usize); - let now = std::time::Instant::now(); - pages.sweep(now); - let mut tiles = Vec::with_capacity(total as usize); - let mut used = Vec::with_capacity(own); - let mut extra = Vec::new(); - for i in 0..total as usize { - let tile = if i < own { - let a = va + i * PAGE; - let tile = match pages.pages.get_mut(&a) { - Some(p) => { - p.users += 1; - p.idle_since = None; - Some(p.tile) - } - None => pages.take_tile(dev).inspect(|&t| { - pages.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - }), - }; - if tile.is_some() { - used.push(a); - } - tile - } else { - pages.take_tile(dev).inspect(|&t| extra.push(t)) - }; - let Some(t) = tile else { break }; - tiles.push(t); - } - pages.targets.insert(raw as usize, (used, extra)); - if tiles.len() < total as usize { - // no video memory for all of it: the target goes (its pages with it) + let Pages { book, pools, .. } = pages; + let Some(tiles) = book.claim(space, raw as usize, va, own, total as usize, std::time::Instant::now(), &mut || Pages::grow(dev, pools)) else { + // no video memory for all of it: the texture goes drop(g); - forget_pages(raw as usize); drop(windows::core::IUnknown::from_raw(raw)); *ppv = std::ptr::null_mut(); return None; - } + }; pages.map(res, &tiles); PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) } -/// A target released: its pages are no longer its. +/// A resource released: its pages are no longer its. fn forget_pages(resource: usize) { let mut g = PAGES.lock().unwrap(); let Some(Some(pages)) = g.as_mut() else { return }; - let Some((used, extra)) = pages.targets.remove(&resource) else { return }; - let now = std::time::Instant::now(); - for a in used { - if let Some(p) = pages.pages.get_mut(&a) { - p.users = p.users.saturating_sub(1); - if p.users == 0 { - p.idle_since = Some(now); - } - } + pages.book.release(resource, std::time::Instant::now()); +} + +/// A texture the title placed at `va` whose texels the CPU writes (kept in step with the memory, +/// `title_textures`) as a reserved resource on the title's pages of such textures (`desc`: the PC +/// description, `console_bytes` its size on the console). A title streams its world by placing +/// new textures over memory it used before – as the console allows: the new texture overwrites +/// the old one's memory – and lets few of the old ones go; a committed texture per placement +/// held the sum of every texture ever placed (a retail game: 12.7 GB of them over 4.0 GB of its +/// memory after 90 s, then the device was removed). On pages they cost the memory they cover. +/// None: not on pages (the caller makes a resource of its own). `XCL_TITLE_TEXTURE_PAGES=0` +/// turns this off. +pub unsafe fn place_title_texture(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, console_bytes: u64, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { + static OFF: std::sync::OnceLock = std::sync::OnceLock::new(); + if *OFF.get_or_init(|| std::env::var("XCL_TITLE_TEXTURE_PAGES").is_ok_and(|v| v.trim() == "0")) { + return None; } - pages.cooling.extend(extra.into_iter().map(|t| (t, now))); + let dev = ID3D12Device::from_raw_borrowed(&this)?; + if !tier2(dev) { + return None; + } + place_on_pages(dev, this, Space::Textures, va, desc, state, std::ptr::null(), Some(console_bytes), riid, ppv) } /// Before a title queue's work: it waits for the pages mapped since its last work. @@ -406,7 +472,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { pub fn page_bytes() -> (usize, usize) { let g = PAGES.lock().unwrap(); let Some(Some(p)) = g.as_ref() else { return (0, 0) }; - (p.pages.len() * PAGE + p.targets.values().map(|t| t.1.len()).sum::() * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + (p.book.bytes(), p.pools.len() * POOL_PAGES as usize * PAGE) } /// Heaps of every kind of resource in one (resource heap tier 2) – else no arenas. @@ -425,7 +491,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st return None; } if std::env::var_os("XCL_VRAM_ARENAS").is_none() { - if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + if let Some(hr) = place_on_pages(dev, this, Space::Targets, va, desc, state, clear, console_bytes, riid, ppv) { return Some(hr); } } @@ -463,6 +529,183 @@ mod tests { assert_eq!(heap_ranges(0, &[(0, 3), (0, 1), (0, 2)]), [(true, 3, 1), (true, 1, 2)]); } + /// A pool-heap maker for `Book` that numbers heaps as they are made. + fn heaps() -> impl FnMut() -> Option { + let mut n = 0; + move || { + n += 1; + Some(n - 1) + } + } + + /// Textures at one address share its pages, an overlapping one the pages they both cover; + /// targets there have pages of their own; tiles past the title's memory are each one's own. + #[test] + fn textures_share_pages_with_textures_not_with_targets() { + let (t, va) = (Instant::now(), 0x2_0000_0000usize); + let mut b = Book::new(); + let mut grow = heaps(); + let a = b.claim(Space::Textures, 1, va, 4, 4, t, &mut grow).unwrap(); + let same = b.claim(Space::Textures, 2, va, 4, 5, t, &mut grow).unwrap(); + assert_eq!(same[..4], a[..], "a texture placed over another one: the same memory"); + assert!(!a.contains(&same[4]), "a tile past the title's memory is its own"); + let over = b.claim(Space::Textures, 3, va + 2 * PAGE, 4, 4, t, &mut grow).unwrap(); + assert_eq!(over[..2], a[2..], "the pages both cover"); + assert!(!a.contains(&over[2]) && !a.contains(&over[3])); + let target = b.claim(Space::Targets, 4, va, 4, 4, t, &mut grow).unwrap(); + assert!(target.iter().all(|x| !a.contains(x) && !over.contains(x)), "a target's pages are not a texture's"); + // 6 texture pages, 4 target pages, 1 own tile + assert_eq!(b.bytes(), 11 * PAGE); + } + + /// The retail game's pattern (#248): textures streamed in over memory used before, nearly + /// none released. Committed, they held the sum of every texture placed; on pages, the memory + /// they cover. + #[test] + fn streamed_textures_cost_the_memory_they_cover() { + const SPAN: usize = 256 * MIB; + let (t, va) = (Instant::now(), 0x3_0000_0000usize); + let mut b = Book::new(); + let mut grow = heaps(); + let mut placed = 0usize; + // 8000 textures of 64 KiB to 4 MiB at page addresses all over the span + let mut x = 0x2545_F491u32; + for res in 0..8000usize { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let pages = 1usize << (x % 7); + let at = (x as usize >> 3) % (SPAN / PAGE - pages) * PAGE; + b.claim(Space::Textures, res, va + at, pages, pages, t, &mut grow).unwrap(); + placed += pages * PAGE; + } + assert!(placed > 30 * SPAN, "the test places {placed} bytes"); + assert!(b.bytes() <= SPAN, "{} bytes of pages for a span of {SPAN}", b.bytes()); + } + + /// A page no resource uses keeps its tile (and what it holds) for 2 s, then the tile cools + /// another 2 s before it is reused; a claim without video memory for all of it keeps nothing. + #[test] + fn released_pages_are_kept_then_cooled_before_reuse() { + let (t, va) = (Instant::now(), 0x4_0000_0000usize); + let s = Duration::from_secs; + let mut b = Book::new(); + let mut grow = heaps(); + let first = b.claim(Space::Textures, 1, va, 1, 1, t, &mut grow).unwrap(); + b.release(1, t); + assert_eq!(b.claim(Space::Textures, 2, va, 1, 1, t + s(1), &mut grow).unwrap(), first, "placed again within 2 s: the same memory"); + b.release(2, t + s(1)); + // the page is let go at 3 s (2 s idle) and its tile cools until 5 s + b.sweep(t + s(3)); + assert!(b.pages.is_empty()); + b.free.clear(); + assert!(b.claim(Space::Textures, 3, va, 1, 1, t + s(4), &mut || None).is_none(), "the tile is still cooling, no new heap"); + assert_eq!(b.claim(Space::Textures, 4, va + PAGE, 1, 1, t + s(5), &mut || None).unwrap(), first, "cooled down: reused"); + // 3 pages wanted, one tile to be had: nothing kept, the tile reusable + b.free.push((7, 7)); + assert!(b.claim(Space::Textures, 5, va + 8 * PAGE, 3, 3, t + s(5), &mut || None).is_none()); + assert!(!b.users.contains_key(&5)); + assert!(b.pages.get(&(Space::Textures, va + 8 * PAGE)).is_some_and(|p| p.users == 0), "its page is idle, not in use"); + } + + /// On the GPU: kept-in-step textures placed at one title address are one memory (an upload + /// through one is what the other reads), and many placements there take one texture's video + /// memory. Needs a hardware adapter with tiled resources tier 2 (skips otherwise). + #[test] + fn title_textures_at_one_address_share_video_memory() { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + eprintln!("SKIPPED title_textures_at_one_address_share_video_memory: software adapter"); + return; + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev.filter(|d| tier2(d)) else { return }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let memory: IDXGIAdapter3 = adapter.cast().unwrap(); + let local = || { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let _ = memory.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut i); + i.CurrentUsage as usize + }; + // RGBA8 512x512, one mip: 1 MiB (16 pages) on the console + let (w, h) = (512u32, 512u32); + let console_bytes = (w * h * 4) as u64; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w as u64, Height: h, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; + let srv = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place_at = |va: usize| { + let mut p = std::ptr::null_mut(); + let hr = place_title_texture(dev.as_raw(), va, &desc, srv.0 as u32, console_bytes, riid, &mut p); + if hr.is_none() { + return None; + } + assert!(hr.is_some_and(|hr| hr >= 0) && !p.is_null(), "texture at {va:#x}"); + Some(ID3D12Resource::from_raw(p)) + }; + let va = 0x60_0000_0000usize; + let Some(a) = place_at(va) else { + eprintln!("SKIPPED title_textures_at_one_address_share_video_memory: no reserved RGBA8 textures"); + return; + }; + let b = place_at(va).unwrap(); + + // texels uploaded through b are what a holds + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + before_execute(&queue); + let texels: Vec = (0..w * h * 4).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + let sub = crate::gpu::texture::Subresource { rows: h as usize, row_bytes: w as usize * 4, depth: 1, data: texels.clone() }; + let failed = crate::gpu::texture::upload_batch(&dev, &queue, &[(b.clone(), vec![sub], vec![srv])]).unwrap(); + assert!(failed.is_empty(), "{failed:?}"); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(&desc, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + let buffer = 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 readback: Option = None; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let barrier = |from: D3D12_RESOURCE_STATES, to: D3D12_RESOURCE_STATES| { + let t = D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(&a), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: from, StateAfter: to }; + D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(t) }, ..Default::default() } + }; + // (tiles shared between two reserved resources: an aliasing barrier between them) + let alias = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { pResourceBefore: std::mem::transmute_copy(&b), pResourceAfter: std::mem::transmute_copy(&a) }) }, ..Default::default() }; + list.ResourceBarrier(&[alias, barrier(srv, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&a), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, srv)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let pitch = fp.Footprint.RowPitch as usize; + let bad = (0..h as usize).filter(|&y| std::slice::from_raw_parts((p as *const u8).add(y * pitch), w as usize * 4) != &texels[y * w as usize * 4..(y + 1) * w as usize * 4]).count(); + readback.Unmap(0, None); + assert_eq!(bad, 0, "rows of the texture placed first that differ from what was uploaded through the second"); + + // 256 more placements at 8 addresses: video memory for 8 textures, not 256 + let used0 = local(); + let pages0 = page_bytes().0; + let more: Vec = (0..256).map(|k| place_at(va + 0x100_0000 + (k % 8) * 0x10_0000).unwrap()).collect(); + let (used, pages) = (local().saturating_sub(used0), page_bytes().0 - pages0); + println!("256 RGBA8 512x512 textures at 8 addresses: {pages} bytes of pages, {used} bytes more local video memory"); + assert!(pages <= 8 * console_bytes as usize + 256 * PAGE, "{pages} bytes of pages"); + assert!(used < 64 * console_bytes as usize, "{used} bytes of video memory"); + drop((more, a, b)); + } + } + /// A placement's arena id, with heaps numbered as they are made. fn take(a: &mut Arenas, va: usize, bytes: usize, align: usize, now: Instant) -> u64 { let n = a.list.len() as u32; diff --git a/crates/xcl/src/hle/user.rs b/crates/xcl/src/hle/user.rs index 030e286..45da60e 100644 --- a/crates/xcl/src/hle/user.rs +++ b/crates/xcl/src/hle/user.rs @@ -71,6 +71,15 @@ unsafe fn name(p: *const u8, keep: &mut Vec>) -> *const u16 { keep.last().unwrap().as_ptr() } +#[link(name = "kernel32")] +extern "system" { + fn GetLastError() -> u32; +} + +/// Atoms this process registered, so a second RegisterClassExA of the same name still returns +/// the atom. Windows answers the second call with 0, and the title stops on that. +static CLASS_ATOMS: std::sync::Mutex, u16)>> = std::sync::Mutex::new(Vec::new()); + pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx) -> u16 { if c.is_null() { return 0; @@ -95,7 +104,28 @@ pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx) -> u16 class_name: name(c.class_name, &mut keep), icon_small: c.icon_small, }; - RegisterClassExW(&w) + let class_key = ((c.class_name as usize) >= 0x1_0000).then(|| keep.last().cloned().unwrap_or_default()).unwrap_or_default(); + if !class_key.is_empty() { + if let Some(atom) = CLASS_ATOMS.lock().unwrap().iter().find(|(n, _)| n == &class_key).map(|(_, a)| *a) { + return atom; + } + } + let atom = RegisterClassExW(&w); + if atom != 0 { + if !class_key.is_empty() { + CLASS_ATOMS.lock().unwrap().push((class_key, atom)); + } + return atom; + } + let err = GetLastError(); + // ERROR_CLASS_ALREADY_EXISTS: the class is registered, the title only tests the atom is non-zero + if err == 1410 { + crate::xlog_info!("user: RegisterClassExA: class already registered"); + return 1; + } + let shown = if class_key.is_empty() { String::new() } else { String::from_utf16_lossy(&class_key) }; + crate::xlog_warn!("user: RegisterClassExA failed ({err}) for '{shown}'"); + 0 } #[allow(clippy::too_many_arguments)] @@ -148,8 +178,14 @@ unsafe fn console_window(ex_style: u32, class: *const u16, title: *const u16, st } let style = style & !WS_FRAME | WS_POPUP; let ex_style = ex_style & !WS_EX_FRAME & !WS_EX_APPWINDOW | WS_EX_TOOLWINDOW; - let hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, parent, menu, instance, param); + let mut hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, parent, menu, instance, param); + if hwnd.is_null() { + let err = GetLastError(); + crate::xlog_warn!("user: CreateWindowEx failed ({err:#x}) style {style:#x} parent {parent:p}; retrying without a parent"); + hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, std::ptr::null_mut(), std::ptr::null_mut(), instance, param); + } if hwnd.is_null() { + crate::xlog_warn!("user: CreateWindowEx retry failed ({:#x})", GetLastError()); return hwnd; } let cloak: i32 = 1; diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d203..5983db3 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -2,8 +2,10 @@ Status: implemented for compute / kernel mode, the mesh (NGG) first pass and ES+GS (`gpu/recomp/emit.rs`, `PRELUDE_X64`); wave64 VS / PS, which cannot be paired, get the values -of the lanes ≥ 32 they read instead (`upper_lanes.rs`, "Vertex and pixel shaders" below). -The native path is untouched: the form below is only +of the lanes ≥ 32 they read instead (`upper_lanes.rs`, "Vertex and pixel shaders" below), and +their whole-wave reductions – those of wave32 VS / PS too – become wave operations +(`reductions.rs`, "Whole-wave reductions" below). +The native path is untouched (but for the VS / PS with a whole-wave reduction): the form below is only generated when the adapter cannot run 64-lane waves (`D3D12_FEATURE_DATA_D3D12_OPTIONS1` `WaveLaneCountMax < 64`, e.g. NVIDIA, whose D3D12 range is 32..32). On such an adapter a `[WaveSize(64)]` compute shader is rejected at PSO creation, so until now wave64 compute @@ -141,9 +143,10 @@ A wave64 program pays one exchange per mask write that is read whole (`v_cmp*` f `s_and_saveexec`, `s_cbranch_vccz`, `s_bcnt1`, …) and per readlane / readfirstlane / ds_bpermute / coherent scalar load, nothing per ALU, memory or DPP instruction, nor for masks read lane by lane (selects, 64-bit carry chains). Wave32 programs and everything on GPUs with 64-lane waves are -unchanged (the HLSL of every native translation the test suite makes is byte-identical). A -wave64 VS / PS pays nothing for a lane ≥ 32 read as a constant (the lane read is skipped) and -one scalar per spill slot read from its shadow. +unchanged (the HLSL of every native translation the test suite makes is byte-identical) – but +for VS / PS with a whole-wave reduction, which become wave operations at every wave size +("Whole-wave reductions"). A wave64 VS / PS pays nothing for a lane ≥ 32 read as a constant +(the lane read is skipped) and one scalar per spill slot read from its shadow. Measured on an RTX 5070 Ti (`bench_split_wave64`, an ignored test): a loop of 8 instructions with one exchange, 2^18 threads × 32 768 iterations, wave32 program (no @@ -204,7 +207,7 @@ wave64 VS / PS (13 210 programs; 749 – 748 PS, 1 VS – were flagged by the ol | pattern | reads | programs (distinct code) | the console lane ≥ 32 holds | before | |---|---|---|---|---| -| whole-wave reduction: the identity into the lanes outside the mask (`v_cndmask` with mask & saved EXEC), DPP8 xor 1 / 2 / 4, row_mirror, `v_permlanex16`, `v_readlane` 32 for the upper half, `v_readlane` 0 for the total; `v_min_u32` (identity -1), `v_max_u32` (0), `v_or_b32` (0) | 1 082 | 436 (434) | the identity | right by chance: NVIDIA reads lane 0 for lane 32, and min / max / or are idempotent (a sum would double) | +| whole-wave reduction: the identity into the lanes outside the mask (`v_cndmask` with mask & saved EXEC), three DPP8 steps, row_mirror, `v_permlanex16`, `v_readlane` 32 for the upper half, `v_readlane` 0 for the total; `v_min_u32` (identity -1), `v_max_u32` (0), `v_or_b32` (0) – now replaced as a whole ("Whole-wave reductions") | 1 082 | 436 (434) | the identity | right by chance: NVIDIA reads lane 0 for lane 32, and min / max / or are idempotent (a sum would double) | | waterfall / uniformity check: `v_readlane v, s` with s = `s_ff1_i32_b64(mask & EXEC)` | 355 | 353 (351) | nothing (the lane is < 32 unless the mask is empty; then 63, never written) | right | | SGPR spill slots: `v_writelane` / `v_readlane` of lanes 0..47 of one VGPR | 200 | 11 | the spilled SGPR | wrong: the write is lost, the read returns another slot (lane & 31) | | `ds_bpermute` | 0 | | | | @@ -253,26 +256,88 @@ identical to the one before In the pack every read resolves: 1 082 constants, 355 unwritten, 3 740 slot reads; none is left unsafe. Only a program with a constant or a slot to read gets the form: the HLSL changes for 613 programs (the 436 reductions and the 287 with spill slots, which overlap), all of -which DXC compiles. Tests on the GPU: `gpu_wave64_ps_whole_wave_reductions` +which DXC compiles – now 287: the reductions' reads are replaced as a whole ("Whole-wave +reductions"). Tests on the GPU: `gpu_wave64_ps_whole_wave_reductions` (the pack's reduction as min and as a sum, and the waterfall read, checked per hardware wave against a console wave of the same lanes), `gpu_wave64_ps_spill_slots` (whole target and a 6-pixel triangle), `gpu_wave64_vs_spill_slots_and_identity` (a wave of 3 vertices). +### Whole-wave reductions + +The console runs whole-wave code in every lane of the wave, inactive ones included; the +translation runs it only in the lanes the PC GPU launched. The pack's whole-wave code is +reductions: the console's compiler turns a wave reduction of a uint (`WaveActiveMin` / `Max` / +`BitOr`) into `s_or_saveexec -1`, a `v_cndmask` that puts x into the lanes of a mask within the +saved EXEC (the live pixels, or the saved EXEC itself) and the op's identity into every other +lane, three DPP8 steps and a row_mirror (each 16-lane row), `v_permlanex16` (the other row of +the 32-lane half), and in a wave64 program `v_readlane` 32 / 0 for the upper half's and the +wave's result (a wave32 program reads lane 0). In a partial wave – a primitive's edge, the last +vertices of a draw – the steps read lanes that were never launched instead of the identity the +console put there, on every GPU and at both wave sizes. Measured on an RTX 5070 Ti: such lanes +read 0, so a min (identity -1) gave 0; max / or (identity 0) were right by chance, except with +helper lanes in the mask (the saved EXEC after `s_wqm`): an or over a 3-quad wave missed two of +its helper pixels (not followed further). + +`reductions.rs` recognises the sequence as a whole – exactly those instructions (with +`s_waitcnt` / `s_nop` / `v_nop` between them), the mask within the saved EXEC, the constant +the op's identity, DPP8 selects that with the row_mirror take in the whole row (followed as the +set of lanes each lane has read: the op is idempotent; the pack's steps read one lane of the +other pair, then of the other quad), no branch into it, EXEC restored right after – and the +emitter replaces it, from the `v_cndmask` to the last `v_readlane`, with wave operations. +`xcl_wave_(x, mask)` gives the op over the mask's lanes of each 16-lane row of the +hardware wave (`WaveActiveMin(row == k ? q : identity)`, q = x in the mask, the identity +elsewhere), and the four rows give every value the steps leave: the upper half's (sH) and the +wave's (sT), vA (the wave's – wave64: in lanes 0..31, the upper half's in 32..63) and vB (the +other row's of its half). A wave operation leaves out lanes that were not launched, which are +never in the mask (it is within the saved EXEC, and EXEC outside whole-wave code holds only +lanes the program was started with), and helper lanes: in a pixel shader q is first the op +over the lane's quad, through quad reads, which see helper lanes. The rows are those of the +hardware wave: a wave64 program's is (the lower part of) its console wave; a 64-lane wave of a +wave32 program holds two console waves, rows 0–1 and 2–3, one per `xcl_half`. So the form is +the same on every GPU and at every wave size, and it replaces the 32-lane form's lane-32 +constant (`upper_lanes`) for these reads. It changes the HLSL GPUs with 64-lane waves get, for +the programs with a reduction. `XCL_NO_WAVE_REDUCTIONS=1` translates each step on its own, as +before (the digests of `retail_wave64_graphics_lane_forms` are then `main`'s). + +`retail_wave_reductions_census` (an ignored test) lists the pack's whole-wave sections, sites +(programs): + +| programs | recognised | min_u32 | max_u32 | or_b32 | +|---|---|---|---|---| +| wave64 VS / PS | all 1 082 (436) | 325 (325) | 322 (322) | 435 (433) | +| wave32 PS | all 2 106 (926) | 588 (588) | 588 (588) | 930 (926) | + +Every lane ≥ 32 read as a constant in the 436 wave64 programs is inside a recognised +reduction; 110 of them still get the 32-lane form, for their spill slots. The HLSL changes for +the 1 362 VS / PS with a reduction (436 wave64, 926 wave32), at every wave size, and for no +other program: `retail_wave64_graphics_lane_forms` with `XCL_FORMS_LIST` (each program's +digests) against `XCL_NO_WAVE_REDUCTIONS=1`. The 32-lane form differs from the native one for +the 287 programs with spill slots only (613 before). DXC compiles all of them. + +A reduction costs four wave reductions (and four quad reads in a pixel shader) instead of +seven lane reads through `rla`, each a wave read, a ballot and eight quad / wave reads in a +pixel shader. Tests on the GPU: `gpu_ps_partial_wave_reductions` – min, max and or of wave64 +and wave32 programs over the odd pixels and over the quads' lanes (the saved EXEC after +`s_wqm`), drawn as the whole target, a 3-quad triangle and a 55-pixel one; every result (sT, +sH, vA, vB) of every pixel against a console wave of the same lanes – and +`gpu_vs_partial_wave_reductions` (a wave of three vertices). Before, on the RTX 5070 Ti: in +every partial wave the min (sT, vA, vB) is 0, and the or over the quads' lanes of the 3-quad +wave misses two helper pixels, at both wave sizes; the vertex wave's min and vB are 0. Full +waves are right either way. + +Compute and mesh programs have the same sequences (wave32 CS: 4 371 of their 4 607 whole-wave +sites, wave64 CS: 94 of 1 148, wave64 MS: 17 of 17), but the translation keeps the steps +there: on a GPU with 32-lane waves a wave64 console wave is two hardware waves (`x64`), which +would need the halves' exchange, and a compute wave is partial only when its group is not a +multiple of the wave size. The other compute sections are sums (`v_add_nc_u32`, `v_add_f32`, +`v_add_f16`, also prefix sums with row shifts), a float min / max whose identity comes from a +VGPR (`v_mov` before the `v_cndmask`) and two `v_and_b32`. + ### What is still not exact -**Lanes the PC did not launch, inside a wave** – on every GPU and wave size, and before this -change too. The console runs whole-wave code in all 64 lanes, inactive ones included; the -translation runs it only in the lanes the PC GPU launched. In a partial wave, the reduction's -DPP / `v_permlanex16` steps read lanes that were never launched (undefined) instead of the -identity the console put there – not only lanes 32..63. The lanes ≥ 32 of a 32-lane wave are -handled above because they are all missing and all hold the identity; a lane missing among -launched ones holds a partial result that the translation does not have. Making that exact -needs the reduction recognised as a whole (`WaveActiveMin` / `Max` / `BitOr` over the -launched lanes, with the identity for the lanes outside the mask) – not done. Measured on an -RTX 5070 Ti (the reduction of `gpu_wave64_ps_whole_wave_reductions` drawn as a 3-quad -triangle, lanes 12..31 not launched): those lanes read 0, so a min reduction (identity -1) -gives 0, while max / or / sum (identity 0) and the waterfall read are right. 325 of the 436 -reduction programs have a min reduction (322 a max, 433 an or). +Whole-wave code other than the recognised reductions still reads lanes the PC did not launch +in a partial wave: the compute / mesh sections above, and anything a program would do under +`s_or_saveexec -1` in another form (none in the pack's VS / PS). Spill slots of lanes that were not launched are also still lost in the native form (GPUs with 64-lane waves, which keep the HLSL as it was), and in the 32-lane form for slots ≥ 32 when the diff --git a/scripts/check_content.py b/scripts/check_content.py new file mode 100644 index 0000000..171fd91 --- /dev/null +++ b/scripts/check_content.py @@ -0,0 +1,122 @@ +"""Content gate for pull requests: fails when a change adds what this repository must never hold. + +Run by CI on the files a pull request changes (python -I scripts/check_content.py --base origin/main), or by hand +on the whole tree (no --base). Standard library only. Exit 0 = clean, 1 = findings (one line each), 2 = usage. + +Checks, on added or modified files only: + - binaries: Windows PE (MZ ... PE), ELF, and archive/media containers by magic, wherever they are named; + - file types that are game material here: .exe .dll .rpf .xvd .bk2 .awc .dxbc .dxil .spv .ytd .ydr .pak ...; + - any file over 1 MiB, outside the allow list below; + - commercial title names in text (the project writes "a newer retail title"); + - new HTTP/TLS/telemetry crates in Cargo.lock (the code must not go online). +""" +import argparse +import os +import re +import subprocess +import sys + +MAX_BYTES = 1 << 20 +# Synthetic fixtures that are allowed to be binary (tests build them by hand). Paths relative to the root. +ALLOWED_BINARY_PREFIXES = ("tests/data/testgame/",) +BANNED_EXTENSIONS = { + ".exe", ".dll", ".sys", ".rpf", ".xvd", ".xvc", ".msixvc", ".appx", ".bk2", ".bik", ".awc", ".xma", ".dxbc", + ".dxil", ".spv", ".cso", ".ytd", ".ydr", ".ydd", ".yft", ".ybn", ".ymap", ".ytyp", ".pak", ".pdb", +} +MAGIC = [ + (b"MZ", "Windows executable (MZ)"), + (b"\x7fELF", "ELF executable"), + (b"RPF", "RPF archive"), + (b"DXBC", "DXBC shader container"), + (b"\x03\x02\x23\x07", "SPIR-V module"), + (b"BIK", "Bink video"), + (b"KB2", "Bink 2 video"), + (b"PK\x03\x04", "ZIP archive"), + (b"7z\xbc\xaf\x27\x1c", "7-Zip archive"), + (b"Rar!", "RAR archive"), +] +TITLE_NAMES = re.compile( + r"grand\s+theft\s+auto|\bgta\s*(?:v|vi|5|6|online)\b|rockstar\s+games|\bcyberleek\b|game_scarlett_master", + re.IGNORECASE) +NETWORK_CRATES = { + "reqwest", "ureq", "hyper", "curl", "curl-sys", "isahc", "attohttpc", "surf", "native-tls", "rustls", + "openssl", "openssl-sys", "tungstenite", "tokio-tungstenite", "sentry", "opentelemetry", "h2", "quinn", +} +TEXT_EXTENSIONS = {".rs", ".md", ".toml", ".py", ".ps1", ".yml", ".yaml", ".txt", ".json", ".hlsl", ".cfg", ".bat", + ".cmd", ".sh", ".lock"} +SELF = "scripts/check_content.py" + + +def git(*args: str) -> str: + return subprocess.run(["git", *args], check=True, capture_output=True, text=True).stdout + + +def changed_files(base: str) -> list[str]: + out = git("diff", "--name-only", "--diff-filter=AMR", "-z", f"{base}...HEAD") + return [p for p in out.split("\0") if p] + + +def all_files() -> list[str]: + return [p for p in git("ls-files", "-z").split("\0") if p] + + +def crates(lock_text: str) -> set[str]: + return set(re.findall(r'^name = "([^"]+)"', lock_text, re.MULTILINE)) + + +def check_file(path: str) -> list[str]: + findings = [] + if not os.path.isfile(path): + return findings + rel = path.replace("\\", "/") + allowed_binary = rel.startswith(ALLOWED_BINARY_PREFIXES) + ext = os.path.splitext(rel)[1].lower() + size = os.path.getsize(path) + if ext in BANNED_EXTENSIONS and not allowed_binary: + findings.append(f"{rel}: file type {ext} is not allowed in this repository") + if size > MAX_BYTES and not allowed_binary: + findings.append(f"{rel}: {size} bytes, over the {MAX_BYTES}-byte limit") + with open(path, "rb") as f: + head = f.read(4096) + if not allowed_binary: + for magic, what in MAGIC: + if head.startswith(magic): + if magic == b"MZ" and b"PE\0\0" not in head: + continue + findings.append(f"{rel}: looks like a {what}") + break + if ext in TEXT_EXTENSIONS and rel != SELF and size <= 4 * MAX_BYTES: + with open(path, encoding="utf-8", errors="replace") as f: + for number, line in enumerate(f, 1): + m = TITLE_NAMES.search(line) + if m: + findings.append(f"{rel}:{number}: names a commercial title ({m.group(0)!r}); " + "write \"a newer retail title\"") + return findings + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--base", help="compare against this ref (merge base); without it the whole tree is checked") + a = ap.parse_args() + files = changed_files(a.base) if a.base else all_files() + findings = [] + for path in files: + findings.extend(check_file(path)) + if a.base and "Cargo.lock" in files: + try: + before = crates(git("show", f"{a.base}:Cargo.lock")) + except subprocess.CalledProcessError: + before = set() + with open("Cargo.lock", encoding="utf-8") as f: + added = crates(f.read()) - before + for name in sorted(added & NETWORK_CRATES): + findings.append(f"Cargo.lock: adds network crate {name!r}; the code must not go online") + for line in findings: + print(line) + print(f"check_content: {len(files)} files checked, {len(findings)} findings") + return 1 if findings else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/merge_ready.py b/scripts/merge_ready.py new file mode 100644 index 0000000..f56aa61 --- /dev/null +++ b/scripts/merge_ready.py @@ -0,0 +1,108 @@ +"""Lists and merges pull requests that are ready: open, not draft, mergeable, every check passed or skipped, +no review asking for changes. Needs the GitHub CLI (gh) logged in with write access. Standard library only. + + python -I scripts/merge_ready.py # dry run: the ready list and why the rest wait + python -I scripts/merge_ready.py --merge 50 # squash-merge up to 50 ready PRs, oldest first + python -I scripts/merge_ready.py --merge 50 --approved # only PRs with an approving review + +A PR whose merge fails (a conflict that appeared after an earlier merge) is skipped and reported; the run goes on. +Every decision goes to merge_ready.log (append) as one line: time, PR, action, reason. +""" +import argparse +import datetime +import json +import subprocess +import sys +import time + +OK_STATES = {"SUCCESS", "SKIPPED", "NEUTRAL"} +FIELDS = "number,title,author,isDraft,mergeable,reviewDecision,statusCheckRollup,baseRefName,createdAt,labels" + + +def gh(*args: str) -> str: + return subprocess.run(["gh", *args], check=True, capture_output=True, text=True).stdout + + +def check_state(pr: dict) -> tuple[bool, str]: + checks = pr.get("statusCheckRollup") or [] + if not checks: + return False, "no checks yet" + for c in checks: + state = (c.get("conclusion") or c.get("state") or c.get("status") or "").upper() + name = c.get("name") or c.get("context") or "?" + if state in ("", "PENDING", "QUEUED", "IN_PROGRESS", "EXPECTED", "WAITING", "ACTION_REQUIRED"): + return False, f"check {name} {state.lower() or 'pending'}" + if state not in OK_STATES: + return False, f"check {name} {state.lower()}" + return True, "checks green" + + +def readiness(pr: dict, base: str, approved_only: bool) -> tuple[bool, str]: + if pr["baseRefName"] != base: + return False, f"targets {pr['baseRefName']}" + if pr["isDraft"]: + return False, "draft" + if any(l["name"] in ("do-not-merge", "blocked") for l in pr.get("labels") or []): + return False, "labelled do-not-merge" + if pr["mergeable"] != "MERGEABLE": + return False, f"mergeable={pr['mergeable'].lower()}" + if pr["reviewDecision"] == "CHANGES_REQUESTED": + return False, "changes requested" + if approved_only and pr["reviewDecision"] != "APPROVED": + return False, "not approved" + return check_state(pr) + + +def log(line: str) -> None: + stamp = datetime.datetime.now().isoformat(timespec="seconds") + with open("merge_ready.log", "a", encoding="utf-8") as f: + f.write(f"{stamp} {line}\n") + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--repo", default="T-Crypt/bathyal") + ap.add_argument("--base", default="main") + ap.add_argument("--merge", type=int, default=0, metavar="N", help="merge up to N ready PRs (default: dry run)") + ap.add_argument("--approved", action="store_true", help="only PRs with an approving review") + ap.add_argument("--limit", type=int, default=2000, help="open PRs to read") + ap.add_argument("--pause", type=float, default=2.0, help="seconds between merges (API rate)") + a = ap.parse_args() + + prs = json.loads(gh("pr", "list", "-R", a.repo, "--state", "open", "--limit", str(a.limit), "--json", FIELDS)) + prs.sort(key=lambda p: p["createdAt"]) + ready, waiting = [], {} + for pr in prs: + ok, why = readiness(pr, a.base, a.approved) + if ok: + ready.append(pr) + else: + waiting.setdefault(why.split(" ")[0] if why.startswith("check") else why, []).append(pr["number"]) + print(f"{len(prs)} open, {len(ready)} ready") + for why, nums in sorted(waiting.items(), key=lambda kv: -len(kv[1])): + print(f" waiting ({why}): {len(nums)} e.g. #{', #'.join(map(str, nums[:5]))}") + if not a.merge: + for pr in ready[:20]: + print(f" ready #{pr['number']} {pr['author']['login']}: {pr['title'][:80]}") + return 0 + + merged, failed = 0, 0 + for pr in ready[: a.merge]: + n = str(pr["number"]) + try: + gh("pr", "merge", n, "-R", a.repo, "--squash") + merged += 1 + log(f"#{n} merged ({pr['author']['login']}: {pr['title'][:80]})") + print(f"merged #{n}") + except subprocess.CalledProcessError as e: + failed += 1 + reason = (e.stderr or "").strip().splitlines()[-1:] or ["unknown"] + log(f"#{n} skipped: {reason[0][:160]}") + print(f"skipped #{n}: {reason[0][:160]}") + time.sleep(a.pause) + print(f"merged {merged}, skipped {failed}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 new file mode 100644 index 0000000..a4f668a --- /dev/null +++ b/scripts/smoke.ps1 @@ -0,0 +1,64 @@ +# Regression run of a title for a pull request: runs it for a fixed time, reads XCL's log and +# prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built +# from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). +# +# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] +# +# Networking is off (XCL_NETWORK=0). Build first: cargo build --release -p xcl +param( + [Parameter(Mandatory = $true)][string]$Game, + [int]$Seconds = 60, + [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe') +) +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path $Xcl)) { throw "no $Xcl - build it first (cargo build --release -p xcl)" } +$root = Split-Path $PSScriptRoot -Parent +$commit = (git -C $root rev-parse HEAD).Trim() +$dirty = [bool](git -C $root status --porcelain --untracked-files=no -- crates Cargo.toml Cargo.lock) + +$out = New-TemporaryFile +$err = New-TemporaryFile +$env:XCL_NETWORK = '0' +$env:XCL_RUN_SECONDS = "$Seconds" +$env:XCL_ACTIVITY = '1' +$p = Start-Process -FilePath $Xcl -ArgumentList @('run', "`"$Game`"") -NoNewWindow -PassThru -RedirectStandardOutput $out -RedirectStandardError $err +$null = $p.Handle # (without it ExitCode stays empty) +if (-not $p.WaitForExit(($Seconds + 120) * 1000)) { + Stop-Process -Id $p.Id -Force + $timedOut = $true +} +Remove-Item Env:XCL_RUN_SECONDS, Env:XCL_ACTIVITY + +$stdout = Get-Content $out -Raw -Encoding utf8 +Remove-Item $out, $err +$logLine = ($stdout -split "`n" | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) +if (-not $logLine) { throw "XCL printed no log path; its output:`n$stdout" } +$log = ($logLine -replace '^Log:\s+', '').Trim() +$text = Get-Content $log -Raw -Encoding utf8 + +$frames = if ($text -match '\((\d+) frames shown, (\d+) PresentX calls\)') { "$($Matches[1]) (PresentX $($Matches[2]))" } else { 'none logged (the run did not reach its end)' } +$presents = [regex]::Matches($text, 'activity \(2 s\): (\d+) presents') | ForEach-Object { [int]$_.Groups[1].Value } +$lastPresents = ($presents | Select-Object -Last 3) -join ' ' +$commits = [regex]::Matches($text, 'memory: (\d+) MB committed') | ForEach-Object { [int]$_.Groups[1].Value } +$peak = if ($commits) { ($commits | Measure-Object -Maximum).Maximum } else { 'n/a' } +$removals = ([regex]::Matches($text, 'device removed')).Count +$crashes = ([regex]::Matches($text, 'unhandled exception|process ends with status')).Count +$gpu = (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1).Name +$code = if ($timedOut) { 'killed (no exit)' } else { '0x{0:x}' -f $p.ExitCode } + +@" +`````` +xcl-smoke v1 +commit: $commit$(if ($dirty) { ' (uncommitted changes)' }) +gpu: $gpu +title: $(Split-Path $Game -Leaf) +seconds: $Seconds +exit: $code +frames shown: $frames +presents per 2 s (last 3): $lastPresents +device removals: $removals +crashes: $crashes +peak commit: $peak MB +`````` +"@ From 0e946cfc68244edee1fba6e0425371f687a05ccd Mon Sep 17 00:00:00 2001 From: ivall Date: Mon, 23 Nov 2026 23:39:22 +0100 Subject: [PATCH 07/34] PR checks: only the PR's own run must be clean, main's run must be from main; game data refused From a review of the check: it looked for crashes and device removals anywhere in the description, so a PR fixing a crash on main failed on main's run, and nothing made the two runs come from different commits. The checker is now scripts/pr_check.py: the PR's xcl-smoke block must be its head commit with no uncommitted changes, the other a commit on main (the compare API), both of the same title for the same time; crashes and device removals count in the PR's run only, which must keep 80 % of main's frames and stay under 125 % of its peak commit. The workflow runs as pull_request_target with main's checker: a PR can no longer change what checks it, and nothing of the PR is checked out or run (only its description and file list are read through the API). Game data: .gitignore keeps game packages, archives, executables, video, audio banks, textures and dumps out, and the check refuses a PR adding one, a MicrosoftGame.config other than the test title's, or any binary outside tests/data/ or over 1 MB. --- .github/workflows/pr-check.yml | 64 +++++--------- .gitignore | 44 ++++++++++ CONTRIBUTING.md | 17 ++-- scripts/pr_check.py | 148 +++++++++++++++++++++++++++++++++ 4 files changed, 222 insertions(+), 51 deletions(-) create mode 100644 scripts/pr_check.py diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml index 6850fdc..a5d88d2 100644 --- a/.github/workflows/pr-check.yml +++ b/.github/workflows/pr-check.yml @@ -1,13 +1,15 @@ -# The description a pull request needs before it can be merged (CONTRIBUTING.md, "What a PR -# needs to be merged"): the Tested / Not tested / AI use sections, and – when it changes the -# runtime (crates/xcl/src outside tests) – two `xcl-smoke` blocks from scripts/smoke.ps1, one of -# them made on the PR's head commit with no uncommitted changes. AI use must not name a small or -# open-weight model (CONTRIBUTING.md, "AI-assisted contributions"). Runs again when the -# description is edited or a commit is pushed. +# What a pull request needs before it can be merged (CONTRIBUTING.md, "What a PR needs to be +# merged"), checked by scripts/pr_check.py from the PR's description and files: the Tested / Not +# tested / AI use sections, no small / open-weight model named in AI use, no game data or +# binaries, and – when it changes the runtime – `xcl-smoke` runs on main and on the PR's head. +# +# pull_request_target: the workflow and the checker are main's (a PR cannot change what checks +# it). Nothing of the PR is checked out or run – only its description and file list are read +# through the API – so its code never runs with this token. name: PR checks on: - pull_request: + pull_request_target: types: [opened, edited, synchronize, reopened, ready_for_review] permissions: @@ -19,7 +21,12 @@ jobs: name: PR description runs-on: ubuntu-latest steps: - - name: Check the description + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.base.sha }} + sparse-checkout: scripts/pr_check.py + sparse-checkout-cone-mode: false + - name: Check the description and files env: GH_TOKEN: ${{ github.token }} BODY: ${{ github.event.pull_request.body }} @@ -27,40 +34,7 @@ jobs: NUMBER: ${{ github.event.pull_request.number }} REPO: ${{ github.repository }} run: | - gh api "repos/$REPO/pulls/$NUMBER/files" --paginate --jq '.[].filename' > files.txt - python3 - <<'EOF' - import os, re, sys - body = (os.environ.get("BODY") or "").replace("\r\n", "\n") - head = os.environ["HEAD"] - files = open("files.txt").read().split() - problems = [] - for section in ("Tested", "Not tested", "AI use"): - if not re.search(r"\*\*" + section + r"\*\*\s*\n\s*\S", body): - problems.append(f"the **{section}** section is missing or empty") - def runtime(f): - return f.startswith("crates/xcl/src/") and "/tests" not in f and not f.endswith("tests.rs") - if any(runtime(f) for f in files): - blocks = re.findall(r"xcl-smoke v1\s*\ncommit: (\S+)(.*)", body) - if len(blocks) < 2: - problems.append("the PR changes the runtime: **Regression run** needs two `xcl-smoke` blocks " - "(scripts/smoke.ps1 built from main and from this PR's head commit)") - elif not any(head.startswith(c) and "uncommitted" not in rest for c, rest in blocks): - problems.append(f"no `xcl-smoke` block was made on this PR's head commit {head[:12]} without " - "uncommitted changes - rerun scripts/smoke.ps1 after the last push") - for key in ("device removals", "crashes"): - for n in re.findall(key + r": (\d+)", body): - if int(n) > 0: - problems.append(f"a regression run shows {key}: {n}") - # small / open-weight models are not accepted (CONTRIBUTING.md, "AI-assisted contributions") - ai = re.search(r"\*\*AI use\*\*(.*?)(\n\*\*|\Z)", body, re.S) - banned = re.findall(r"\b(qwen|deepseek|llama|mistral|mixtral|gemma|phi-?\d)", ai.group(1), re.I) if ai else [] - if banned: - problems.append("**AI use** names a model this repository does not accept for code (" - + ", ".join(sorted({b.lower() for b in banned})) + "): see CONTRIBUTING.md") - if problems: - print("This PR cannot be merged yet (see CONTRIBUTING.md, 'What a PR needs to be merged'):") - for p in problems: - print(" -", p) - sys.exit(1) - print("description ok") - EOF + printf '%s' "$BODY" > body.md + gh api "repos/$REPO/pulls/$NUMBER/files" --paginate \ + --jq '.[] | [.filename, .status, ((.patch == null) and (.changes == 0)), .sha] | @tsv' > files.tsv + python3 scripts/pr_check.py --body body.md --head "$HEAD" --files files.tsv --repo "$REPO" diff --git a/.gitignore b/.gitignore index ea8c4bf..db3c979 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,45 @@ /target + +# Game data never goes into the repository (CONTRIBUTING.md, "Licence and provenance"): game +# packages and archives, console executables and libraries, video, audio banks, textures, dumps. +# XCL's own synthetic test data lives in tests/data/ and is listed explicitly below. +*.rpf +*.xvd +*.xvc +*.msixvc +*.appx +*.msix +*.appxbundle +*.xex +*.xbe +*.pak +*.bk2 +*.bik +*.ttpf +*.dds +*.ktx +*.ktx2 +*.wem +*.bnk +*.exe +*.dll +*.pdb +*.sys +*.dmp +*.mdmp +*.iso +*.pkg +*.xsp +*.cab +MicrosoftGame.config +appxmanifest.xml +resources.pri +!tests/data/testgame/MicrosoftGame.config + +# XCL's run output (logs, reports, frame dumps, shader dumps) +*.log +report.json +frame_*.bmp + +# Python bytecode of the scripts +__pycache__/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7d29342..e5c18f5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,15 +19,20 @@ checked before anything else; a PR that does not meet them waits (or is closed a (`cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored, and the SKIPPED tests). 3. **A PR that changes the runtime** (`crates/xcl/src` outside tests) **has a regression run on a real title**: `scripts/smoke.ps1 -Game ` built from `main` and built from the PR's head - commit, both `xcl-smoke` blocks pasted under **Regression run**. The PR's block must name its head - commit with no uncommitted changes: rerun it after every push. It must show no device removal and - no crash, at least as many frames as `main` and no much higher peak commit. A run on a title that - does not reach the code the PR changes still counts as a regression check; say what it does not - cover under **Not tested**. + commit, both `xcl-smoke` blocks pasted under **Regression run**, of the same title for the same + time. The PR's block must name its head commit with no uncommitted changes (rerun it after every + push); the other must be made on a commit of `main`. The PR's run must show no device removal and + no crash (the `main` run may: a PR that fixes a crash shows it there), at least 80 % of `main`'s + frames and at most 125 % of its peak commit. A run on a title that does not reach the code the PR + changes still counts as a regression check; say what it does not cover under **Not tested**. + `scripts/pr_check.py` checks all of this (and the rest of this list it can see) on every PR. 4. **No regression on the maintainer's run.** The maintainer merges in batches: the whole suite and a retail title run again on the merged tree, on an AMD RDNA4 GPU. A PR that breaks either is taken out of the batch and gets a comment with what failed. -5. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and +5. **No game data.** No file of a game package (archives, executables, video, audio banks, textures, + `MicrosoftGame.config`, dumps) and no binary outside `tests/data/` or over 1 MB; `.gitignore` keeps + the usual ones out and the check refuses the rest. +6. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and scope rules below. A PR that duplicates one already merged is closed. A test result that was not produced by a real run on the hardware named gets the PR closed. diff --git a/scripts/pr_check.py b/scripts/pr_check.py new file mode 100644 index 0000000..b834254 --- /dev/null +++ b/scripts/pr_check.py @@ -0,0 +1,148 @@ +"""What a pull request needs before it can be merged (CONTRIBUTING.md, "What a PR needs to be +merged"), checked from its description and its files – run by .github/workflows/pr-check.yml +(`pull_request_target`: this file as it is on main, never the PR's copy) and locally: + + python scripts/pr_check.py --body body.md --head --files files.tsv [--local] + +files.tsv: one line per file of the PR – path, status, binary (true/false), blob sha. --local +asks git instead of the GitHub API (whether a commit is on main, a blob's size). +""" +import argparse, os, re, subprocess, sys + +SECTIONS = ("Tested", "Not tested", "AI use") +# small / open-weight models are not accepted for code (CONTRIBUTING.md, "AI-assisted contributions") +BANNED_MODELS = r"\b(qwen|deepseek|llama|mistral|mixtral|gemma|phi-?\d)" +# game data never goes into the repository (CONTRIBUTING.md, "Licence and provenance") +GAME_DATA = re.compile( + r"\.(rpf|xvd|xvc|msixvc|appx|msix|appxbundle|xex|xbe|pak|bk2|bik|ttpf|dds|ktx2?|wem|bnk|" + r"exe|dll|pdb|sys|dmp|mdmp|bin|dat|img|iso|pkg|xsp|cab)$", re.I) +GAME_FILES = re.compile(r"(^|/)(MicrosoftGame\.config|appxmanifest\.xml|resources\.pri)$", re.I) +# where test data of XCL's own may live (synthetic, small) +TEST_DATA = ("tests/data/",) +MAX_BINARY = 1 << 20 +FRAMES_KEPT = 0.8 # the PR's frames at least this share of main's +COMMIT_GROWTH = 1.25 # the PR's peak commit at most this times main's + + +def smoke_blocks(body): + """The `xcl-smoke v1` blocks of `body`: each a dict of its `key: value` lines.""" + out = [] + for m in re.finditer(r"xcl-smoke v1\s*\n(.*?)(?:```|\Z)", body, re.S): + block = {} + for line in m.group(1).splitlines(): + k, sep, v = line.partition(":") + if sep: + block[k.strip()] = v.strip() + out.append(block) + return out + + +def number(s): + m = re.match(r"\s*(\d+)", s or "") + return int(m.group(1)) if m else None + + +def runtime(path): + return path.startswith("crates/xcl/src/") and "/tests" not in path and not path.endswith("tests.rs") + + +def check(body, head, files, is_main_ancestor): + """The problems (empty: mergeable as far as this check goes). `files`: (path, status, binary, + size) with `size` a function giving the file's bytes; `is_main_ancestor(sha)`: whether the + commit is on main.""" + body = body.replace("\r\n", "\n") + problems = [] + for section in SECTIONS: + if not re.search(r"\*\*" + section + r"\*\*\s*\n\s*\S", body): + problems.append(f"the **{section}** section is missing or empty") + + ai = re.search(r"\*\*AI use\*\*(.*?)(\n\*\*|\Z)", body, re.S) + banned = re.findall(BANNED_MODELS, ai.group(1), re.I) if ai else [] + if banned: + problems.append("**AI use** names a model this repository does not accept for code (" + + ", ".join(sorted({b.lower() for b in banned})) + "): see CONTRIBUTING.md") + + for path, status, binary, size in files: + if status == "removed": + continue + in_test_data = path.startswith(TEST_DATA) and size() <= MAX_BINARY + if GAME_FILES.search(path) and path != "tests/data/testgame/MicrosoftGame.config": + problems.append(f"`{path}` is a game package file: game files never go into the repository") + elif GAME_DATA.search(path) and not in_test_data: + problems.append(f"`{path}` looks like game data or a binary: game files never go into the repository") + elif binary and not in_test_data: + problems.append(f"`{path}` is a binary file outside tests/data/ or over 1 MB") + + if any(runtime(p) for p, *_ in files): + blocks = smoke_blocks(body) + mine = [b for b in blocks if len(b.get("commit", "")) >= 7 and head.startswith(b["commit"].split()[0])] + clean = [b for b in mine if "uncommitted" not in b.get("commit", "")] + base = [b for b in blocks if b not in mine and len(b.get("commit", "").split()[0] if b.get("commit") else "") >= 7] + if not clean: + problems.append(f"the PR changes the runtime: **Regression run** needs an `xcl-smoke` block made on this PR's " + f"head commit {head[:12]} with no uncommitted changes (rerun scripts/smoke.ps1 after every push)") + main = [b for b in base if is_main_ancestor(b["commit"].split()[0])] + if not main: + problems.append("**Regression run** needs an `xcl-smoke` block made on a commit of main (not the PR's), " + "with the same title and time as the PR's") + if clean: + pr = clean[-1] + for key in ("device removals", "crashes"): + if (number(pr.get(key)) or 0) > 0: + problems.append(f"the PR's regression run shows {key}: {pr.get(key)}") + if pr.get("exit", "").startswith("killed"): + problems.append("the PR's regression run did not end by itself (killed)") + if main: + m = next((b for b in main if b.get("title") == pr.get("title") and b.get("seconds") == pr.get("seconds")), None) + if m is None: + problems.append("the main and PR regression runs are not of the same title for the same time") + else: + pf, mf = number(pr.get("frames shown")), number(m.get("frames shown")) + if mf and (pf is None or pf < FRAMES_KEPT * mf): + problems.append(f"the PR's run shows fewer frames than main's ({pf} against {mf})") + pc, mc = number(pr.get("peak commit")), number(m.get("peak commit")) + if pc and mc and pc > COMMIT_GROWTH * mc: + problems.append(f"the PR's run commits much more memory than main's ({pc} MB against {mc} MB)") + return problems + + +def main(): + a = argparse.ArgumentParser() + a.add_argument("--body", required=True) + a.add_argument("--head", required=True) + a.add_argument("--files", required=True) + a.add_argument("--repo", default=os.environ.get("REPO", "")) + a.add_argument("--local", action="store_true") + o = a.parse_args() + body = open(o.body, encoding="utf-8").read() + def blob_size(sha): + if o.local: + r = subprocess.run(["git", "cat-file", "-s", sha], capture_output=True, text=True) + else: + r = subprocess.run(["gh", "api", f"repos/{o.repo}/git/blobs/{sha}", "--jq", ".size"], capture_output=True, text=True) + return int(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip().isdigit() else 1 << 62 + + files = [] + for line in open(o.files, encoding="utf-8"): + parts = line.rstrip("\r\n").split("\t") + if len(parts) >= 4: + sha = parts[3] + files.append((parts[0], parts[1], parts[2] == "true", lambda sha=sha: blob_size(sha))) + + def is_main_ancestor(sha): + if o.local: + return subprocess.run(["git", "merge-base", "--is-ancestor", sha, "origin/main"], capture_output=True).returncode == 0 + r = subprocess.run(["gh", "api", f"repos/{o.repo}/compare/{sha}...main", "--jq", ".status"], capture_output=True, text=True) + return r.returncode == 0 and r.stdout.strip() in ("ahead", "identical") + + problems = check(body, o.head, files, is_main_ancestor) + if problems: + print("This PR cannot be merged yet (see CONTRIBUTING.md, 'What a PR needs to be merged'):") + for p in problems: + print(" -", p) + sys.exit(1) + print("description ok") + + +if __name__ == "__main__": + main() From 469c1cabeb0a645521231d7bee65ed80d6e2e709 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:39:30 -0700 Subject: [PATCH 08/34] Rect lists: the GS carries flat outputs, v0 the provoking vertex From ivall/xcl#293 by @Kalmarv, squashed. --- crates/xcl/src/gpu/recomp/emit.rs | 61 +++++++++++-------- crates/xcl/src/gpu/recomp/pso.rs | 31 +--------- crates/xcl/src/gpu/recomp/runner.rs | 60 +++++++++++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 90 ++++++++++++++++++++++------- crates/xcl/src/hle/d3d12x/real.rs | 11 +--- 5 files changed, 165 insertions(+), 88 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index e353c1f..57a6499 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4865,40 +4865,53 @@ fn out_struct(h: &mut String, name: &str, outputs: &[SigElement]) { /// two is not always the same vertex: Mesa's radeonsi blits send (x1,y1), (x1,y2), (x2,y1) – v0 /// – and xf86-video-ati's r600 EXA (x1,y1), (x1,y2), (x2,y2) – v1. The corner is the vertex /// sharing x with one of the others and y with the other; the fourth vertex is the opposite -/// corner, a + b - corner, with every output taken the same way (both drivers' texture +/// corner, a + b - corner, with every float output taken the same way (both drivers' texture /// coordinates rely on the implied corner continuing them linearly). Only for three vertices /// with one positive w – then a + b - corner is the same in clip and screen space and every /// interpolation mode agrees; three that are not such corners, or differ in w, stay the one -/// triangle they make. Refused (Err): integer outputs, which are flat – which vertex of a rect -/// gives a flat value is not established, so neither is how the two halves would carry it -/// (the PS side: `pso::ps_reads_flat`). -pub fn rect_list_gs(outputs: &[SigElement]) -> Result { - if let Some(e) = ranked(outputs, true).iter().find(|e| hlsl_type(e) != "float") { - return Err(format!("{} is an integer output (flat)", e.semantic())); - } +/// triangle they make. +/// +/// Flat values are the rect's first vertex's: both triangles start with v[0], which is where +/// the PC takes a flat input from (an integer input, or what the translation declares +/// `nointerpolation` for `v_interp_mov_f32`), and the fourth vertex's integer outputs are +/// v[0]'s. On the console the first vertex is the provoking one of every primitive under +/// D3D's setting – AMD's register references (R6xx, SI, CIK), PA_SU_SC_MODE_CNTL +/// .PROVOKING_VTX_LAST: "Defines which vertex of a primitive is used for attribute components +/// when flat shading is enabled", "0 = First Vtx (D3D)"; the Evergreen / Cayman programming +/// guide, 5.2: a flat attribute is the provoking vertex's value with gradients of 0. Neither +/// says so of a rect in particular, and it is not measured on one. +pub fn rect_list_gs(outputs: &[SigElement]) -> String { let mut h = String::new(); h.push_str("// generated by XCL: a console rect list's rectangles (three corners, the fourth implied)\n"); out_struct(&mut h, "XclOut", outputs); h.push_str("[maxvertexcount(6)]\nvoid main(triangle XclOut v[3], inout TriangleStream s)\n{\n"); - h.push_str(" s.Append(v[0]);\n s.Append(v[1]);\n s.Append(v[2]);\n"); - h.push_str(" if (!(v[0].pos.w > 0.0 && v[1].pos.w == v[0].pos.w && v[2].pos.w == v[0].pos.w))\n return;\n"); + // the corner c: x shared with a and y with b, or the other way round (a = c + 1, b = c + 2); // one w: clip-space x and y compare as the screen's do - h.push_str(" float2 q[3] = { v[0].pos.xy, v[1].pos.xy, v[2].pos.xy };\n"); - // the corner c: x shared with a and y with b, or the other way round (a = c + 1, b = c + 2) - h.push_str(" uint c = 3u;\n [unroll] for (uint i = 0u; i < 3u; i++) {\n"); - h.push_str(" float2 p = q[i], a = q[(i + 1u) % 3u], b = q[(i + 2u) % 3u];\n"); - h.push_str(" bool corner = (p.x == a.x && p.y == b.y) || (p.x == b.x && p.y == a.y);\n"); - h.push_str(" bool degenerate = all(p == a) || all(p == b) || all(a == b);\n"); - h.push_str(" if (c == 3u && corner && !degenerate)\n c = i;\n }\n"); - h.push_str(" if (c == 3u)\n return;\n"); - h.push_str(" XclOut k = v[c], a = v[(c + 1u) % 3u], b = v[(c + 2u) % 3u];\n XclOut d = a;\n"); + h.push_str(" uint c = 3u;\n"); + h.push_str(" if (v[0].pos.w > 0.0 && v[1].pos.w == v[0].pos.w && v[2].pos.w == v[0].pos.w) {\n"); + h.push_str(" float2 q[3] = { v[0].pos.xy, v[1].pos.xy, v[2].pos.xy };\n"); + h.push_str(" [unroll] for (uint i = 0u; i < 3u; i++) {\n"); + h.push_str(" float2 p = q[i], a = q[(i + 1u) % 3u], b = q[(i + 2u) % 3u];\n"); + h.push_str(" bool corner = (p.x == a.x && p.y == b.y) || (p.x == b.x && p.y == a.y);\n"); + h.push_str(" bool degenerate = all(p == a) || all(p == b) || all(a == b);\n"); + h.push_str(" if (c == 3u && corner && !degenerate)\n c = i;\n }\n }\n"); + h.push_str(" if (c == 3u) {\n s.Append(v[0]);\n s.Append(v[1]);\n s.Append(v[2]);\n return;\n }\n"); + h.push_str(" XclOut k = v[c], a = v[(c + 1u) % 3u], b = v[(c + 2u) % 3u];\n XclOut d = v[0];\n"); h.push_str(" d.pos = a.pos + b.pos - k.pos;\n"); - for k in 0..ranked(outputs, true).len() { - let _ = writeln!(h, " d.p{k} = a.p{k} + b.p{k} - k.p{k};"); + for (k, e) in ranked(outputs, true).iter().enumerate() { + if hlsl_type(e) == "float" { + let _ = writeln!(h, " d.p{k} = a.p{k} + b.p{k} - k.p{k};"); + } } - // (c, a, b) is the first triangle's winding; (a, d, b) – its point reflection – keeps it - h.push_str(" s.RestartStrip();\n s.Append(a);\n s.Append(d);\n s.Append(b);\n}\n"); - Ok(h) + // (corner, a, b) is v0 v1 v2 in its order or rotated; (corner, a, d), (corner, d, b) and + // (a, d, b) wind as it does. Of those, the two halves that both hold v0, v0 first: + // v0 v1 d, v0 d v2 (corner v0) – v0 v1 v2, v0 v2 d (v1) – v0 v1 v2, v0 d v1 (v2) + h.push_str(" s.Append(v[0]);\n s.Append(v[1]);\n"); + h.push_str(" if (c == 0u)\n s.Append(d);\n else\n s.Append(v[2]);\n"); + h.push_str(" s.RestartStrip();\n s.Append(v[0]);\n"); + h.push_str(" if (c == 1u) {\n s.Append(v[2]);\n s.Append(d);\n } else {\n s.Append(d);\n"); + h.push_str(" if (c == 0u)\n s.Append(v[2]);\n else\n s.Append(v[1]);\n }\n}\n"); + h } /// Second pass of the mesh mode: a mesh shader that turns the records written by the diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ca0d463..006ab5b 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -767,36 +767,7 @@ pub fn rect_list_gs(vs: &[u8]) -> Result, String> { if outputs.is_empty() { return Err("the VS has no output signature".into()); } - Ok(dxc::compile_cached(&super::emit::rect_list_gs(&outputs)?, "main", "gs_6_6")?.0) -} - -/// Whether the console PS `ps` (its container) reads an attribute flat: an integer input, or a -/// `v_interp_mov_f32` – what the translation declares `nointerpolation` (`emit`, `XclIn`). A rect -/// list's flat values are not carried by `rect_list_gs` (see there). -pub fn ps_reads_flat(ps: &[u8]) -> Result { - let sh = xbox::parse(ps).ok_or("not a console shader container")?; - let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 5)).ok_or("no PS hardware variant")?; - let Some(Mode::Pixel(psi)) = interface(ps, &sh, f) else { - return Err("unknown PS interface".into()); - }; - if super::ranked(&psi.inputs, false).iter().any(|e| e.component_type != 3) { - return Ok(true); - } - let p = f.programs.first().ok_or("FSSM without a program")?; - reads_flat(&f.data[p.offset..p.offset + p.len]) -} - -/// Whether PS code has a `v_interp_mov_f32`. -pub fn reads_flat(code: &[u8]) -> Result { - let mut off = 0usize; - while off + 4 <= code.len() { - let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("+{off:#x}: cannot decode ({e:?})"))?; - if d.inst.name.eq_ignore_ascii_case("v_interp_mov_f32") { - return Ok(true); - } - off += d.len; - } - Ok(false) + Ok(dxc::compile_cached(&super::emit::rect_list_gs(&outputs), "main", "gs_6_6")?.0) } /// XCL shader ABI root signature (see the module docs); `graphics` allows an input layout. diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index bd738cb..c78d64c 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -690,7 +690,23 @@ pub fn draw_gs( size: u32, clear: [f32; 4], ) -> Result, String> { - draw_gs_views(vs, gs, ps, layout, vertices, stride, sgprs, mem, &[], &[], size, clear) + draw_gs_views(vs, gs, ps, layout, vertices, stride, &[], sgprs, mem, &[], &[], size, clear) +} + +/// `draw_gs` of an indexed triangle list (`indices`). +#[allow(clippy::too_many_arguments)] +pub fn draw_gs_indexed( + vs: &[u8], + gs: Option<&[u8]>, + ps: &[u8], + layout: &[VertexElement], + vertices: &[f32], + stride: u32, + indices: &[u32], + size: u32, + clear: [f32; 4], +) -> Result, String> { + draw_gs_views(vs, gs, ps, layout, vertices, stride, indices, &[], &[], &[], &[], size, clear) } /// `draw` with textures and samplers in the directly indexed heaps (see `ViewTexture`). @@ -708,7 +724,7 @@ pub fn draw_views( size: u32, clear: [f32; 4], ) -> Result, String> { - draw_gs_views(vs, None, ps, layout, vertices, stride, sgprs, mem, textures, samplers, size, clear) + draw_gs_views(vs, None, ps, layout, vertices, stride, &[], sgprs, mem, textures, samplers, size, clear) } #[allow(clippy::too_many_arguments)] @@ -719,6 +735,7 @@ fn draw_gs_views( layout: &[VertexElement], vertices: &[f32], stride: u32, + indices: &[u32], sgprs: &[u32], mem: &[u32], textures: &[ViewTexture], @@ -763,7 +780,7 @@ fn draw_gs_views( pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|x| format!("CreateGraphicsPipelineState: {x}"))?; let draw = Draw { sgprs: sgprs.to_vec(), scissor: [0, 0, size as i32, size as i32] }; - draw_on_multi(dev, &pso, &rs, vertices, stride, &[draw], mem, textures, samplers, size, clear) + draw_indexed_on(dev, &pso, &rs, vertices, stride, indices, &[draw], mem, textures, samplers, size, clear) } }) } @@ -897,6 +914,25 @@ pub fn draw_on_multi( samplers: &[D3D12_SAMPLER_DESC], size: u32, clear: [f32; 4], +) -> Result, String> { + draw_indexed_on(dev, pso, rs, vertices, stride, &[], draws, mem, textures, samplers, size, clear) +} + +/// `draw_on_multi`, the draws indexed when there are `indices` (one index buffer for all). +#[allow(clippy::too_many_arguments)] +fn draw_indexed_on( + dev: &ID3D12Device, + pso: &ID3D12PipelineState, + rs: &ID3D12RootSignature, + vertices: &[f32], + stride: u32, + indices: &[u32], + draws: &[Draw], + mem: &[u32], + textures: &[ViewTexture], + samplers: &[D3D12_SAMPLER_DESC], + size: u32, + clear: [f32; 4], ) -> Result, String> { unsafe { // one queue and fence per device for all draws, not one per draw: once a test has @@ -995,11 +1031,27 @@ pub fn draw_on_multi( list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let vbv = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: upload.GetGPUVirtualAddress(), SizeInBytes: vb_bytes as u32, StrideInBytes: stride }; list.IASetVertexBuffers(0, Some(&[vbv])); + let _index_buf = if indices.is_empty() { + None + } else { + let bytes = (indices.len() * 4) as u64; + let b = buffer(dev, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).map_err(werr)?; + std::ptr::copy_nonoverlapping(indices.as_ptr(), p as *mut u32, indices.len()); + b.Unmap(0, None); + list.IASetIndexBuffer(Some(&D3D12_INDEX_BUFFER_VIEW { BufferLocation: b.GetGPUVirtualAddress(), SizeInBytes: bytes as u32, Format: DXGI_FORMAT_R32_UINT })); + Some(b) + }; for (k, d) in draws.iter().enumerate() { list.SetGraphicsRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress() + (k * KERNEL_SGPRS * 4) as u64); let [left, top, right, bottom] = d.scissor; list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left, top, right, bottom }]); - list.DrawInstanced((vertices.len() as u32 * 4) / stride, 1, 0, 0); + if indices.is_empty() { + list.DrawInstanced((vertices.len() as u32 * 4) / stride, 1, 0, 0); + } else { + list.DrawIndexedInstanced(indices.len() as u32, 1, 0, 0, 0); + } } list.ResourceBarrier(&[transition(&rt, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); let dst = D3D12_TEXTURE_COPY_LOCATION { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index e7c39d8..f58f1e5 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2164,33 +2164,19 @@ fn gpu_graphics_vs_ps_draw() { } } -/// `emit::rect_list_gs` refuses integer (flat) outputs and declares the VS's output struct. +/// `emit::rect_list_gs` declares the VS's output struct; the fourth vertex is v[0] with its +/// float outputs continued from the other three, its integer (flat) ones left as v[0]'s. #[test] fn rect_list_gs_outputs() { - let float = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF), el("SV_ClipDistance", 0, 2, 3, 2, 1)]; - let h = super::emit::rect_list_gs(&float).unwrap(); - assert!(h.contains("triangle XclOut v[3]") && h.contains("d.p0 = a.p0 + b.p0 - k.p0;") && h.contains("d.p1 = a.p1 + b.p1 - k.p1;"), "{h}"); - let flat = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 1, 1, 0xF)]; - assert!(super::emit::rect_list_gs(&flat).unwrap_err().contains("TEXCOORD0")); + let outputs = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF), el("TEXCOORD", 1, 0, 1, 2, 0xF), el("SV_ClipDistance", 0, 2, 3, 3, 1)]; + let h = super::emit::rect_list_gs(&outputs); + assert!(h.contains("triangle XclOut v[3]") && h.contains("XclOut d = v[0];"), "{h}"); + assert!(h.contains("d.p0 = a.p0 + b.p0 - k.p0;") && h.contains("d.p2 = a.p2 + b.p2 - k.p2;") && !h.contains("d.p1 ="), "{h}"); if super::dxc::location().is_ok() { super::dxc::compile(&h, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{h}")); } } -/// A PS with `v_interp_mov_f32` reads flat (`pso::reads_flat`): its rect list keeps no GS. -#[test] -fn rect_list_ps_reads_flat() { - let mov = prog(&[ - ("V_INTERP_MOV_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 2), ("ATTR", 0), ("ATTRCHAN", 0)], None), - ]); - let p2 = prog(&[ - ("V_INTERP_P1_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 0), ("ATTR", 0), ("ATTRCHAN", 0)], None), - ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), - ]); - assert!(super::pso::reads_flat(&mov).unwrap()); - assert!(!super::pso::reads_flat(&p2).unwrap()); -} - /// `emit::rect_list_gs` on the full-screen pass a downstream build (theaustinayers/xcl, build 5, /// via #189) reports from a retail title: positions (−1,1) (−1,−1) (1,−1), texture coordinates /// (0,0) (0,1) (1,1), the shared corner v1 and the implied one (1,1) with (1,0). Plain HLSL @@ -2210,7 +2196,7 @@ fn gpu_rect_list_fullscreen_order() { let ps_hlsl = "float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0) : SV_Target { return uv; }\n"; let vs = super::dxc::compile(vs_hlsl, "main", "vs_6_6", &[]).unwrap(); let ps = super::dxc::compile(ps_hlsl, "main", "ps_6_6", &[]).unwrap(); - let gs_hlsl = super::emit::rect_list_gs(&outputs).unwrap(); + let gs_hlsl = super::emit::rect_list_gs(&outputs); let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); let layout = [ runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, @@ -2236,6 +2222,66 @@ fn gpu_rect_list_fullscreen_order() { } } +/// A console rect list with flat outputs – an integer one, and a float one the PS reads +/// `nointerpolation` (what `v_interp_mov_f32` is translated to) – drawn indexed through +/// `emit::rect_list_gs`, the corner at v0, v1 or v2: the whole rect is drawn, the smooth output +/// continues into the implied corner's half, and both flat ones are the rect's first vertex's +/// in both halves. On the console that is the provoking vertex under D3D's setting +/// (PA_SU_SC_MODE_CNTL.PROVOKING_VTX_LAST = 0, see `emit::rect_list_gs`). Synthetic: not a +/// measurement of the hardware. Without the GS part of every rect stays clear. +#[test] +fn gpu_rect_list_flat_outputs() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32_UINT}; + let outputs = [el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 0, 0, 3, 1, 0xF), el("TEXCOORD", 1, 0, 1, 2, 0xF), el("TEXCOORD", 2, 0, 3, 3, 0xF)]; + let vs_hlsl = "struct V { float4 pos : SV_Position; float4 uv : TEXCOORD0; uint4 id : TEXCOORD1; float4 tint : TEXCOORD2; };\nV main(float4 pos : POSITION, uint id : ID) { V o; o.pos = pos; o.uv = float4(pos.xy, 0.0, 1.0); o.id = uint4(id, 0u, 0u, 0u); o.tint = float4(id * 0.125, 0.0, 0.0, 0.0); return o; }\n"; + let ps_hlsl = "float4 main(float4 pos : SV_Position, float4 uv : TEXCOORD0, nointerpolation uint4 id : TEXCOORD1, nointerpolation float4 tint : TEXCOORD2) : SV_Target { return float4(uv.xy, id.x, tint.x); }\n"; + let vs = super::dxc::compile(vs_hlsl, "main", "vs_6_6", &[]).unwrap(); + let ps = super::dxc::compile(ps_hlsl, "main", "ps_6_6", &[]).unwrap(); + let gs_hlsl = super::emit::rect_list_gs(&outputs); + let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "ID", index: 0, format: DXGI_FORMAT_R32_UINT, offset: 16 }, + ]; + // a 3 × 2 grid: columns x = -0.75, 0, 0.75, rows y = -0.5, 0.5; vertex 2·column + row has id = its number + 1 + let grid: Vec = (0..6u32).flat_map(|v| [[-0.75f32, 0.0, 0.75][v as usize / 2], [-0.5f32, 0.5][v as usize % 2], 0.0, 1.0, f32::from_bits(v + 1)]).collect(); + let (left, right) = ([-0.75f32, 0.0, -0.5, 0.5], [0.0f32, 0.75, -0.5, 0.5]); + let (n, clear) = (16usize, [0.0f32, 0.0, 1.0, 0.5]); + // (indices, the rects (x1, x2, y1, y2) and their first vertex's id) + for (name, indices, rects) in [ + ("corner v0", vec![0u32, 1, 2], vec![(left, 1.0f32)]), + ("corner v1", vec![0, 1, 3], vec![(left, 1.0)]), + ("corner v1, the other way round", vec![1, 0, 2], vec![(left, 2.0)]), + ("corner v2", vec![1, 2, 0], vec![(left, 2.0)]), + ("two rects sharing vertices", vec![0, 1, 2, 5, 3, 2], vec![(left, 1.0), (right, 6.0)]), + ] { + let run = |with_gs: bool| runner::draw_gs_indexed(&vs, with_gs.then_some(gs.as_slice()), &ps, &layout, &grid, 20, &indices, n as u32, clear).unwrap(); + let wrong = |px: &[[f32; 4]], report: bool| { + let mut wrong = 0; + for y in 0..n { + for x in 0..n { + let (fx, fy) = ((x as f32 + 0.5) / 8.0 - 1.0, 1.0 - (y as f32 + 0.5) / 8.0); + let rect = rects.iter().find(|&&([x1, x2, y1, y2], _)| fx > x1 && fx < x2 && fy > y1 && fy < y2); + let want = rect.map_or(clear, |&(_, id)| [fx, fy, id, id * 0.125]); + let got = px[y * n + x]; + if !got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5) { + assert!(!report, "{name}: pixel ({x},{y}) = {got:?}, expected {want:?}"); + wrong += 1; + } + } + } + wrong + }; + wrong(&run(true), true); + // the negative control: as a triangle list part of every rect is not drawn + let missing = wrong(&run(false), false); + assert!(missing >= 12 * rects.len(), "{name}: without the GS {missing} pixels differ"); + } +} + /// Console rect lists (DI_PT_RECTLIST) drawn through `emit::rect_list_gs`: three corners of a /// screen-aligned rectangle, the corner between the other two at v0 (Mesa radeonsi's blits), /// v1 (xf86-video-ati's r600 EXA) or v2. Each covers the whole rectangle and its attribute – the @@ -2283,7 +2329,7 @@ fn gpu_rect_list_corners() { assert!(vt.complete() && pt.complete(), "{:?} {:?}", vt.unsupported, pt.unsupported); let vs = super::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); let ps = super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); - let gs_hlsl = super::emit::rect_list_gs(&outputs).unwrap(); + let gs_hlsl = super::emit::rect_list_gs(&outputs); let gs = super::dxc::compile(&gs_hlsl, "main", "gs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{gs_hlsl}")); let layout = [ runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 0 }, diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9e33bb0..70161e1 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4368,16 +4368,11 @@ unsafe fn untranslated_stream_desc(desc: *const c_void, stream: bool) -> Option< } /// The GS that completes a rect list's rects behind the console VS `vs` and the PS `ps`; refused -/// for a PS that reads flat or is not a console one (its inputs' modes are not known). +/// for a PS that is not a console one (its inputs' modes are not known). fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result, String> { use crate::gpu::recomp::pso; - if let Some(p) = ps { - if !pso::is_console(p) { - return Err("a PC pixel shader".into()); - } - if pso::ps_reads_flat(p)? { - return Err("the PS reads a flat attribute".into()); - } + if ps.is_some_and(|p| !pso::is_console(p)) { + return Err("a PC pixel shader".into()); } pso::rect_list_gs(vs) } From 886a205bcff46013b2df4b34e5cc21d367f917c6 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:39:59 -0700 Subject: [PATCH 09/34] Console CPU instructions: fix ClzeroLoop ModRM check and loop semantics From ivall/xcl#290 by @AlpPesen, squashed. --- crates/xcl/src/eh.rs | 141 ++++++++++++++++++++++++++++++++++++++--- crates/xcl/src/insn.rs | 12 +++- 2 files changed, 140 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 6c041f1..44698db 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -275,6 +275,34 @@ unsafe fn code_at(rip: usize) -> String { crate::insn::hex(std::slice::from_raw_parts(rip as *const u8, n)) } +/// Update the x86-64 arithmetic flags (CF, PF, AF, ZF, SF, OF) for `cmp lhs, rhs`, keeping all +/// other EFLAGS bits intact. +fn cmp_eflags(eflags: u32, lhs: u64, rhs: u64) -> u32 { + const ARITH: u32 = 0x001 | 0x004 | 0x010 | 0x040 | 0x080 | 0x800; + let (res, cf) = lhs.overflowing_sub(rhs); + let (_, of) = (lhs as i64).overflowing_sub(rhs as i64); + let mut f = eflags & !ARITH; + if cf { + f |= 0x001; + } + if (res as u8).count_ones() % 2 == 0 { + f |= 0x004; + } + if (lhs & 0xF) < (rhs & 0xF) { + f |= 0x010; + } + if res == 0 { + f |= 0x040; + } + if (res as i64) < 0 { + f |= 0x080; + } + if of { + f |= 0x800; + } + f +} + /// A title's STATUS_ILLEGAL_INSTRUCTION: an instruction the console's Zen 2 has and this CPU /// lacks (`insn`) is emulated and stepped over (EXCEPTION_CONTINUE_EXECUTION); anything else is /// logged with its code bytes and goes on to the title's handlers. @@ -301,6 +329,7 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics } } } + let mut step = len; match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { @@ -332,17 +361,32 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics &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 * 1024 * 1024 * 1024 { - let bytes = end - start; - if is_writable(start, bytes) { - std::ptr::write_bytes(start as *mut u8, 0, bytes); - } else { - return 0; + let end = *regs[end_reg as usize & 15]; + let start = ctx.Rax; + let line = (start as usize) & !63; + let fast = (end > start) + .then(|| (end - start).div_ceil(64).checked_mul(64)) + .flatten() + .filter(|&b| b < 2 * 1024 * 1024 * 1024) + .and_then(|b| { + let bytes = usize::try_from(b).ok()?; + line.checked_add(bytes)?; + Some((bytes, start.checked_add(b)?)) + }); + match fast { + Some((bytes, final_rax)) if is_writable(line, bytes) => { + std::ptr::write_bytes(line as *mut u8, 0, bytes); + ctx.Rax = final_rax; + ctx.EFlags = cmp_eflags(ctx.EFlags, final_rax, end); } + _ if is_writable(line, 64) => { + // Fall back to stepping the single `clzero` (len - 9) so the title's own + // `add / cmp / jb` runs natively for end <= start, huge/wrapping, or partial ranges. + std::ptr::write_bytes(line as *mut u8, 0, 64); + step = len - 9; + } + _ => return 0, } - ctx.Rax = end as u64; } ConsoleOnly::Rdpru => { let mut v = 0i64; @@ -399,7 +443,7 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics } } } - ctx.Rip += len as u64; + ctx.Rip += step as u64; -1 // EXCEPTION_CONTINUE_EXECUTION } @@ -1159,4 +1203,81 @@ mod tests { let r = std::panic::catch_unwind(|| unsafe { unhandled_filter(std::ptr::null()) }); assert!(r.is_err(), "unhandled_filter must propagate unwind from guest title filter"); } + + #[test] + fn cmp_eflags_matches_x86_64_sub_flags() { + // equal: ZF=1, PF=1 (0 has even parity), CF=AF=SF=OF=0; IF (0x200) preserved + assert_eq!(cmp_eflags(0x202 | 0x891, 0x100, 0x100), 0x202 | 0x040 | 0x004); + // 0xD0 - 0xC0 = 0x10 (1 one-bit -> PF=0): all arithmetic flags 0 + assert_eq!(cmp_eflags(0x202 | 0x8D5, 0xD0, 0xC0), 0x202); + // unsigned borrow + AF + SF: 0x00 - 0x01 = -1 (0xFF has 8 one-bits -> PF=1) + assert_eq!(cmp_eflags(0x202, 0, 1), 0x202 | 0x001 | 0x004 | 0x010 | 0x080); + // signed overflow: i64::MIN - 1 = i64::MAX (0xFF -> PF=1, AF=1, OF=1, CF=0, SF=0) + assert_eq!(cmp_eflags(0x202, 0x8000_0000_0000_0000, 1), 0x202 | 0x004 | 0x010 | 0x800); + } + + #[test] + fn clzero_loop_aligns_updates_flags_and_falls_back_when_end_le_start() { + use std::sync::{atomic::AtomicBool, Arc}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + let alloc = || unsafe { VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize }; + let (buf, code) = (alloc(), alloc()); + assert_ne!(buf, 0); + assert_ne!(code, 0); + modules::register_mapped(Arc::new(modules::MappedModule { + name: "clzero_loop_test.exe".into(), path: "clzero_loop_test.exe".into(), base: code, size: 0x1000, entry_rva: 0, is_dll: false, + exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(true), stack_reserve: 0, + })); + // clzero; add rax, 0x40; cmp rax, rdx; jb -12 + let loop_bytes: [u8; 12] = [0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]; + unsafe { + std::ptr::copy_nonoverlapping(loop_bytes.as_ptr(), code as *mut u8, loop_bytes.len()); + + // 1) Aligned exact multiple: [0x40..0x100), Rax -> 0x100, ZF=1, CF=0 + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140); + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x40) as u64, (buf + 0x100) as u64, 0x202 | 0x001); + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, code as u64 + 12); + assert_eq!(ctx.Rax, (buf + 0x100) as u64); + assert_eq!(ctx.EFlags, 0x202 | 0x040 | 0x004); + let s = std::slice::from_raw_parts(buf as *const u8, 0x140); + assert!(s[..0x40].iter().all(|&b| b == 0xA5)); + assert!(s[0x40..0x100].iter().all(|&b| b == 0)); + assert!(s[0x100..0x140].iter().all(|&b| b == 0xA5)); + + // 2) Unaligned start + non-64B-multiple length: start = +0x50, end = +0xC0 -> 2 cache lines [0x40..0xC0), Rax -> +0xD0, ZF=0, CF=0 + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140); + ctx = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x50) as u64, (buf + 0xC0) as u64, 0x202 | 0x041); + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, code as u64 + 12); + assert_eq!(ctx.Rax, (buf + 0xD0) as u64); + assert_eq!(ctx.EFlags, 0x202); + let s = std::slice::from_raw_parts(buf as *const u8, 0x140); + assert!(s[..0x40].iter().all(|&b| b == 0xA5)); + assert!(s[0x40..0xC0].iter().all(|&b| b == 0)); + assert!(s[0xC0..0x140].iter().all(|&b| b == 0xA5)); + + // 3) end <= start: executes the single first clzero line [0x40..0x80) and steps only 3 bytes so add/cmp/jb runs natively + for end in [buf + 0x40, buf] { + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140); + ctx = std::mem::zeroed(); + (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x53) as u64, end as u64, 0x202); + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, code as u64 + 3); + assert_eq!(ctx.Rax, (buf + 0x53) as u64); + let s = std::slice::from_raw_parts(buf as *const u8, 0x140); + assert!(s[..0x40].iter().all(|&b| b == 0xA5)); + assert!(s[0x40..0x80].iter().all(|&b| b == 0)); + assert!(s[0x80..0x140].iter().all(|&b| b == 0xA5)); + } + } + modules::unregister_mapped(code); + unsafe { + VirtualFree(buf as *mut _, 0, MEM_RELEASE); + VirtualFree(code as *mut _, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/insn.rs b/crates/xcl/src/insn.rs index 71cae7d..d36573d 100644 --- a/crates/xcl/src/insn.rs +++ b/crates/xcl/src/insn.rs @@ -189,15 +189,17 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40] && (code[i + 7] == 0x48 || code[i + 7] == 0x4C) && code[i + 8] == 0x39 + && (code[i + 9] & 0xC7) == 0xC0 && 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)) + if reg_idx != 0 { + return Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)); + } } + Some((ConsoleOnly::Clzero, i + 3)) } (0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)), (0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)), @@ -272,6 +274,10 @@ mod tests { ); // 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))); + // cmp with non-rax rm, memory operand, or cmp rax, rax is not a ClzeroLoop + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xCA, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0x10, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xC0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); 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))); From ba18f73c06e981237a9015eaec300ad01eae5adb Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:39:59 -0700 Subject: [PATCH 10/34] xapu: decode the title's Opus packets and play them on the PC From ivall/xcl#294 by @simnJS, squashed. --- THIRD_PARTY.md | 1 + crates/xcl/src/hle/acphal.rs | 289 ++++++++++++++++++++++++++++++++-- crates/xcl/src/hle/opus.rs | 190 +++++++++++++++++++++- crates/xcl/src/hle/xaudio2.rs | 194 +++++++++++++++++++++++ 4 files changed, 652 insertions(+), 22 deletions(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index fd42e6a..5ea31ec 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -19,6 +19,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | Windows XGameRuntime (`System32\xgameruntime.dll`) | system | class GUIDs and slot order of the GDK thunk protocol in `hle/xgameruntime/api.rs` (facts, determined by analysis); APIs XCL does not implement are forwarded to it at runtime | interoperability; not distributed | | docs.xbox.com | documentation | signatures, enums, structs written independently | reference | | Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked | +| [libopus](https://opus-codec.org/) (`opus.dll`) | BSD-3-Clause | Opus decoding where Windows has no `MSOpusDecoder.dll` (Wine): loaded at runtime from `%XCL_OPUS_DIR%` / next to xcl.exe (`hle/opus.rs`) | **not** distributed with XCL | | DXC (`dxcompiler.dll`, `dxil.dll`) from the Windows SDK | NCSA (dxcompiler) / Microsoft (dxil) | HLSL → DXIL compilation at runtime | loaded from the user's SDK, **not** distributed with XCL | | Windows system libraries (d3d12, dxgi, xaudio2_9, mfplat, MSOpusDecoder, ole32 …) | system | target APIs | GPL-2.0 "system library" exception | diff --git a/crates/xcl/src/hle/acphal.rs b/crates/xcl/src/hle/acphal.rs index f43e43c..71051b2 100644 --- a/crates/xcl/src/hle/acphal.rs +++ b/crates/xcl/src/hle/acphal.rs @@ -1,12 +1,45 @@ //! The console's audio processor (`acphal.dll`, `xapu.dll`): memory the audio hardware //! addresses, the processor's command / message channel, SHAPE contexts and the decoder queue. //! -//! Nothing is decoded or mixed here – the processor answers as hardware with no work to do: -//! commands are acknowledged, audio frames tick (one every 128 samples at 48 kHz), SHAPE -//! context arrays exist, and the decoder returns silence of the length asked for. A title's -//! audio engine then starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole -//! audio setup), sounds decoded in software go wherever the engine sends them, and nothing -//! waits forever on the processor. Audio through the console's mixer (SHAPE) stays silent. +//! The processor answers as hardware with little to do: commands are acknowledged, audio frames +//! tick (one every 128 samples at 48 kHz), SHAPE context arrays exist. A title's audio engine then +//! starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole audio setup), and +//! nothing waits forever on the processor. The SHAPE mixer is not run. +//! +//! What runs is the decoder (xapu): Opus packets a title sends are decoded (`hle::opus`, Windows' +//! Media Foundation decoder – without it the decoder answers silence, logged once) and the PCM is +//! played on the PC by `hle::xaudio2::console_pcm`, one voice per decoder stream, without the +//! SHAPE mixer's volumes / panning / effects. `XCL_TRACE_APU=1` logs what a title sends (acphal +//! commands, xapu commands with their structures and the start of the Opus input, the caller in the +//! title, the rate per kind of command). +//! +//! # The decoder's commands as the title sends them (observed with `XCL_TRACE_APU=1`, retail build) +//! +//! Every command starts with the 24-byte `XApuCommand` (`kind`, `stream`, `sequence`, `options`, +//! `context` u64); the title builds it on its stack and sets only the fields it uses (`kind` and +//! `stream`, the others are left as they were – `sequence`, `options`, `context` mean nothing to it), +//! then calls `XApuEnqueueCommand(handle, &command, &count)` and polls `XApuDequeueResult`. +//! The title drives stream 0 only (so far) and is on one thread. +//! +//! * kind 1, Activate: `u32 channels` at +24 (1: mono, 2: stereo), the output rate 48000 at +56 (the +//! decoder is 48 kHz). Starts a stream. +//! * kind 3, Process: one Opus packet (RFC 6716, no length prefix, no container: 80 / 160 B mono +//! CELT full band 20 ms, TOC 0xF8; 320 B stereo, TOC 0xFC) in `input` / `input_bytes`; `frames` = 960 +//! (one packet), `first_frame` = 312 on the first command of a stream (the Opus pre-skip: decoded +//! frames to leave out), 0 after; the output is `frames × channels` float32 at `output` +//! (3 840 B mono). The input and output buffers are the same two for every command of the stream +//! (a ring the title refills); `ramp` is 0, the f32 "pitch" field holds 48000.0. A command every ~20 ms +//! once the title's own prefetch (a burst of ~20 commands, 4–6 ms apart) is done. +//! * kind 2, Deactivate: nothing after the header (the 40 bytes behind are the title's stack); the +//! title sends it when it releases the stream (`kind`, `stream`, sequence 0), then frees the +//! stream's slot. Activate / Deactivate alternate with no Process in between for short sounds. +//! * results: `state` bits 0 (output ready) and 1 (more input wanted), `frames` / `output_bytes` +//! the frames written (those after `first_frame`), `input` / `input_bytes` as sent. +//! * acphal: one command (`type` 2, id 0xF0F0F0F0, no data) right after `Connect`, nothing after +//! it during menus / sound (the SHAPE contexts are written in APU memory, not through commands); +//! the DSP (chad) gets nothing. +//! * APU memory: `ApuCreateHeap`, then `ApuAlloc` of 0x5780 (align 0x100), 0x222E00 (align 0x800, +//! flags 2) and 0x1913AFA0 (align 0x800, flags 1); `ApuMapVirtualAddress` is not called. //! //! Interfaces as titles call them (observed on retail titles; another project's notes on //! the same titles agree): `ApuAlloc(&va, &apu, size, alignment, flags)`, @@ -27,6 +60,7 @@ use std::ffi::c_void; use std::sync::Mutex; use std::time::{Duration, Instant}; +use crate::hle::{opus, xaudio2}; use crate::util::{HRESULT, S_OK}; const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; @@ -38,6 +72,99 @@ const XAPU_NO_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; /// one audio frame: 128 samples at 48 kHz const FRAME: Duration = Duration::from_micros(2667); +// --------------------------------------------------------------------------------------- +// XCL_TRACE_APU=1: what the title sends the audio processor and the decoder +// --------------------------------------------------------------------------------------- + +/// `XCL_TRACE_APU` set (not "0"): log the commands, their structures and buffers +fn trace_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_APU").is_ok_and(|v| !v.is_empty() && v != "0")) +} + +/// Per kind of command: how many came, when the first and the last did (for the call frequency), +/// and how many were logged in full. +#[derive(Default)] +struct TraceKind { + count: u64, + logged: u32, + first: Option, + last_report: Option, + since_report: u64, +} + +/// the first commands of each kind are logged in full, then one line per second and kind +struct Tracer { + kinds: Vec<(&'static str, u32, TraceKind)>, +} + +static TRACER: Mutex = Mutex::new(Tracer { kinds: Vec::new() }); +/// commands of one kind logged in full +const TRACE_FULL: u32 = 24; + +/// true: log this command in full; false: tracing is off, or the command is only counted (a rate line +/// is logged here when due) +fn trace_command(origin: &'static str, kind: u32) -> bool { + if !trace_on() { + return false; + } + let now = Instant::now(); + let mut t = TRACER.lock().unwrap(); + let i = match t.kinds.iter().position(|k| k.0 == origin && k.1 == kind) { + Some(i) => i, + None => { + t.kinds.push((origin, kind, TraceKind::default())); + t.kinds.len() - 1 + } + }; + let k = &mut t.kinds[i].2; + k.count += 1; + k.since_report += 1; + k.first.get_or_insert(now); + if k.logged < TRACE_FULL { + k.logged += 1; + return true; + } + match k.last_report { + None => k.last_report = Some(now), + Some(r) if now.duration_since(r) >= Duration::from_secs(5) => { + let rate = k.since_report as f64 / now.duration_since(r).as_secs_f64(); + crate::xlog_info!("apu-trace: {origin} command {kind:#x}: {} so far, {rate:.1}/s", k.count); + k.last_report = Some(now); + k.since_report = 0; + } + _ => {} + } + false +} + +/// the return addresses of the call into the decoder's queue (`module+offset`), for the first +/// commands of a kind: where in the title's code it comes from +unsafe fn trace_callers(kind: u32) { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + static LOGGED: Mutex> = Mutex::new(Vec::new()); + { + let mut l = LOGGED.lock().unwrap(); + if l.iter().filter(|&&k| k == kind).count() >= 2 { + return; + } + l.push(kind); + } + let mut frames = [std::ptr::null_mut::(); 8]; + let n = RtlCaptureStackBackTrace(1, frames.len() as u32, frames.as_mut_ptr(), std::ptr::null_mut()); + let list: Vec = frames[..n as usize].iter().map(|&f| crate::modules::describe_address(f as usize)).collect(); + crate::xlog_info!("apu-trace: command {kind:#x} called from {}", list.join(" < ")); +} + +/// up to `n` bytes at `p`, in hex (null: "null") +unsafe fn hex(p: *const c_void, n: usize) -> String { + if p.is_null() { + return "null".into(); + } + let b = std::slice::from_raw_parts(p as *const u8, n); + b.iter().map(|x| format!("{x:02x}")).collect::>().join("") +} + // --------------------------------------------------------------------------------------- // memory the audio processor addresses (32-bit APU addresses) // --------------------------------------------------------------------------------------- @@ -175,6 +302,9 @@ pub unsafe extern "system" fn ApuAlloc(va: *mut *mut c_void, apu: *mut u32, size if !apu.is_null() { *apu = a; } + if trace_command("ApuAlloc", 0) { + crate::xlog_info!("apu-trace: ApuAlloc({size:#x}, align {alignment:#x}, flags {_flags:#x}) -> va {p:#x} apu {a:#x}"); + } S_OK } @@ -208,6 +338,9 @@ pub unsafe extern "system" fn ApuMapVirtualAddress(apu: *mut u32, va: *mut c_voi return E_OUTOFMEMORY; }; *apu = a; + if trace_command("ApuMapVirtualAddress", 0) { + crate::xlog_info!("apu-trace: ApuMapVirtualAddress({va:p}, {size:#x}) -> apu {a:#x}"); + } S_OK } @@ -415,7 +548,11 @@ unsafe extern "system" fn hal_disconnect(h: *mut Hal) -> HRESULT { S_OK } -unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, _frame: u32, _data: *const c_void, _size: u32) -> HRESULT { +unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, frame: u32, data: *const c_void, size: u32) -> HRESULT { + if trace_command("acphal", kind) { + let dump = if data.is_null() || size == 0 { "none".to_string() } else { hex(data, (size as usize).min(96)) }; + crate::xlog_info!("apu-trace: acphal command {kind:#x} id {id:#x} frame {frame} data {data:p} size {size}: {dump}"); + } static SEEN: Mutex> = Mutex::new(Vec::new()); { let mut s = SEEN.lock().unwrap(); @@ -437,14 +574,22 @@ unsafe extern "system" fn hal_pop(h: *mut Hal, m: *mut Message) -> bool { } match (*h).channel.lock().unwrap().pop(Instant::now()) { Some(x) => { + if trace_command("acphal-pop", x.kind) { + let (kind, value, id) = (x.kind, x.value, x.id); + crate::xlog_info!("apu-trace: acphal PopMessage -> kind {kind:#x} value {value:#x} id {id:#x}"); + } *m = x; true } - None => false, + None => { + trace_command("acphal-pop", 0xFFFF_FFFF); + false + } } } unsafe extern "system" fn hal_count(h: *mut Hal) -> u32 { + trace_command("acphal-count", 0); (*h).channel.lock().unwrap().count(Instant::now()) } @@ -537,11 +682,20 @@ pub struct XApuConnectOutput { } const XAPU_ACTIVATE: u32 = 1; +const XAPU_DEACTIVATE: u32 = 2; const XAPU_PROCESS: u32 = 3; +/// What one decoder stream holds between commands. +struct XApuStream { + /// 1 or 2 (what Activate asked for) + channels: u32, + /// the Opus decoder of the stream (made by Activate; none: no decoder in this process) + decoder: Option, +} + struct XApu { results: Mutex>, - channels: Mutex>, + channels: Mutex>, data: usize, ready: usize, frames_per_output: u32, @@ -602,15 +756,86 @@ where clear_out(); return E_OUTOFMEMORY; } - channels.resize(n_streams, 2); + channels.resize_with(n_streams, || XApuStream { channels: 2, decoder: None }); let x = Box::new(XApu { results: Mutex::new(VecDeque::new()), channels: Mutex::new(channels), data, ready, frames_per_output: i.frames_per_output }); std::ptr::write_unaligned(output, XApuConnectOutput { data: data as *mut c_void, ready: ready as *mut c_void }); *handle = Box::into_raw(x) as *mut c_void; let (process, streams) = (i.process, i.streams); - crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – it answers with silence"); + if trace_on() { + let (data_bytes, per_stream, frames, options) = (i.data_bytes, i.commands_per_stream, i.frames_per_output, i.options); + crate::xlog_info!("apu-trace: XApuConnect: data {data_bytes:#x} B at {data:#x}, {per_stream} commands per stream, {frames} frames per output, options {options:#x}"); + } + crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – Opus packets are decoded and played on the PC (silence without an Opus decoder)"); S_OK } +/// The Opus decoder of a stream Activate (re)started. None when the process has no decoder (logged once). +fn new_decoder(stream: u32, channels: u32) -> Option { + static WARNED: std::sync::Once = std::sync::Once::new(); + match opus::Decoder::new(channels as u16, 48_000, &[]) { + Ok(d) => Some(d), + Err(e) => { + WARNED.call_once(|| crate::xlog_warn!("xapu: no Opus decoder ({e}) – the decoder answers with silence")); + crate::xlog_debug!("xapu: stream {stream} without decoder"); + None + } + } +} + +/// Decodes a Process command's input (Opus packets) into `out` (float32 samples, `channels` interleaved): +/// `first_frame` frames of what the decoder produces are skipped, the rest fills `out` (what is not +/// produced stays silent). Returns the frames written (None: nothing was decoded). +unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out: &mut [f32]) -> Option { + let (input, input_bytes, first_frame) = (p.input, p.input_bytes, p.first_frame); + let dec = s.decoder.as_mut()?; + if input.is_null() || input_bytes == 0 { + return None; + } + let packet = std::slice::from_raw_parts(input as *const u8, input_bytes as usize); + let mut pcm: Vec = Vec::with_capacity(960 * 2); + let ch = s.channels as usize; + match dec.decode_packet(packet, &mut pcm) { + Ok(frames) if frames > 0 => { + let skip = (first_frame as usize).min(frames); + let produced = (frames - skip).min(out.len() / ch); + let mut nonzero = 0u64; + for (o, &v) in out.iter_mut().zip(pcm[skip * ch..(skip + produced) * ch].iter()) { + *o = v as f32 / 32768.0; + nonzero += (v != 0) as u64; + } + xaudio2::note_console_decode(1, 0, produced as u64, nonzero); + Some(produced) + } + other => { + xaudio2::note_console_decode(0, 1, 0, 0); + if trace_on() { + crate::xlog_info!("apu-trace: stream {stream}: {input_bytes} B did not decode ({other:?})"); + } + None + } + } +} + +/// Every 5 s while the decoder works: what it decoded and what was played (the log is what a +/// run that is cut short leaves; report.json is written at the start). +fn report_progress() { + static LAST: Mutex> = Mutex::new(None); + let now = Instant::now(); + { + let mut l = LAST.lock().unwrap(); + match *l { + Some(t) if now.duration_since(t) < Duration::from_secs(5) => return, + _ => *l = Some(now), + } + } + let a = xaudio2::stats(); + crate::xlog_info!( + "xapu: {} Opus packets decoded ({} errors), {} frames, {} non-zero samples; played on the PC: {} samples ({} non-zero, {} dropped, {} errors, {} voices)", + a.xapu_packets_decoded, a.xapu_decode_errors, a.xapu_frames, a.xapu_nonzero_samples, + a.console_pcm_samples, a.console_pcm_nonzero_samples, a.console_pcm_dropped, a.console_pcm_errors, a.console_pcm_voices + ); +} + /// XApuConnect(&input, &output, &handle) pub unsafe extern "system" fn XApuConnect(input: *const XApuConnectInput, output: *mut XApuConnectOutput, handle: *mut *mut c_void) -> HRESULT { use windows_sys::Win32::System::Threading::CreateEventW; @@ -645,20 +870,44 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * } let x = &*(handle as *const XApu); let c = std::ptr::read_unaligned(command); + if trace_command("xapu", c.kind) { + let (kind, stream, seq, opts, ctx) = (c.kind, c.stream, c.sequence, c.options, c.context); + crate::xlog_info!("apu-trace: xapu command {kind:#x} stream {stream} seq {seq} options {opts:#x} context {ctx:p}: {}", hex(command as *const c_void, 64)); + trace_callers(kind); + if kind == XAPU_PROCESS { + let p = std::ptr::read_unaligned(command as *const XApuProcess); + let (ramp, pitch, first, frames, ib, input, ob, output) = (p.ramp, p.pitch, p.first_frame, p.frames, p.input_bytes, p.input, p.output_bytes, p.output); + crate::xlog_info!( + "apu-trace: process ramp {ramp} pitch {pitch} first_frame {first} frames {frames} input {ib} B at {input:p} output {ob} B at {output:p}; input starts {}", + hex(input, (ib as usize).min(512)) + ); + } + } let mut r = XApuResult { id: c, state: 0, state_data: 0, time: 0, error: S_OK, frames: 0, output_bytes: 0, output: std::ptr::null_mut(), pitch: 1.0, input_bytes: 0, input: std::ptr::null_mut() }; { let mut ch = x.channels.lock().unwrap(); let s = if (c.stream as usize) < ch.len() { c.stream as usize } else { 0 }; if c.kind == XAPU_ACTIVATE { let n = std::ptr::read_unaligned(command as *const XApuActivate).channels; - ch[s] = if n == 1 { 1 } else { 2 }; + let channels = if n == 1 { 1 } else { 2 }; + ch[s].channels = channels; + ch[s].decoder = new_decoder(c.stream, channels); + } else if c.kind == XAPU_DEACTIVATE { + ch[s].decoder = None; } else if c.kind == XAPU_PROCESS { let p = std::ptr::read_unaligned(command as *const XApuProcess); - let frame_bytes = ch[s] * 4; + let frame_bytes = ch[s].channels * 4; let asked = if p.frames != 0 { p.frames } else { x.frames_per_output }; let frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes); + let mut frames = frames; if !p.output.is_null() && frames != 0 { - std::ptr::write_bytes(p.output as *mut u8, 0, (frames * frame_bytes) as usize); + let out = std::slice::from_raw_parts_mut(p.output as *mut f32, (frames * ch[s].channels) as usize); + out.fill(0.0); + // decoded: the frames after first_frame; not decoded: silence of the length asked for + if let Some(n) = decode_into(&mut ch[s], c.stream, &p, out) { + frames = n as u32; + xaudio2::console_pcm(c.stream, ch[s].channels as u16, &out[..n * ch[s].channels as usize]); + } } // output ready, more input wanted r.state = 1 | 2; @@ -668,6 +917,7 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * r.pitch = p.pitch; r.input_bytes = p.input_bytes; r.input = p.input; + report_progress(); } } let n = { @@ -689,6 +939,7 @@ pub unsafe extern "system" fn XApuDequeueResult(handle: *mut c_void, result: *mu if handle.is_null() || result.is_null() { return E_INVALIDARG; } + trace_command("xapu-dequeue", 0); match (*(handle as *const XApu)).results.lock().unwrap().pop_front() { Some(r) => { std::ptr::write_unaligned(result, r); @@ -747,7 +998,10 @@ pub unsafe extern "system" fn XDspDisconnect(handle: *mut c_void) -> HRESULT { S_OK } -pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { + if trace_command("dsp", 0xA0) { + crate::xlog_info!("apu-trace: XDspActivate({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { E_INVALIDARG } else { @@ -763,8 +1017,11 @@ pub unsafe extern "system" fn XDspDeactivate(handle: *mut c_void, _a: usize, _b: } } -pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { static FIRST: std::sync::Once = std::sync::Once::new(); + if trace_command("dsp", 0x5C) { + crate::xlog_info!("apu-trace: XDspSubmitCommand({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { return E_INVALIDARG; } diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index c2d1018..097d494 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -826,9 +826,187 @@ fn mf_runtime() -> Result<&'static MfRuntime, String> { .map_err(|e| e.clone()) } -/// Whether Windows' built-in `MSOpusDecoder.dll` + Media Foundation runtime is available. +/// Whether an Opus decoder is available: Windows' built-in `MSOpusDecoder.dll` + Media Foundation +/// runtime, or libopus loaded from `opus.dll` (see [`libopus`]). pub fn is_available() -> bool { - mf_runtime().is_ok() + mf_runtime().is_ok() || libopus().is_ok() +} + +/// The decoder in use ("Windows MSOpusDecoder", "libopus (path)"), or why there is none. Logged once. +pub fn backend() -> String { + match (mf_runtime(), libopus()) { + (Ok(_), _) => "Windows' MSOpusDecoder (Media Foundation)".to_string(), + (_, Ok(l)) => format!("libopus ({})", l.path), + (Err(a), Err(b)) => format!("none ({a}; {b})"), + } +} + +// --------------------------------------------------------------------------------------- +// libopus from `opus.dll`, loaded at run time (where Windows' decoder does not exist: Wine) +// --------------------------------------------------------------------------------------- +// +// Not distributed with XCL (like DXC): `opus.dll` – libopus (BSD-3-Clause), built for Windows – is +// looked for in `%XCL_OPUS_DIR%`, then next to xcl.exe (`opus.dll`, `libopus.dll`, `libopus-0.dll`). +// Windows' own decoder is used first when the system has it. Only the decoder is used. + +type OpusDecoderCreateFn = unsafe extern "C" fn(i32, i32, *mut i32) -> *mut c_void; +type OpusDecodeFn = unsafe extern "C" fn(*mut c_void, *const u8, i32, *mut i16, i32, i32) -> i32; +type OpusDecoderDestroyFn = unsafe extern "C" fn(*mut c_void); +type OpusDecoderCtlFn = unsafe extern "C" fn(*mut c_void, i32, ...) -> i32; + +/// `OPUS_RESET_STATE`: the decoder starts again +const OPUS_RESET_STATE: i32 = 4028; + +struct LibOpus { + path: String, + create: OpusDecoderCreateFn, + decode: OpusDecodeFn, + destroy: OpusDecoderDestroyFn, + ctl: OpusDecoderCtlFn, +} + +static LIBOPUS: OnceLock> = OnceLock::new(); + +fn libopus() -> Result<&'static LibOpus, String> { + LIBOPUS + .get_or_init(|| unsafe { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::System::LibraryLoader::LoadLibraryW; + let mut dirs: Vec = Vec::new(); + if let Some(d) = std::env::var_os("XCL_OPUS_DIR") { + dirs.push(d.into()); + } + if let Some(d) = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf())) { + dirs.push(d); + } + for dir in &dirs { + for name in ["opus.dll", "libopus.dll", "libopus-0.dll"] { + let path = dir.join(name); + if !path.is_file() { + continue; + } + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let h = LoadLibraryW(wide.as_ptr()) as usize; + if h == 0 { + continue; + } + let f = |n: &str| crate::resolver::system_proc_in(h, &crate::pe::ImportName::Name { hint: 0, name: n.into() }); + let (Some(create), Some(decode), Some(destroy), Some(ctl)) = + (f("opus_decoder_create"), f("opus_decode"), f("opus_decoder_destroy"), f("opus_decoder_ctl")) + else { + continue; + }; + return Ok(LibOpus { + path: path.display().to_string(), + create: std::mem::transmute::(create), + decode: std::mem::transmute::(decode), + destroy: std::mem::transmute::(destroy), + ctl: std::mem::transmute::(ctl), + }); + } + } + Err("no opus.dll (libopus) in %XCL_OPUS_DIR% or next to xcl.exe".to_string()) + }) + .as_ref() + .map_err(|e| e.clone()) +} + +/// One libopus decoder (1 or 2 channels), the same job as [`MftDecoder`]. +struct LibDecoder { + lib: &'static LibOpus, + state: *mut c_void, + channels: u16, + output_rate: u32, +} + +impl LibDecoder { + fn new(channels: u16, sample_rate: u32) -> Result { + let lib = libopus()?; + let ch = channels.clamp(1, 2); + // libopus decodes to 8, 12, 16, 24 or 48 kHz + let rate = if matches!(sample_rate, 8_000 | 12_000 | 16_000 | 24_000 | 48_000) { sample_rate } else { 48_000 }; + let mut err = 0i32; + let state = unsafe { (lib.create)(rate as i32, ch as i32, &mut err) }; + if state.is_null() || err != 0 { + return Err(format!("opus_decoder_create: {err}")); + } + Ok(Self { lib, state, channels: ch, output_rate: rate }) + } + + fn flush(&mut self) { + unsafe { + (self.lib.ctl)(self.state, OPUS_RESET_STATE); + } + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + let max_frames = (MAX_PACKET_SAMPLES_48K as usize * self.output_rate as usize) / 48_000; + let ch = self.channels as usize; + let start = out.len(); + out.resize(start + max_frames * ch, 0); + let n = unsafe { (self.lib.decode)(self.state, packet.as_ptr(), packet.len() as i32, out[start..].as_mut_ptr(), max_frames as i32, 0) }; + if n < 0 { + out.truncate(start); + return Err(format!("opus_decode: {n}")); + } + out.truncate(start + n as usize * ch); + Ok(n as usize) + } +} + +impl Drop for LibDecoder { + fn drop(&mut self) { + unsafe { (self.lib.destroy)(self.state) } + } +} + +// SAFETY: a libopus decoder state is used by one thread at a time (`&mut self`). +unsafe impl Send for LibDecoder {} + +/// One single-stream decoder: Windows' MFT where there is one, else libopus. +enum SingleStreamDecoder { + Mft(MftDecoder), + Lib(LibDecoder), +} + +impl SingleStreamDecoder { + fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { + static CHOICE: std::sync::Once = std::sync::Once::new(); + CHOICE.call_once(|| crate::xlog_info!("Opus: decoder = {}", backend())); + match MftDecoder::new(channels, sample_rate, head_bytes) { + Ok(d) => Ok(Self::Mft(d)), + Err(mft) => LibDecoder::new(channels, sample_rate).map(Self::Lib).map_err(|lib| format!("{mft}; {lib}")), + } + } + + fn output_rate(&self) -> u32 { + match self { + Self::Mft(d) => d.output_rate, + Self::Lib(d) => d.output_rate, + } + } + + /// stream time of the next packet (0: nothing decoded since the start / the last flush) + fn timestamp_100ns(&self) -> i64 { + match self { + Self::Mft(d) => d.timestamp_100ns, + Self::Lib(_) => 0, + } + } + + fn flush(&mut self) { + match self { + Self::Mft(d) => d.flush(), + Self::Lib(d) => d.flush(), + } + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + match self { + Self::Mft(d) => d.decode_packet(packet, out), + Self::Lib(d) => d.decode_packet(packet, out), + } + } } fn mf_create_media_type(rt: &MfRuntime) -> Result { @@ -882,7 +1060,7 @@ enum OutputSampleFormat { Float32, } -struct SingleStreamDecoder { +struct MftDecoder { mft: IMFTransform, channels: u16, output_rate: u32, @@ -892,7 +1070,7 @@ struct SingleStreamDecoder { timestamp_100ns: i64, } -impl SingleStreamDecoder { +impl MftDecoder { fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { let rt = mf_runtime()?; let mft = create_opus_mft(rt)?; @@ -1163,7 +1341,7 @@ impl Decoder { streams.push(SingleStreamDecoder::new(sch, rate, Some(&ud))?); } } - let output_rate = streams[0].output_rate; + let output_rate = streams[0].output_rate(); let pre_skip_scaled = ((head.pre_skip as u64 * output_rate as u64) / 48_000) as usize; let output_gain_scale = gain_scale(head.output_gain); @@ -1291,7 +1469,7 @@ impl Decoder { && t.head.coupled_count == self.coupled_count && t.head.mapping == self.mapping && gain_scale(t.head.output_gain) == self.output_gain_scale - && self.streams.iter().all(|s| s.timestamp_100ns == 0) + && self.streams.iter().all(|s| s.timestamp_100ns() == 0) }); if let Some(timing) = timing { for pkt in &packets { diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index f762160..932e0ef 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -67,6 +67,7 @@ const CO_E_NOTINITIALIZED: HRESULT = 0x8004_01F0u32 as i32; const ENGINE_CREATE_SOURCE_VOICE: usize = 5; const ENGINE_CREATE_MASTERING_VOICE: usize = 7; const VOICE_DESTROY: usize = 18; +const VOICE_START: usize = 19; const VOICE_SUBMIT_SOURCE_BUFFER: usize = 21; const VOICE_FLUSH_SOURCE_BUFFERS: usize = 22; const VOICE_GET_STATE: usize = 25; @@ -171,6 +172,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { // --------------------------------------------------------------------------------------- #[derive(Debug, Default, Clone, Serialize, Deserialize)] +#[serde(default)] pub struct AudioStats { pub engines: u64, pub engine_errors: u64, @@ -197,6 +199,19 @@ pub struct AudioStats { pub source_voice_errors: u64, /// console-only flags we dropped, e.g. "XAudio2Create:0x1" pub dropped_flags: Vec, + /// the console's decoder (xapu, `hle::acphal`): Opus packets decoded, packets that failed (silence + /// went out), frames produced, samples that are not 0 + pub xapu_packets_decoded: u64, + pub xapu_decode_errors: u64, + pub xapu_frames: u64, + pub xapu_nonzero_samples: u64, + /// the console decoder's PCM played here: voices, samples (and the non-zero ones) submitted to + /// XAudio2, buffers dropped (queue full or no device), errors + pub console_pcm_voices: u64, + pub console_pcm_samples: u64, + pub console_pcm_nonzero_samples: u64, + pub console_pcm_dropped: u64, + pub console_pcm_errors: u64, } static ENGINES: AtomicU64 = AtomicU64::new(0); @@ -236,6 +251,15 @@ pub fn stats() -> AudioStats { buffers_silenced: SILENCED.load(Ordering::Relaxed), source_voice_errors: SOURCE_ERRORS.load(Ordering::Relaxed), dropped_flags: DROPPED.lock().map(|d| d.clone()).unwrap_or_default(), + xapu_packets_decoded: PCM_PACKETS.load(Ordering::Relaxed), + xapu_decode_errors: PCM_PACKET_ERRORS.load(Ordering::Relaxed), + xapu_frames: PCM_DECODED_FRAMES.load(Ordering::Relaxed), + xapu_nonzero_samples: PCM_NONZERO.load(Ordering::Relaxed), + console_pcm_voices: SINK_VOICES.load(Ordering::Relaxed), + console_pcm_samples: SINK_SAMPLES.load(Ordering::Relaxed), + console_pcm_nonzero_samples: SINK_NONZERO.load(Ordering::Relaxed), + console_pcm_dropped: SINK_DROPPED.load(Ordering::Relaxed), + console_pcm_errors: SINK_ERRORS.load(Ordering::Relaxed), } } @@ -1168,6 +1192,176 @@ unsafe extern "system" fn destroy_voice(this: *mut c_void) { } } +// --------------------------------------------------------------------------------------- +// the console audio processor's PCM out (hle::acphal): decoded streams played on the PC +// --------------------------------------------------------------------------------------- +// +// A title that uses the console's audio hardware (xapu decoder, SHAPE mixer) has no XAudio2 +// engine of its own. What xapu decodes is played here: one float32 source voice per decoder +// stream on an engine of this module's own (system XAudio2), mixed by Windows. It runs on a thread +// of its own (COM, the device and the queue never hold up the title's audio thread). The SHAPE +// mixer's volumes, panning and effects are not applied – the decoded stream plays as it is. + +use std::sync::mpsc::{channel, Sender}; + +/// float32 samples a title's decoder stream hands over: (decoder stream, channels, interleaved samples) +type SinkItem = (u32, u16, Vec); + +/// buffers of one sink voice: a queue deeper than this drops the newest samples +const SINK_RING: usize = 24; + +static SINK: OnceLock>>> = OnceLock::new(); +static SINK_SAMPLES: AtomicU64 = AtomicU64::new(0); +static SINK_NONZERO: AtomicU64 = AtomicU64::new(0); +static SINK_DROPPED: AtomicU64 = AtomicU64::new(0); +static SINK_ERRORS: AtomicU64 = AtomicU64::new(0); +static SINK_VOICES: AtomicU64 = AtomicU64::new(0); +static PCM_DECODED_FRAMES: AtomicU64 = AtomicU64::new(0); +static PCM_NONZERO: AtomicU64 = AtomicU64::new(0); +static PCM_PACKETS: AtomicU64 = AtomicU64::new(0); +static PCM_PACKET_ERRORS: AtomicU64 = AtomicU64::new(0); + +/// What the console decoder (xapu) did: `packets` Opus packets decoded to `frames` frames of which +/// `nonzero` samples are not 0, `errors` packets that did not decode (silence went out). +pub fn note_console_decode(packets: u64, errors: u64, frames: u64, nonzero: u64) { + PCM_PACKETS.fetch_add(packets, Ordering::Relaxed); + PCM_PACKET_ERRORS.fetch_add(errors, Ordering::Relaxed); + PCM_DECODED_FRAMES.fetch_add(frames, Ordering::Relaxed); + PCM_NONZERO.fetch_add(nonzero, Ordering::Relaxed); +} + +/// Plays what a console decoder stream produced (interleaved float32, 48 kHz). Never blocks. +pub fn console_pcm(stream: u32, channels: u16, samples: &[f32]) { + if samples.is_empty() || !(1..=2).contains(&channels) { + return; + } + let tx = SINK.get_or_init(|| { + let (tx, rx) = channel::(); + match std::thread::Builder::new().name("console-audio".into()).spawn(move || sink_thread(rx)) { + Ok(_) => Mutex::new(Some(tx)), + Err(_) => { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + Mutex::new(None) + } + } + }); + if let Some(t) = tx.lock().unwrap().as_ref() { + let _ = t.send((stream, channels, samples.to_vec())); + } +} + +/// a voice's method: the system's, whatever this module patched in the shared vtable +unsafe fn voice_fn(obj: *mut c_void, slot: usize) -> usize { + original(obj, slot).unwrap_or_else(|| vtable(obj).add(slot).read()) +} + +struct SinkVoice { + voice: *mut c_void, + channels: u16, + ring: Vec>, + next: usize, +} + +unsafe fn sink_engine() -> Option<(*mut c_void, *mut c_void)> { + use windows_sys::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED}; + CoInitializeEx(std::ptr::null(), COINIT_MULTITHREADED as u32); + let (with_version, plain) = system_create()?; + let mut engine: *mut c_void = std::ptr::null_mut(); + let hr = match (with_version, plain) { + (Some(f), _) => f(&mut engine, 0, XAUDIO2_DEFAULT_PROCESSOR, NTDDI_WIN10_RS5), + (None, Some(f)) => f(&mut engine, 0, XAUDIO2_DEFAULT_PROCESSOR), + _ => E_FAIL, + }; + if hr < 0 || engine.is_null() { + crate::xlog_warn!("console audio: no XAudio2 engine ({:#x}) – decoded sound is not played", hr as u32); + return None; + } + let create_mastering: CreateMasteringVoiceFn = std::mem::transmute(voice_fn(engine, ENGINE_CREATE_MASTERING_VOICE)); + let mut mastering: *mut c_void = std::ptr::null_mut(); + let hr = create_mastering(engine, &mut mastering, 0, 0, 0, std::ptr::null(), std::ptr::null(), AUDIO_CATEGORY_GAME_EFFECTS); + if hr < 0 || mastering.is_null() { + crate::xlog_warn!("console audio: no mastering voice ({:#x}) – no audio device? decoded sound is not played", hr as u32); + return None; + } + crate::xlog_info!("console audio: XAudio2 engine and mastering voice created – the console decoder's PCM is played"); + Some((engine, mastering)) +} + +fn sink_thread(rx: std::sync::mpsc::Receiver) { + unsafe { + let Some((engine, _mastering)) = sink_engine() else { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + // keep draining so the title's side never queues without bound + for _ in rx { + SINK_DROPPED.fetch_add(1, Ordering::Relaxed); + } + return; + }; + let mut voices: HashMap = HashMap::new(); + for (stream, channels, samples) in rx { + let need_new = voices.get(&stream).is_none_or(|v| v.channels != channels); + if need_new { + if let Some(old) = voices.remove(&stream) { + let destroy: DestroyVoiceFn = std::mem::transmute(voice_fn(old.voice, VOICE_DESTROY)); + destroy(old.voice); + } + let fmt = WaveFormatEx { + tag: WAVE_FORMAT_IEEE_FLOAT, + channels, + rate: 48_000, + avg_bytes: 48_000 * 4 * channels as u32, + block_align: 4 * channels, + bits: 32, + cb_size: 0, + }; + let create: CreateSourceVoiceFn = std::mem::transmute(voice_fn(engine, ENGINE_CREATE_SOURCE_VOICE)); + let mut voice: *mut c_void = std::ptr::null_mut(); + let hr = create(engine, &mut voice, &fmt, 0, 1.0, std::ptr::null_mut(), std::ptr::null(), std::ptr::null()); + if hr < 0 || voice.is_null() { + crate::xlog_warn!("console audio: stream {stream}: no source voice ({:#x})", hr as u32); + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + continue; + } + let start: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT = std::mem::transmute(voice_fn(voice, VOICE_START)); + start(voice, 0, 0); + SINK_VOICES.fetch_add(1, Ordering::Relaxed); + voices.insert(stream, SinkVoice { voice, channels, ring: vec![Vec::new(); SINK_RING], next: 0 }); + } + let Some(v) = voices.get_mut(&stream) else { continue }; + let mut st = XAudio2VoiceState { current_buffer_context: std::ptr::null_mut(), buffers_queued: 0, samples_played: 0 }; + let get_state: GetStateFn = std::mem::transmute(voice_fn(v.voice, VOICE_GET_STATE)); + get_state(v.voice, &mut st, 0x100 /* XAUDIO2_VOICE_NOSAMPLESPLAYED */); + let queued = st.buffers_queued; + if queued as usize >= SINK_RING - 1 { + SINK_DROPPED.fetch_add(1, Ordering::Relaxed); + continue; + } + let slot = &mut v.ring[v.next]; + v.next = (v.next + 1) % SINK_RING; + *slot = samples; + let b = XAudio2Buffer { + flags: 0, + audio_bytes: (slot.len() * 4) as u32, + audio_data: slot.as_ptr() as *const u8, + play_begin: 0, + play_length: 0, + loop_begin: 0, + loop_length: 0, + loop_count: 0, + context: std::ptr::null_mut(), + }; + let submit: SubmitSourceBufferFn = std::mem::transmute(voice_fn(v.voice, VOICE_SUBMIT_SOURCE_BUFFER)); + let hr = submit(v.voice, &b, std::ptr::null()); + if hr < 0 { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + } else { + SINK_SAMPLES.fetch_add(slot.len() as u64, Ordering::Relaxed); + SINK_NONZERO.fetch_add(slot.iter().filter(|&&x| x != 0.0).count() as u64, Ordering::Relaxed); + } + } + } +} + #[cfg(test)] mod tests { use super::*; From b2479bf41a9fe7f9754af33fecdc4e16ecc69c36 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:39:59 -0700 Subject: [PATCH 11/34] DirectStorage: a destination page array entry that is 0 at enqueue is read at the request's turn From ivall/xcl#289 by @theaustinayers, squashed. --- crates/xcl/src/hle/dstorage.rs | 87 ++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 32b215b..76f0653 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -909,6 +909,18 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; + // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is + // read again now. A retail title keeps its page arrays in its own tables and fills an + // entry after EnqueueRequest – its streaming requests were refused by the thousand + // with page 0. An array that had its pages at enqueue stays as it was snapshotted + // (titles also pass arrays on the stack). + let late: Vec; + let pages = if pages.contains(&0) && crate::gpu::shader::readable(r.destination as usize, std::mem::size_of_val(pages)) { + late = (0..pages.len()).map(|k| if pages[k] != 0 { pages[k] } else { (r.destination as *const usize).add(k).read_unaligned() }).collect(); + &late[..] + } else { + pages + }; if !crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &payload[..n]) { return Err(E_ACCESS_VIOLATION); } @@ -1951,6 +1963,81 @@ mod tests { } } + /// A destination page array whose entry is still 0 at EnqueueRequest and gets its page + /// before the request's turn: the data arrives (a retail title's streaming). + #[test] + fn a_destination_page_filled_in_after_enqueue() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; + if crate::gpu::uma::get().is_none() { + return; + } + unsafe { + let mut count = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&16u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + // where the pages can be read back: mapped into a reservation + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + 2 * PHYS_PAGE_SIZE, + windows_sys::Win32::System::Memory::MEM_RESERVE, + windows_sys::Win32::System::Memory::PAGE_READWRITE, + ); + assert!(!reserved.is_null()); + assert_eq!(MapTitlePhysicalPages(reserved, 2, 0, 4, pages.as_mut_ptr()), reserved); + + // 0. the title's table: the second entry has no page yet when the request is enqueued + let data: Vec = (0..0x1800u32).map(|i| (i * 13 + 5) as u8).collect(); + let page_off = (PHYS_PAGE_SIZE - 0x800) as u16; + let mut table = Box::new([pages[0], 0usize]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr() as u64, page_off, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr()); + std::ptr::write_volatile(&mut table[1], pages[1]); + status(q, s, 0); + + // 1. an entry that is still 0 at the request's turn is refused as before + let empty = Box::new([0usize]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, empty.as_ptr() as u64, 0, 16, data.as_ptr() as u64, 0, 16, 0, 0).as_ptr()); + status(q, s, 1); + + submit(q); + let t = std::time::Instant::now(); + while !complete(s, 1) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!((hresult(s, 0), hresult(s, 1)), (S_OK, E_ACCESS_VIOLATION)); + let got = std::slice::from_raw_parts((reserved as *const u8).add(page_off as usize), data.len()); + assert_eq!(got, &data[..], "the bytes cross from the page that was there into the one filled in later"); + + MapTitlePhysicalPages(reserved, 2, 0, 4, std::ptr::null_mut()); + windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + queue_close(q); + queue_release(q); + status_release(s); + } + } + #[test] fn physical_page_destinations_and_sources() { use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; From a4388474aa0b64cf3cb3ca4dab58bf81d29f667e Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:39:59 -0700 Subject: [PATCH 12/34] e2e: stage the test title under CARGO_TARGET_TMPDIR From ivall/xcl#270 by @cmt8, squashed. --- crates/xcl/src/hle/d3d12x/null.rs | 34 ++++++++++++++++++++++---- crates/xcl/src/hle/kernelx.rs | 6 ++++- crates/xcl/src/hle/xgameruntime/api.rs | 9 ++++--- crates/xcl/src/preflight.rs | 5 +++- crates/xcl/tests/e2e.rs | 2 +- tests/testgamedll/Cargo.toml | 3 +++ 6 files changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/null.rs b/crates/xcl/src/hle/d3d12x/null.rs index bfaeb60..818a22a 100644 --- a/crates/xcl/src/hle/d3d12x/null.rs +++ b/crates/xcl/src/hle/d3d12x/null.rs @@ -616,11 +616,11 @@ unsafe extern "system" fn Heap_GetDesc16(this: *mut NullObj, ret: *mut u8) -> *m } ret } -unsafe extern "system" fn Heap_GetHandleStart(this: *mut NullObj, ret: *mut u64) -> *mut u64 { - if !ret.is_null() { - *ret = (*this).value.load(Ordering::Relaxed); - } - ret +/// #9 / #10 GetCPU / GetGPUDescriptorHandleForHeapStart: console code takes the handle in rax +/// and passes only `this` (as `real::heap_cpu_start_x`); rdx holds whatever the caller left +/// there, so it must not be written through as the PC's hidden return pointer. +unsafe extern "system" fn Heap_GetHandleStart(this: *mut NullObj) -> u64 { + (*this).value.load(Ordering::Relaxed) } unsafe extern "system" fn Resource_Map(this: *mut NullObj, _sub: u32, _range: *const c_void, data: *mut *mut c_void) -> HRESULT { let mut g = (*this).mem.lock().unwrap(); @@ -792,4 +792,28 @@ mod tests { assert!(crate::stubs::all_stubs().iter().any(|s| s.name == "ID3D12Device::#200" && s.calls.load(Ordering::Relaxed) > 0)); } } + + /// Console code calls descriptor heap #9 / #10 with only `this` and takes the start in rax; + /// rdx is left over from the caller and must not be written (the test title's rdx pointed + /// into its read-only .rdata: an access violation under Wine on the null device). + #[test] + fn heap_start_handles_come_back_in_rax() { + unsafe { + let mut dev = std::ptr::null_mut(); + assert_eq!(D3D12CreateDevice(std::ptr::null_mut(), 0xC100, std::ptr::null(), &mut dev), S_OK); + let desc = [0u32, 16, 1, 0]; // CBV_SRV_UAV, 16 slots, shader visible + let create_heap: Fn4 = std::mem::transmute(slot(dev, 14)); + let mut h = std::ptr::null_mut(); + assert_eq!(create_heap(dev, desc.as_ptr() as *const c_void, std::ptr::null(), &mut h), S_OK); + for i in [9, 10] { + // a caller that passes only `this`, with a stray pointer left in rdx + let start: unsafe extern "system" fn(*mut c_void, *mut u64) -> u64 = std::mem::transmute(slot(h, i)); + let mut stray = 0x5A5A_5A5Au64; + let p = start(h, &mut stray); + assert_eq!(stray, 0x5A5A_5A5A, "slot {i} wrote through rdx"); + assert_ne!(p, 0, "slot {i}"); + assert_ne!(p, &mut stray as *mut u64 as u64, "slot {i} returned rdx"); + } + } + } } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5ee53b5..0d4e64d 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -685,7 +685,9 @@ fn process_private_bytes() -> u64 { let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); c.cb = std::mem::size_of::() as u32; if K32GetProcessMemoryInfo(thr::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb) != 0 { - c.PrivateUsage as u64 + // Wine fills the fields before PrivateUsage only; PagefileUsage is the same number + // on Windows (the commit charge) + if c.PrivateUsage != 0 { c.PrivateUsage as u64 } else { c.PagefileUsage as u64 } } else { 0 } @@ -2219,6 +2221,8 @@ mod tests { assert_eq!(unsafe { TitleMemoryStatus(&mut s) }, 1); assert_eq!(s.total, 13_824 * 1024 * 1024); assert!(s.avail <= s.total); + // the process's own memory counts as used (Wine leaves PrivateUsage 0) + assert!(process_private_bytes() > 0 && s.avail < s.total); s.dw_length = 8; assert_eq!(unsafe { TitleMemoryStatus(&mut s) }, 0); } diff --git a/crates/xcl/src/hle/xgameruntime/api.rs b/crates/xcl/src/hle/xgameruntime/api.rs index a35e9e2..66f9985 100644 --- a/crates/xcl/src/hle/xgameruntime/api.rs +++ b/crates/xcl/src/hle/xgameruntime/api.rs @@ -11,9 +11,10 @@ //! dropped), the XGameUi dialogs that do not take a user –, refuses XStore, app broadcast and //! app capture (the thunk then returns its "API not available" error), and passes everything //! else to the PC's own XGameRuntime (`System32\xgameruntime.dll`: the same classes under the -//! same GUIDs) – XTaskQueue / XAsync, XThread, XNetworking, XGameInvite… Once the PC runtime is -//! in use, the queues and async blocks are its own, so XCL's async APIs run on its XAsync -//! (`xasync::use_pc`). Nothing that takes an XCL user handle goes to the PC runtime: it does not +//! same GUIDs) – XTaskQueue / XAsync, XThread, XGameInvite… (XNetworking is always XCL's). Once +//! the PC runtime is in use, the queues and async blocks are its own, so XCL's async APIs run on +//! its XAsync (`xasync::use_pc`); without `System32\xgameruntime.dll`, XAsync / XTaskQueue / +//! XThread fall back to XCL's own. Nothing that takes an XCL user handle goes to the PC runtime: it does not //! validate foreign handles. //! //! Layout: `gdk_table` (extracted from the public PC GDK's thunk library) gives every @@ -138,7 +139,7 @@ fn pc() -> Option<&'static Pc> { use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32}; let h = LoadLibraryExW(crate::util::wide("xgameruntime.dll").as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); if h.is_null() { - crate::xlog_warn!("XGameRuntime: no System32\\xgameruntime.dll (Gaming Services) – XTaskQueue/XAsync and the other APIs XCL does not implement are unavailable"); + crate::xlog_warn!("XGameRuntime: no System32\\xgameruntime.dll (Gaming Services) – XCL's own XTaskQueue/XAsync are used; dialogs, text entry, game invites, game streaming and the other APIs XCL does not implement are unavailable"); return None; } let f = |n: &str| GetProcAddress(h, format!("{n}\0").as_ptr()).map(|p| p as usize); diff --git a/crates/xcl/src/preflight.rs b/crates/xcl/src/preflight.rs index d394d8f..230a29b 100644 --- a/crates/xcl/src/preflight.rs +++ b/crates/xcl/src/preflight.rs @@ -91,7 +91,7 @@ pub fn checks(f: &Found) -> Vec { Err(_) => v.push(check(Level::Error, "no DXC (dxcompiler.dll + dxil.dll): no shader can be compiled, the game draws nothing", Some("install the Windows SDK, or put dxcompiler.dll and dxil.dll next to xcl.exe (or in %XCL_DXC_DIR%)"))), } if !f.xgameruntime { - v.push(check(Level::Warning, "no System32\\xgameruntime.dll: XCL's own XGameRuntime parts work, the rest (task queues, networking, dialogs) is missing", Some("install Gaming Services (Microsoft Store)"))); + v.push(check(Level::Warning, "no System32\\xgameruntime.dll: dialogs, text entry, game invites and game streaming are missing (XCL's own task queues, async and networking are used)", Some("install Gaming Services (Microsoft Store)"))); } v } @@ -215,6 +215,9 @@ mod tests { let c = checks(&f); assert_eq!(c.iter().map(|c| c.level).collect::>(), [Level::Ok, Level::Error, Level::Warning, Level::Error, Level::Warning]); assert!(c[1].what.contains("has 6.5"), "{:?}", c[1]); + // XCL's own task queues and networking stand in for the PC runtime's: not missing + let missing = c[4].what.split(" missing").next().unwrap(); + assert!(missing.contains("dialogs") && !missing.contains("task queues") && !missing.contains("networking"), "{:?}", c[4]); assert!(c.iter().filter(|c| c.level != Level::Ok).all(|c| c.fix.is_some()), "{c:?}"); } diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index aa73c18..2d7935c 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -97,7 +97,7 @@ fn test_title_runs_and_game_folder_is_untouched() { dll.display() ); let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); - let root = manifest.join("..").join("..").join("target").join("e2e"); + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join("e2e"); let _ = std::fs::remove_dir_all(&root); let game = root.join("game"); let data = root.join("data"); diff --git a/tests/testgamedll/Cargo.toml b/tests/testgamedll/Cargo.toml index 6264862..379c3fa 100644 --- a/tests/testgamedll/Cargo.toml +++ b/tests/testgamedll/Cargo.toml @@ -10,3 +10,6 @@ publish = false name = "testgame_mw" crate-type = ["cdylib"] path = "src/lib.rs" +# no unit tests: the GNU linker keeps the kernelx.dll import in the test harness's exe, +# which then does not start (kernelx.dll exists only inside XCL) +test = false From daba20e5931749498b3854a3b57cf358596c3dce Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:40:00 -0700 Subject: [PATCH 13/34] xcl inspect: include the console verdict in --json output From ivall/xcl#268 by @NethminaYasas, squashed. --- crates/xcl/src/inspect.rs | 94 +++++++++++++++++++++++++++++---------- 1 file changed, 71 insertions(+), 23 deletions(-) diff --git a/crates/xcl/src/inspect.rs b/crates/xcl/src/inspect.rs index 40cc690..66207b0 100644 --- a/crates/xcl/src/inspect.rs +++ b/crates/xcl/src/inspect.rs @@ -5,7 +5,7 @@ use std::path::Path; use serde::Serialize; -use crate::pe::{Layout, Pe}; +use crate::pe::{ImportDll, Layout, Pe}; use crate::resolver::{self, Source}; #[derive(Serialize)] @@ -29,6 +29,10 @@ struct Out { tls_template_bytes: Option, exception_entries: u32, stack_reserve: String, + /// True when the file imports console libraries (kernelx / xgameruntime / d3d12_xs). + is_console: bool, + /// The console libraries it imports, in first-seen order. + console_imports: Vec, imports: Vec, } @@ -39,9 +43,15 @@ pub fn console_imports(path: &Path) -> Option> { let pe = Pe::parse(&data, Layout::File).ok()?; let mut all = pe.imports().unwrap_or_default(); all.extend(pe.delay_imports().unwrap_or_default()); + Some(console_imports_from(&all)) +} + +/// The console libraries in already-parsed imports. Shared with `run` so the text and JSON +/// reports agree without parsing the file twice. +fn console_imports_from(all: &[ImportDll]) -> Vec { let reg = crate::hle::registry(); let mut out: Vec = Vec::new(); - for d in &all { + for d in all { let key = crate::util::dll_key(&d.dll); let console = key == crate::hle::KERNELX || reg @@ -52,7 +62,29 @@ pub fn console_imports(path: &Path) -> Option> { out.push(key); } } - Some(out) + out +} + +/// Assemble the report from the parsed PE, so the JSON path can be tested without capturing stdout. +fn report(path: &Path, pe: &Pe, imports: Vec, console: Vec) -> Out { + let tls = pe.tls().ok().flatten().map(|t| t.total_len()); + let ex = pe.dir(crate::pe::DIR_EXCEPTION); + Out { + file: path.to_string_lossy().into_owned(), + machine: format!("{:#06x}", pe.machine), + image_base: format!("{:#x}", pe.image_base), + entry_rva: format!("{:#x}", pe.entry_rva), + size_of_image: format!("{:#x}", pe.size_of_image), + subsystem: pe.subsystem, + is_dll: pe.is_dll(), + has_relocations: pe.has_relocs(), + tls_template_bytes: tls, + exception_entries: ex.size / 12, + stack_reserve: format!("{:#x}", pe.stack_reserve), + is_console: !console.is_empty(), + console_imports: console, + imports, + } } fn status(s: &Source) -> String { @@ -95,22 +127,8 @@ pub fn run(path: &Path, json: bool) -> i32 { imports.push(Entry { dll: d.dll.clone(), function: e.what.to_string(), delay: d.delay, status: status(&s) }); } } - let tls = pe.tls().ok().flatten().map(|t| t.total_len()); - let ex = pe.dir(crate::pe::DIR_EXCEPTION); - let out = Out { - file: path.to_string_lossy().into_owned(), - machine: format!("{:#06x}", pe.machine), - image_base: format!("{:#x}", pe.image_base), - entry_rva: format!("{:#x}", pe.entry_rva), - size_of_image: format!("{:#x}", pe.size_of_image), - subsystem: pe.subsystem, - is_dll: pe.is_dll(), - has_relocations: pe.has_relocs(), - tls_template_bytes: tls, - exception_entries: ex.size / 12, - stack_reserve: format!("{:#x}", pe.stack_reserve), - imports, - }; + let console = console_imports_from(&all); + let out = report(path, &pe, imports, console); if json { println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default()); return 0; @@ -119,12 +137,13 @@ pub fn run(path: &Path, json: bool) -> i32 { println!("Type: {} x64, subsystem {}", if out.is_dll { "DLL" } else { "EXE" }, out.subsystem); println!("ImageBase: {} (size {}, entry +{})", out.image_base, out.size_of_image, out.entry_rva); println!("Relocations: {}", if out.has_relocations { "yes" } else { "NO (the image must be mapped at ImageBase)" }); - println!("Static TLS: {}", tls.map(|n| format!("{n} B (handled by the TLS carrier)")).unwrap_or_else(|| "none".into())); + println!("Static TLS: {}", out.tls_template_bytes.map(|n| format!("{n} B (handled by the TLS carrier)")).unwrap_or_else(|| "none".into())); println!("Exceptions: {} .pdata entries", out.exception_entries); println!("Stack: {}", out.stack_reserve); - match console_imports(path) { - Some(c) if !c.is_empty() => println!("Console game: yes (imports {})", c.join(", ")), - _ => println!("Console game: NO – no kernelx / xgameruntime / d3d12_xs imports (a regular Windows program?)"), + if out.is_console { + println!("Console game: yes (imports {})", out.console_imports.join(", ")); + } else { + println!("Console game: NO – no kernelx / xgameruntime / d3d12_xs imports (a regular Windows program?)"); } let mut per_dll: BTreeMap> = BTreeMap::new(); for e in &out.imports { @@ -154,3 +173,32 @@ pub fn run(path: &Path, json: bool) -> i32 { } 0 } + +#[cfg(test)] +mod tests { + use super::*; + + fn dll(name: &str) -> ImportDll { + ImportDll { dll: name.into(), delay: false, entries: Vec::new(), module_handle_rva: 0 } + } + + #[test] + fn console_verdict_counts_regular_and_delay_imports_once() { + let all = [dll("kernel32.dll"), dll("KERNELX.DLL"), dll("D3D12_XS.dll"), dll("xgameruntime.dll"), dll("kernelx.dll")]; + assert_eq!(console_imports_from(&all), ["kernelx.dll", "d3d12_xs.dll", "xgameruntime.dll"]); + assert!(console_imports_from(&[dll("kernel32.dll"), dll("user32.dll")]).is_empty()); + } + + #[test] + fn json_report_carries_the_console_verdict() { + let path = std::env::current_exe().unwrap(); + let data = std::fs::read(&path).unwrap(); + let pe = Pe::parse(&data, Layout::File).unwrap(); + let json = serde_json::to_value(report(&path, &pe, Vec::new(), vec!["kernelx.dll".into()])).unwrap(); + assert_eq!(json["is_console"], true); + assert_eq!(json["console_imports"][0], "kernelx.dll"); + let json = serde_json::to_value(report(&path, &pe, Vec::new(), Vec::new())).unwrap(); + assert_eq!(json["is_console"], false); + assert_eq!(json["console_imports"].as_array().unwrap().len(), 0); + } +} From a9f22691e14fcf39ad24c5d1a8b795d5b1978f89 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:40:00 -0700 Subject: [PATCH 14/34] Rect lists: the CPU expansion finds the rect's corner, not always v1 From ivall/xcl#266 by @Kalmarv, squashed. --- crates/xcl/src/hle/d3d12x/bind.rs | 143 ++++++++++++++++++++++++++---- 1 file changed, 126 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f62009c..b52b315 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -254,11 +254,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us /// (the caller draws the three vertices as a triangle – half of each rectangle). /// /// The PC has no rect lists. The fourth corner is made here, on the CPU, from the title's -/// vertex data: v3 = v0 + v2 − v1 (seen in a retail title's full-screen passes: (−1,1) (−1,−1) -/// (1,−1) with texture coordinates (0,0) (0,1) (1,1) – the missing corner is (1,1), (1,0)). -/// The vertex layout is not looked at: each 4-byte word that is the same in all three vertices -/// is kept (a packed colour), any other is taken as a float. Vertices a shader makes from the -/// vertex index alone (no vertex buffer) are not expanded. +/// vertex data (`expand_rect`). Vertices a shader makes from the vertex index alone (no vertex +/// buffer) are not expanded. unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) -> bool { if !cpu_rect_expansion(with(this, |s| s.pso)) { return false; @@ -279,19 +276,12 @@ unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertic if p.is_null() { return false; } - let word = |v: usize, w: usize| (at as *const u8).add(v * s + w * 4).cast::().read_unaligned(); + let out = std::slice::from_raw_parts_mut(p, rects * 6 * s); + // (a copy of each rect: the title may be writing its vertices) + let mut rect = vec![0u8; 3 * s]; for r in 0..rects { - let out = p.add(r * 6 * s); - let src = (at as *const u8).add(r * 3 * s); - // v0 v1 v2, then v0 v2 v3 - std::ptr::copy_nonoverlapping(src, out, 3 * s); - std::ptr::copy_nonoverlapping(src, out.add(3 * s), s); - std::ptr::copy_nonoverlapping(src.add(2 * s), out.add(4 * s), s); - for w in 0..s / 4 { - let (a, b, c) = (word(r * 3, w), word(r * 3 + 1, w), word(r * 3 + 2, w)); - let d = if a == b && b == c { a } else { (f32::from_bits(a) + f32::from_bits(c) - f32::from_bits(b)).to_bits() }; - out.add(5 * s + w * 4).cast::().write_unaligned(d); - } + std::ptr::copy_nonoverlapping((at as *const u8).add(r * 3 * s), rect.as_mut_ptr(), 3 * s); + expand_rect(&rect, s, &mut out[r * 6 * s..][..6 * s]); } views.push((slot, D3D12_VERTEX_BUFFER_VIEW { BufferLocation: super::list_x::pc_va_of(p as u64), SizeInBytes: (rects * 6 * s) as u32, StrideInBytes: stride })); } @@ -311,6 +301,69 @@ unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertic true } +/// The corner of a rect list's rect – the vertex between the other two – from its three +/// vertices (`v`, `s` bytes each). It is not always the same vertex: (x1,y1) (x1,y2) (x2,y1) +/// has it at v0 (Mesa's r600 and radeonsi blits), (x1,y1) (x1,y2) (x2,y2) at v1 +/// (xf86-video-ati's r600 EXA; a retail title's full-screen passes: (−1,1) (−1,−1) (1,−1)). +/// The vertex layout is not looked at. A word two of the vertices share (an x or a y, and what +/// goes with it – a texture coordinate) differs in the third, the far end of one of the +/// corner's edges: the corner is the vertex that differs alone in the fewest words. No single +/// such vertex (not three corners of a screen-aligned rect): v1. +fn rect_corner(v: &[u8], s: usize) -> usize { + let word = |i: usize, w: usize| u32::from_le_bytes(v[i * s + w * 4..][..4].try_into().unwrap()); + let mut alone = [0u32; 3]; + for w in 0..s / 4 { + let (a, b, c) = (word(0, w), word(1, w), word(2, w)); + if a == b && b != c { + alone[2] += 1; + } else if a == c && a != b { + alone[1] += 1; + } else if b == c && a != b { + alone[0] += 1; + } + } + let least = alone.into_iter().min().unwrap_or(0); + match alone.iter().filter(|&&n| n == least).count() { + 1 => alone.iter().position(|&n| n == least).unwrap_or(1), + _ => 1, + } +} + +/// One rect of a rect list (`v`: its three vertices, `s` bytes each) as two triangles (`out`: +/// six vertices). The fourth corner is the one opposite the rect's corner (`rect_corner`): +/// a + b − corner of the other two vertices a and b, each 4-byte word that is not the same in +/// all three vertices (those are kept – a packed colour) taken as a float. Both triangles +/// start with v0 and wind as v0 v1 v2 does: what a pixel shader reads flat (on the PC a +/// triangle's first vertex's value) is v0's in both halves. +fn expand_rect(v: &[u8], s: usize, out: &mut [u8]) { + let k = rect_corner(v, s); + let word = |i: usize, w: usize| u32::from_le_bytes(v[i * s + w * 4..][..4].try_into().unwrap()); + let fourth = |w: usize| { + let (c, a, b) = (word(k, w), word((k + 1) % 3, w), word((k + 2) % 3, w)); + if c == a && a == b { + c + } else { + (f32::from_bits(a) + f32::from_bits(b) - f32::from_bits(c)).to_bits() + } + }; + // 3: the fourth corner d. (corner, a, b) is v0 v1 v2 in its order or rotated, and (corner, + // a, d), (corner, d, b) and (a, d, b) wind as it does + let order: [usize; 6] = match k { + 0 => [0, 1, 3, 0, 3, 2], + 1 => [0, 1, 2, 0, 2, 3], + _ => [0, 1, 2, 0, 3, 1], + }; + for (to, from) in out.chunks_exact_mut(s).zip(order) { + if from < 3 { + to.copy_from_slice(&v[from * s..][..s]); + } else { + for (w, word) in to.chunks_exact_mut(4).enumerate() { + word.copy_from_slice(&fourth(w).to_le_bytes()); + } + } + } +} + /// Whether a rect list drawn with the bound pipeline `pso` is expanded on the CPU (`draw_rects`): /// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both /// would draw every rect twice (each CPU half is three corners of the rect). @@ -1185,6 +1238,62 @@ mod tests { assert!(cpu_rect_expansion(with_gs)); } + /// `expand_rect` on vertices of position (x, y, 0, 1), texture coordinate (u, v) and a packed + /// colour: the six vertices' positions and texture coordinates, and whether every vertex kept + /// the position's z and w and the colour. + fn expanded(corners: [[f32; 2]; 3], uv: impl Fn([f32; 2]) -> [f32; 2]) -> (Vec<([f32; 2], [f32; 2])>, bool) { + const STRIDE: usize = 28; + let mut v = Vec::new(); + for p in corners { + let t = uv(p); + for f in [p[0], p[1], 0.0, 1.0, t[0], t[1]] { + v.extend_from_slice(&f.to_le_bytes()); + } + v.extend_from_slice(&0xFF33_6699u32.to_le_bytes()); + } + let mut out = vec![0u8; 6 * STRIDE]; + expand_rect(&v, STRIDE, &mut out); + let f = |b: &[u8], w: usize| f32::from_le_bytes(b[w * 4..][..4].try_into().unwrap()); + let kept = out.chunks_exact(STRIDE).all(|b| f(b, 2) == 0.0 && f(b, 3) == 1.0 && b[24..] == 0xFF33_6699u32.to_le_bytes()); + (out.chunks_exact(STRIDE).map(|b| ([f(b, 0), f(b, 1)], [f(b, 4), f(b, 5)])).collect(), kept) + } + + /// A rect list's rect on the CPU, for each vertex its corner can be: (x1,y1) (x1,y2) (x2,y1) + /// – v0, as Mesa's r600 and radeonsi blits send it –, (x1,y1) (x1,y2) (x2,y2) – v1, as + /// xf86-video-ati's r600 EXA does –, and v2. The two triangles are the rect's halves along + /// one diagonal, wind as v0 v1 v2 does and start with v0; the fourth corner continues the + /// texture coordinate. Synthetic: the rect is the expectation, not a measurement of hardware. + #[test] + fn rects_expanded_on_the_cpu_have_the_corner_opposite_their_own() { + let (x1, x2, y1, y2) = (16.0f32, 48.0, 8.0, 24.0); + let uv = |[x, y]: [f32; 2]| [(x - x1) / (x2 - x1), (y - y1) / (y2 - y1)]; + let area = |t: &[([f32; 2], [f32; 2])]| (t[1].0[0] - t[0].0[0]) * (t[2].0[1] - t[0].0[1]) - (t[2].0[0] - t[0].0[0]) * (t[1].0[1] - t[0].0[1]); + for (name, corners) in [ + ("corner v0", [[x1, y1], [x1, y2], [x2, y1]]), + ("corner v1", [[x1, y1], [x1, y2], [x2, y2]]), + ("corner v1, the other way round", [[x1, y2], [x1, y1], [x2, y1]]), + ("corner v2", [[x1, y2], [x2, y1], [x1, y1]]), + ] { + let (v, kept) = expanded(corners, uv); + let pos: Vec<[f32; 2]> = v.iter().map(|p| p.0).collect(); + assert!(kept, "{name}: z, w and the colour are kept"); + for corner in [[x1, y1], [x1, y2], [x2, y1], [x2, y2]] { + assert!(pos.contains(&corner), "{name}: no vertex at {corner:?} in {pos:?}"); + } + assert!(v.iter().all(|&(p, t)| t == uv(p)), "{name}: texture coordinates {v:?}"); + // each triangle is half the rect, in the winding of the title's three vertices + let first = area(&[(corners[0], [0.0; 2]), (corners[1], [0.0; 2]), (corners[2], [0.0; 2])]); + assert_eq!(first.abs(), (x2 - x1) * (y2 - y1)); + assert_eq!([area(&v[..3]), area(&v[3..])], [first, first], "{name}: {pos:?}"); + // … on either side of a diagonal, and both start with v0 + assert_eq!(pos[..3].iter().filter(|p| pos[3..].contains(p)).count(), 2, "{name}: {pos:?}"); + assert_eq!([pos[0], pos[3]], [corners[0], corners[0]], "{name}: {pos:?}"); + } + // not three corners of a screen-aligned rect: as before, v0 + v2 − v1 + let (v, _) = expanded([[0.0, 0.0], [8.0, 2.0], [10.0, 9.0]], |p| p); + assert_eq!(v.iter().map(|p| p.0).collect::>(), [[0.0, 0.0], [8.0, 2.0], [10.0, 9.0], [0.0, 0.0], [10.0, 9.0], [2.0, 7.0]]); + } + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. fn test_rts0_blob() -> Vec { let words: [u32; 12] = [ From c066d0e48f01e563c82482222a28abfe25a20800 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:40:00 -0700 Subject: [PATCH 15/34] Tests: the debug-layer tests' SKIPPED lines go straight to stderr From ivall/xcl#264 by @PHeitor1, squashed. --- crates/xcl/tests/e2e.rs | 4 +++- crates/xcl/tests/texture_states.rs | 13 ++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 2d7935c..521c8ec 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -248,7 +248,9 @@ fn test_title_draws_with_a_root_signature_under_the_debug_layer() { let sys = PathBuf::from(std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into())).join("System32"); for dll in ["d3d12SDKLayers.dll", "xgameruntime.dll"] { if !sys.join(dll).is_file() { - eprintln!("SKIPPED test_title_draws_with_a_root_signature_under_the_debug_layer: no {dll}"); + // straight to stderr: libtest captures eprintln!, and scripts/test.ps1 counts this line + use std::io::Write; + let _ = writeln!(std::io::stderr(), "SKIPPED test_title_draws_with_a_root_signature_under_the_debug_layer: no {dll}"); return; } } diff --git a/crates/xcl/tests/texture_states.rs b/crates/xcl/tests/texture_states.rs index 28d4e9b..5406d8c 100644 --- a/crates/xcl/tests/texture_states.rs +++ b/crates/xcl/tests/texture_states.rs @@ -12,6 +12,13 @@ use xcl::gpu::texture::{self, Subresource}; const SRV: D3D12_RESOURCE_STATES = texture::SHADER_READ; +/// `SKIPPED : ` straight to stderr: libtest captures `println!` / `eprintln!`, so +/// the line would show only with `--nocapture` and `scripts/test.ps1` would not count it. +fn skipped(reason: &str) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "SKIPPED uploads_start_from_each_subresources_state: {reason}"); +} + /// The debug layer's error and corruption messages since the last call (then cleared). unsafe fn errors(q: &ID3D12InfoQueue) -> Vec { let mut out = Vec::new(); @@ -51,16 +58,16 @@ fn uploads_start_from_each_subresources_state() { match xcl::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { Ok(d) => d.EnableDebugLayer(), Err(e) => { - println!("SKIPPED uploads_start_from_each_subresources_state: no D3D12 debug layer ({e})"); + skipped(&format!("no D3D12 debug layer ({e})")); return; } } let Ok(dev) = xcl::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { - println!("SKIPPED uploads_start_from_each_subresources_state: no GPU"); + skipped("no GPU"); return; }; let Ok(q) = dev.cast::() else { - println!("SKIPPED uploads_start_from_each_subresources_state: the device has no debug layer"); + skipped("the device has no debug layer"); return; }; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); From 2c44f09f6323b41e825e8b97decfc40f1e9c77ca Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:40:00 -0700 Subject: [PATCH 16/34] this_first: a test of the stale-vtable return buffer and either argument order From ivall/xcl#263 by @ryosen0, squashed. --- crates/xcl/src/hle/d3d12x/real.rs | 46 +++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 70161e1..9ff59f7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5165,6 +5165,52 @@ mod rect_list_pso_tests { } } +#[cfg(test)] +mod this_first_tests { + use super::*; + + /// `this_first`: either argument order, and a return buffer whose first word is a stale copy + /// of the object's vtable pointer (7a033c8: the retail game's C-way call wrote its result + /// over the device). Synthetic objects; no GPU and no title. + #[test] + fn a_return_buffer_with_a_stale_vtable_copy_is_not_the_object() { + let pc = [0usize; 32]; + let ext = [pc.as_ptr() as usize, 0]; + let vtbl = ext.as_ptr() as usize + 8; + EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(vtbl); + let plain = 0x1234_5678usize; + let p = &plain as *const usize as *mut c_void; + // an object off the stack (as a real device is), and a stack buffer holding a stale copy + // of its vtable pointer - the retail game's case + let obj = Box::into_raw(Box::new([vtbl])) as *mut c_void; + let buf = [vtbl]; + let b = buf.as_ptr() as *mut c_void; + unsafe { + assert!(is_adopted(obj) && is_adopted(b), "both look adopted"); + // one adopted: that one is the object, either position + assert!(this_first(obj, p)); + assert!(!this_first(p, obj)); + // neither adopted: unchanged (the C way is assumed) + assert!(!this_first(p, p) && !this_first(std::ptr::null_mut(), std::ptr::null_mut())); + // one null argument: the other is taken as `this`, either position + assert!(this_first(obj, std::ptr::null_mut())); + assert!(!this_first(std::ptr::null_mut(), obj)); + // both adopted, one on this thread's stack: the stack one is the buffer, so the heap + // one is `this` in either order - what 7a033c8 fixed + assert!(this_first(obj, b)); + assert!(!this_first(b, obj)); + // both on the stack, neither the device: `a` (the C++ way) + let stale = [vtbl]; + let s = stale.as_ptr() as *mut c_void; + assert!(this_first(b, s) && this_first(s, b)); + drop(Box::from_raw(obj as *mut [usize; 1])); + } + if let Some(g) = EXTS.lock().unwrap().as_mut() { + g.remove(&vtbl); + } + } +} + #[cfg(test)] mod cache_report_tests { use super::*; From 82a7f7410179f3e3e1d9b0864f4a59dcfd64aa80 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:40:00 -0700 Subject: [PATCH 17/34] Runtime: validate Zen 2 ISA features and CPUID at startup in launcher and host From ivall/xcl#259 by @slopgobblercobbler, squashed. --- crates/xcl/src/host.rs | 48 +++++++++++++++++ crates/xcl/src/launcher.rs | 105 +++++++++++++++++++++++++++++-------- 2 files changed, 130 insertions(+), 23 deletions(-) diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 4d4bf80..3208153 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -8,6 +8,18 @@ use crate::config::Boot; pub static HOST_MODE: AtomicBool = AtomicBool::new(false); +/// Validate that this CPU has the console Zen 2 instruction set extensions. +/// Returns Ok(()) if all features are present or if XCL_SKIP_CPU_CHECK is set; +/// returns Err(missing) listing any missing features. +pub fn check_cpu_requirements() -> Result<(), Vec<&'static str>> { + let missing = crate::launcher::missing_console_cpu_features(); + if missing.is_empty() || std::env::var_os("XCL_SKIP_CPU_CHECK").is_some() { + Ok(()) + } else { + Err(missing) + } +} + pub fn host_main(boot_path: &Path) -> i32 { let boot: Boot = match std::fs::read_to_string(boot_path).map_err(|e| e.to_string()).and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string())) { Ok(b) => b, @@ -29,6 +41,22 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + + // the console's CPU is a Zen 2: its titles are compiled for it and fault with an illegal + // instruction (0xC000001D) on a PC without its extensions – said here instead + let missing = crate::launcher::missing_console_cpu_features(); + if !missing.is_empty() { + if std::env::var_os("XCL_SKIP_CPU_CHECK").is_some() { + crate::xlog_warn!("this CPU lacks {} (XCL_SKIP_CPU_CHECK set, continuing)", missing.join(", ")); + println!(" WARNING: this CPU lacks {} (XCL_SKIP_CPU_CHECK set, continuing)", missing.join(", ")); + } else { + let msg = crate::launcher::format_missing_cpu_message(&missing); + crate::xlog_error!("{msg}"); + eprintln!("xcl host: {msg}"); + crate::report::write_final(Some(format!("CPU lacks required Zen 2 features: {}", missing.join(", ")))); + return 0x7C1_0003; + } + } // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) if std::env::var_os("XCL_ACTIVITY").is_some() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { @@ -146,3 +174,23 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::log::flush(); code as i32 } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_cpu_validation() { + std::env::set_var("XCL_SKIP_CPU_CHECK", "1"); + assert!(check_cpu_requirements().is_ok()); + std::env::remove_var("XCL_SKIP_CPU_CHECK"); + + let result = check_cpu_requirements(); + let expected_missing = crate::launcher::missing_console_cpu_features(); + if expected_missing.is_empty() { + assert!(result.is_ok()); + } else { + assert_eq!(result.unwrap_err(), expected_missing); + } + } +} diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index af591db..c1b5592 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -360,10 +360,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { if std::env::var_os("XCL_SKIP_CPU_CHECK").is_some() { println!(" WARNING: this CPU lacks {} (XCL_SKIP_CPU_CHECK set, continuing)", missing.join(", ")); } else { - eprintln!( - "xcl: this CPU lacks {}: Xbox Series X|S games are compiled for the console's Zen 2 CPU\n and need them (they would stop with an illegal instruction). XCL_SKIP_CPU_CHECK=1 runs anyway.", - missing.join(", ") - ); + eprintln!("xcl: {}", format_missing_cpu_message(&missing)); return 2; } } @@ -384,28 +381,53 @@ pub fn run(target: &Path, args: &[String]) -> i32 { code as i32 } +/// Formats a friendly error message listing the missing console Zen 2 CPU features. +pub fn format_missing_cpu_message(missing: &[&str]) -> String { + format!( + "this CPU lacks {}: Xbox Series X|S games are compiled for the console's Zen 2 CPU\n and need them (they would stop with an illegal instruction). XCL_SKIP_CPU_CHECK=1 runs anyway.", + missing.join(", ") + ) +} + +/// Helper to evaluate CPU features using a query closure, returning missing feature names. +pub fn check_cpu_features bool>(has: F) -> Vec<&'static str> { + const REQUIRED: &[(&str, &str)] = &[ + ("sse4.2", "SSE4.2"), + ("popcnt", "POPCNT"), + ("avx", "AVX"), + ("avx2", "AVX2"), + ("fma", "FMA"), + ("f16c", "F16C"), + ("bmi1", "BMI1"), + ("bmi2", "BMI2"), + ("lzcnt", "LZCNT"), + ("movbe", "MOVBE"), + ]; + let mut missing = Vec::new(); + for &(feature, name) in REQUIRED { + if !has(feature) { + missing.push(name); + } + } + missing +} + /// Instruction set extensions of the console's Zen 2 that this CPU does not have (titles are /// compiled for them: AVX2, FMA, F16C, BMI1 / BMI2, LZCNT, POPCNT, MOVBE, SSE4.2). pub fn missing_console_cpu_features() -> Vec<&'static str> { - let mut missing = Vec::new(); - macro_rules! need { - ($($feature:tt => $name:literal),* $(,)?) => { - $(if !std::arch::is_x86_feature_detected!($feature) { missing.push($name); })* - }; - } - need!( - "sse4.2" => "SSE4.2", - "popcnt" => "POPCNT", - "avx" => "AVX", - "avx2" => "AVX2", - "fma" => "FMA", - "f16c" => "F16C", - "bmi1" => "BMI1", - "bmi2" => "BMI2", - "lzcnt" => "LZCNT", - "movbe" => "MOVBE", - ); - missing + check_cpu_features(|f| match f { + "sse4.2" => std::arch::is_x86_feature_detected!("sse4.2"), + "popcnt" => std::arch::is_x86_feature_detected!("popcnt"), + "avx" => std::arch::is_x86_feature_detected!("avx"), + "avx2" => std::arch::is_x86_feature_detected!("avx2"), + "fma" => std::arch::is_x86_feature_detected!("fma"), + "f16c" => std::arch::is_x86_feature_detected!("f16c"), + "bmi1" => std::arch::is_x86_feature_detected!("bmi1"), + "bmi2" => std::arch::is_x86_feature_detected!("bmi2"), + "lzcnt" => std::arch::is_x86_feature_detected!("lzcnt"), + "movbe" => std::arch::is_x86_feature_detected!("movbe"), + _ => false, + }) } fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result { @@ -649,4 +671,41 @@ mod tests { assert_eq!(quote("say \"hi\""), "\"say \\\"hi\\\"\""); assert_eq!(quote(""), "\"\""); } + + #[test] + fn cpu_feature_detection_identifies_missing_features() { + let all_present = check_cpu_features(|_| true); + assert!(all_present.is_empty()); + + let none_present = check_cpu_features(|_| false); + assert_eq!( + none_present, + vec!["SSE4.2", "POPCNT", "AVX", "AVX2", "FMA", "F16C", "BMI1", "BMI2", "LZCNT", "MOVBE"] + ); + + let missing_avx2 = check_cpu_features(|f| f != "avx2"); + assert_eq!(missing_avx2, vec!["AVX2"]); + + let missing_fma = check_cpu_features(|f| f != "fma"); + assert_eq!(missing_fma, vec!["FMA"]); + + let missing_bmi = check_cpu_features(|f| f != "bmi1" && f != "bmi2"); + assert_eq!(missing_bmi, vec!["BMI1", "BMI2"]); + + let missing_zen2_subset = check_cpu_features(|f| { + !["avx2", "fma", "bmi1", "bmi2", "popcnt", "sse4.2", "lzcnt"].contains(&f) + }); + assert_eq!( + missing_zen2_subset, + vec!["SSE4.2", "POPCNT", "AVX2", "FMA", "BMI1", "BMI2", "LZCNT"] + ); + } + + #[test] + fn missing_cpu_message_format() { + let msg = format_missing_cpu_message(&["AVX2", "FMA", "BMI1", "BMI2", "POPCNT", "SSE4.2", "LZCNT"]); + assert!(msg.contains("this CPU lacks AVX2, FMA, BMI1, BMI2, POPCNT, SSE4.2, LZCNT")); + assert!(msg.contains("Zen 2 CPU")); + assert!(msg.contains("XCL_SKIP_CPU_CHECK=1")); + } } From d8dd022dba2823f050ca2e6ffe586be901f3e6ba Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:29:43 -0700 Subject: [PATCH 18/34] D3D12.X: sRGB and R9G9B9E5 UAV textures keep both view families An R9G9B9E5 target with unordered access became R16G16B16A16_FLOAT, which holds the values exactly but leaves no way to write the packed 32 bits (an R32_UINT view of it is an invalid format pair). It is R32_TYPELESS now, the console's 32 bits a texel: R32_FLOAT for the shaders that write values, R32_UINT for those that write the packed bits. An sRGB texture with unordered access is typeless on the PC (it has no sRGB UAV): the UAV views take the UNORM format, the SRV / RTV views keep sRGB. A UAV / SRV / RTV without a description of a typeless resource gets a typed one, which the console's own format describes. GetResourceAllocationInfo answers a format the PC has no layout for with the console's layout of a same-bits-per-texel stand-in instead of u64::MAX. --- crates/xcl/src/hle/d3d12x/device_x.rs | 140 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 178 ++++++++++++++++++++++++-- 2 files changed, 301 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index e8dbfb0..135731c 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -676,9 +676,19 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { } // R9G9B9E5_SHAREDEXP targets: the PC renders into the format neither as a target nor through // unordered access (a retail game's 1920x1080 one on the Series S profile, flags 0x300005: - // E_INVALIDARG, then its assertion) – half floats hold every shared-exponent value exactly + // E_INVALIDARG, then its assertion). R32_TYPELESS, the console's 32 bits a texel: its views + // are R32_FLOAT for the shaders that write shared-exponent values as floats (exact, every + // 9E5 value is), and R32_UINT for those that write the packed 32 bits themselves if format == 67 && flags & 5 != 0 { - d[0x20..0x24].copy_from_slice(&10u32.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&39u32.to_le_bytes()); + } + // sRGB textures the console also lets shaders write: the PC has no sRGB unordered access + // (a retail game's 2048x2048 R8G8B8A8 one: E_INVALIDARG) – typeless, so the UAV views are + // the UNORM format (`pc_unorm_format`) and the SRV / RTV views keep the sRGB one + if flags & 4 != 0 { + if let Some(t) = srgb_typeless(format) { + d[0x20..0x24].copy_from_slice(&t.to_le_bytes()); + } } // a depth buffer the console also lets shaders write (a retail game's: ALLOW_DEPTH_STENCIL | // ALLOW_UNORDERED_ACCESS): the PC refuses the pair – the depth buffer stays @@ -721,11 +731,43 @@ fn depth_typeless(f: u32) -> Option { pub fn pc_target_format(f: u32) -> u32 { match f { 86 | 115 => 28, - 67 => 10, + 67 => 41, f => pc_view_format(f), } } +/// The typeless format of an sRGB one that a UAV has to reach (`pc_resource_desc`): the +/// uncompressed ones, the only ones a UAV can name. None: not one of those. +fn srgb_typeless(f: u32) -> Option { + Some(match f { + 29 => 27, // R8G8B8A8_UNORM_SRGB + 91 => 90, // B8G8R8A8_UNORM_SRGB + 93 => 92, // B8G8R8X8_UNORM_SRGB + _ => return None, + }) +} + +/// The UNORM format of an sRGB one: what a UAV view of an sRGB texture is on the PC, which has +/// no sRGB unordered access. +pub fn pc_unorm_format(f: u32) -> u32 { + match f { + 29 => 28, + 72 => 71, + 75 => 74, + 78 => 77, + 91 => 87, + 93 => 88, + 99 => 98, + f => f, + } +} + +/// Whether a format is typeless: its views name the typed formats of its family, so a resource +/// in it needs one (`pc_shader_view_format`). +pub fn typeless_format(f: u32) -> bool { + matches!(f, 1 | 5 | 9 | 15 | 19 | 23 | 27 | 33 | 39 | 44 | 48 | 53 | 60 | 70 | 73 | 76 | 79 | 82 | 90 | 92 | 94 | 97) +} + /// The format a shader's view of a resource whose PC format is `resource` has on the PC (`view` /// 0: the resource's own). The console names depth buffers' views plainly (R16_UNORM of a D16S8 /// buffer, R32_FLOAT of a D32 one, even the depth format itself); the PC wants its family's @@ -744,8 +786,12 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (53 | 55, 0 | 53 | 55) => 56, // a target made R8G8B8A8 (`pc_resource_desc`) (28, 86 | 115) => 28, - // an R9G9B9E5 target made half floats - (10, 67) => 10, + // an R9G9B9E5 target made R32_TYPELESS: floats, and a view that names the format itself + (39, 67) => 41, + // an sRGB texture made typeless for its UAVs: its own views stay sRGB + (27, 0) => 29, + (90, 0) => 91, + (92, 0) => 93, (_, v) => v, } } @@ -784,6 +830,13 @@ pub(super) unsafe extern "system" fn get_resource_allocation_info_x(a: *mut c_vo let d = pc_resource_desc(&x); let mut r = [0u64; 2]; pc(this, &mut r, mask, 1, &d); + // a format the PC has no layout for (it answers u64::MAX, and a title asserts): + // the console's layout of a format of the same bits per texel + if r[0] == u64::MAX || r[1] == 0 { + if let Some(t) = standin_texture(&x) { + r = [t.size(), t.alignment()]; + } + } (r[0], r[1]) } }; @@ -800,6 +853,29 @@ pub(super) unsafe extern "system" fn get_resource_allocation_info_x(a: *mut c_vo ret } +/// The console's layout of a texture in a format that XG does not model, by a stand-in of the +/// same bits per texel (`pc_standin_format`): a title's allocation queries must not fail on a +/// format the PC has no layout for. None: no such format. +fn standin_texture(x: &[u8; 0x38]) -> Option { + let mut s = *x; + let f = u32::from_le_bytes(s[0x20..0x24].try_into().unwrap()); + s[0x20..0x24].copy_from_slice(&pc_standin_format(f)?.to_le_bytes()); + crate::hle::xg::Texture::new(&s).ok() +} + +/// A PC format whose console layout stands in for one that the PC has none for, of the same +/// bits per texel: R1 (8), the packed 4:2:2 pair (16 a pixel), XR_BIAS (32), and the 96-bit +/// ones, which take the smallest the PC has above them (128). None: not one of those. +pub fn pc_standin_format(f: u32) -> Option { + Some(match f { + 5..=8 => 2, // R32G32B32 family: R32G32B32A32_FLOAT + 66 => 61, // R1_UNORM: R8_UNORM + 68 | 69 => 56, // R8G8_B8G8 / G8R8_G8B8 (2 bytes a pixel): R16_UNORM + 89 => 28, // R10G10B10_XR_BIAS_A2_UNORM: R8G8B8A8_UNORM + _ => return None, + }) +} + /// device #108 (a retail game) GetResourceAllocationInfo2(visible mask, count, D3D12_RESOURCE_DESC1s, /// D3D12_RESOURCE_ALLOCATION_INFO1* each) -> {size, alignment} of them all, returned like #25's; /// each resource's {offset, alignment, size} goes to the last argument when there is one. @@ -1079,12 +1155,15 @@ mod tests { x[0x20] = 86; // B5G5R5A1 target that is also a UAV x[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); assert_eq!(desc(&x), (28, 0x5)); - x[0x20] = 67; // R9G9B9E5 target that is also a UAV (and console bits): half floats + x[0x20] = 67; // R9G9B9E5 target that is also a UAV (and console bits): R32_TYPELESS x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); - assert_eq!(desc(&x), (10, 0x5)); + assert_eq!(desc(&x), (39, 0x5)); x[0x30..0x34].copy_from_slice(&0x0u32.to_le_bytes()); // a sampled one stays R9G9B9E5 assert_eq!(desc(&x), (67, 0)); - assert_eq!((pc_shader_view_format(10, 67), pc_shader_view_format(67, 67), pc_target_format(67)), (10, 67, 10)); + // its target views are floats; a shader's own-format and packed-uint views are too / + // as they are (the same 32 bits a texel) + assert_eq!((pc_shader_view_format(39, 67), pc_shader_view_format(67, 67), pc_target_format(67)), (41, 67, 41)); + assert_eq!((pc_shader_view_format(39, 0), pc_shader_view_format(39, 42)), (41, 42)); // views: a D24S8 format or R16_UNORM of the D16S8 buffer read depth; stencil formats plane 1 assert_eq!(pc_shader_view_format(44, 45), 46); assert_eq!(pc_shader_view_format(44, 56), 46); @@ -1098,6 +1177,51 @@ mod tests { assert_eq!((pc_target_format(86), pc_target_format(118), pc_view_format(117)), (28, 45, 10)); } + /// sRGB textures the console also lets shaders write are typeless on the PC (it has no sRGB + /// unordered access): their UAV views are the UNORM format, their own views still sRGB. A + /// format the PC has no layout for gets the console's layout of the same bits a texel. + #[test] + fn srgb_uavs_and_unsupported_allocation_formats() { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&2048u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&2048u32.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + x[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let format = |x: &[u8; 0x38]| u32::from_le_bytes(pc_resource_desc(x)[0x20..0x24].try_into().unwrap()); + x[0x20..0x24].copy_from_slice(&29u32.to_le_bytes()); // R8G8B8A8_UNORM_SRGB, a UAV + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); + assert_eq!(format(&x), 27); + assert_eq!((pc_shader_view_format(27, 0), pc_unorm_format(pc_shader_view_format(27, 29))), (29, 28)); + x[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); // and a target + assert_eq!(format(&x), 27); + x[0x30..0x34].copy_from_slice(&0x1u32.to_le_bytes()); // a target alone stays sRGB + assert_eq!(format(&x), 29); + x[0x20..0x24].copy_from_slice(&91u32.to_le_bytes()); // B8G8R8A8_UNORM_SRGB, a UAV + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); + assert_eq!(format(&x), 90); + assert_eq!((pc_shader_view_format(90, 0), pc_unorm_format(91)), (91, 87)); + x[0x20..0x24].copy_from_slice(&72u32.to_le_bytes()); // BC1_UNORM_SRGB has no UAV + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); + assert_eq!(format(&x), 72); + + // a format the PC has no layout for: a stand-in of the same bits a texel + assert_eq!((pc_standin_format(89), pc_standin_format(68), pc_standin_format(66), pc_standin_format(6)), (Some(28), Some(56), Some(61), Some(2))); + assert_eq!((pc_standin_format(28), pc_standin_format(0), pc_standin_format(130)), (None, None, None)); + for f in [89u32, 68, 66, 6] { + x[0x20..0x24].copy_from_slice(&f.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&0x1u32.to_le_bytes()); + assert!(crate::hle::xg::Texture::new(&x).is_err(), "XG should not model {f}"); + let t = standin_texture(&x).unwrap_or_else(|| panic!("no stand-in for {f}")); + let (size, align) = (t.size(), t.alignment()); + assert!(size >= 2048 * 2048 && align.is_power_of_two(), "{f}: {size:#x} {align:#x}"); + } + // a format XG models is left to XG (`standin_texture` is only for the PC's refusals) + x[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); + assert!(standin_texture(&x).is_none()); + } + #[test] fn derived_pipeline_patches_land_on_the_desc_parts() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9e33bb0..a46f16b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1945,8 +1945,9 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) let mut out = match v { Some(v) => *v, None => { - // only a typeless depth buffer needs a description of its own - if !matches!(rf, 19 | 39 | 44 | 53) { + // only a typeless resource needs a description of its own (a depth buffer, and one + // `pc_resource_desc` made typeless for its views) + if !matches!(rf, 19 | 39 | 44 | 53) && !super::device_x::typeless_format(rf) { return None; } let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; @@ -1964,6 +1965,10 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) return None; } let f = super::device_x::pc_shader_view_format(rf, out.Format.0 as u32); + // a typeless resource whose family has no obvious view (none of the console's): as it was + if f == 0 { + return None; + } let stencil = super::device_x::stencil_view(rf, f); if v.is_some() && f == out.Format.0 as u32 && !stencil { return None; @@ -2165,14 +2170,57 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI crate::gpu::desc::buffer_words(va + first * elem as u64, stride, records, fmt) } -unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { - // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, - // `device_x::pc_resource_desc`: an invalid call, the device removed) - let mut copy = desc.as_ref().copied(); - if let (Some(c), Some(r)) = (copy.as_mut(), ID3D12Resource::from_raw_borrowed(&res)) { - let rf = r.GetDesc().Format.0 as u32; - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); +/// A UAV view desc `d` (None: the resource's own) of `rd` with the PC's format names +/// (`device_x::pc_shader_view_format`, `device_x::pc_unorm_format`) – None: as it is. A resource +/// the PC holds typeless (`pc_resource_desc`: an R9G9B9E5 target, an sRGB one with UAVs) needs a +/// typed desc of its own. +fn pc_uav_desc(rd: &D3D12_RESOURCE_DESC, d: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>) -> Option { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + if rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return None; + } + let rf = rd.Format.0 as u32; + let named = d.map_or(0, |c| c.Format.0 as u32); + let f = super::device_x::pc_unorm_format(super::device_x::pc_shader_view_format(rf, named)); + if named != 0 { + if f == named { + return None; + } + let mut c = *d?; + c.Format = DXGI_FORMAT(f as i32); + return Some(c); } + // the console's default view is the resource's own format; a typeless one has no such view + if f == rf || f == 0 { + return None; + } + let mut c = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT(f as i32), ..Default::default() }; + let dim = rd.Dimension.0 as u32; + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE1D.0 as u32 { + if rd.DepthOrArraySize > 1 { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + c.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV { ArraySize: rd.DepthOrArraySize as u32, ..Default::default() }; + } else { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + c.Anonymous.Texture1D = D3D12_TEX1D_UAV::default(); + } + } else if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 as u32 { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + c.Anonymous.Texture3D = D3D12_TEX3D_UAV { WSize: rd.DepthOrArraySize as u32, ..Default::default() }; + } else if rd.DepthOrArraySize > 1 { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + c.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { ArraySize: rd.DepthOrArraySize as u32, ..Default::default() }; + } else { + c.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + c.Anonymous.Texture2D = D3D12_TEX2D_UAV::default(); + } + Some(c) +} + +unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { + // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, an sRGB + // one of a texture made typeless: an invalid call, the device removed) + let copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_uav_desc(&r.GetDesc(), desc.as_ref())); let desc = copy.as_ref().map_or(desc, |c| c as *const _); super::present::note_use(res as usize, super::present::USE_UAV); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19)); @@ -4614,6 +4662,43 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // presentation tracking // --------------------------------------------------------------------------------------- +/// The view a render target view without a description has, for a texture `pc_resource_desc` +/// made typeless (an sRGB one with UAVs, an R9G9B9E5 target) – None: the resource's format is +/// a typed one. +fn default_rtv(d: &D3D12_RESOURCE_DESC) -> Option { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + let rf = d.Format.0 as u32; + if matches!(rf, 19 | 44 | 53) { + return None; + } + let f = super::device_x::pc_shader_view_format(rf, 0); + if f == rf { + return None; + } + let mut v = D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT(f as i32), ..Default::default() }; + let dim = d.Dimension.0 as u32; + let array = d.DepthOrArraySize; + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE1D.0 as u32 { + if array > 1 { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; + v.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_RTV { ArraySize: array as u32, ..Default::default() }; + } else { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; + v.Anonymous.Texture1D = D3D12_TEX1D_RTV::default(); + } + } else if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 as u32 { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; + v.Anonymous.Texture3D = D3D12_TEX3D_RTV { WSize: array as u32, ..Default::default() }; + } else if array > 1 { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_RTV { ArraySize: array as u32, ..Default::default() }; + } else { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + v.Anonymous.Texture2D = D3D12_TEX2D_RTV::default(); + } + Some(v) +} + unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); @@ -4623,6 +4708,11 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let rf = ID3D12Resource::from_raw_borrowed(&res).map_or(0, |r| r.GetDesc().Format.0 as u32); c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); } + // no description: the resource's format – which a texture made typeless is not one a view + // can have + if copy.is_none() { + copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_rtv(&r.GetDesc())); + } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); @@ -5477,6 +5567,76 @@ mod srv_tests { } } +#[cfg(test)] +mod typeless_uav_view_tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + fn rd(format: u32, array: u16) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2048, + Height: 2048, + DepthOrArraySize: array, + MipLevels: 1, + Format: DXGI_FORMAT(format as i32), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + } + } + + fn uav(format: u32, mip: u32) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(format as i32), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: mip, PlaneSlice: 0 } }, + } + } + + /// A resource the PC holds typeless (an sRGB texture with UAVs, an R9G9B9E5 target) gets a + /// typed UAV desc: the sRGB one's UNORM for shaders that write values, the shared-exponent + /// one's R32_FLOAT or, as the console names it, R32_UINT for the packed 32 bits. + #[test] + fn typeless_resources_get_typed_uav_descs() { + // sRGB typeless: a named sRGB view becomes UNORM, keeping its mip + let v = pc_uav_desc(&rd(27, 1), Some(&uav(29, 2))).expect("a UAV of an sRGB texture"); + assert_eq!((v.Format.0, v.ViewDimension.0), (28, D3D12_UAV_DIMENSION_TEXTURE2D.0)); + assert_eq!(unsafe { v.Anonymous.Texture2D }.MipSlice, 2); + // ... and the default view too + let v = pc_uav_desc(&rd(27, 1), None).expect("the sRGB texture's own UAV"); + assert_eq!((v.Format.0, v.ViewDimension.0), (28, D3D12_UAV_DIMENSION_TEXTURE2D.0)); + let v = pc_uav_desc(&rd(27, 3), None).expect("the sRGB array's own UAV"); + assert_eq!((v.Format.0, v.ViewDimension.0), (28, D3D12_UAV_DIMENSION_TEXTURE2DARRAY.0)); + assert_eq!(unsafe { v.Anonymous.Texture2DArray }.ArraySize, 3); + + // R9G9B9E5 typeless: floats for the console format, the packed bits' format as named + assert_eq!(pc_uav_desc(&rd(39, 1), Some(&uav(67, 0))).map(|v| v.Format.0), Some(41)); + assert_eq!(pc_uav_desc(&rd(39, 1), None).map(|v| v.Format.0), Some(41)); + assert!(pc_uav_desc(&rd(39, 1), Some(&uav(42, 0))).is_none(), "R32_UINT stays R32_UINT"); + + // a resource that is its own typed format is left as the title made it + assert!(pc_uav_desc(&rd(28, 1), Some(&uav(28, 0))).is_none()); + assert!(pc_uav_desc(&rd(28, 1), None).is_none()); + assert!(pc_uav_desc(&rd(67, 1), Some(&uav(67, 0))).is_none(), "a sampled R9G9B9E5 texture"); + + // an SRV of a typeless sRGB resource: its own view is the sRGB one + let s = pc_srv(&rd(27, 1), None).expect("the sRGB texture's own SRV"); + assert_eq!((s.Format.0, s.ViewDimension.0), (29, D3D12_SRV_DIMENSION_TEXTURE2D.0)); + let s = pc_srv(&rd(39, 1), None).expect("an R32_TYPELESS texture's own SRV"); + assert_eq!(s.Format.0, 41); + assert!(pc_srv(&rd(28, 1), None).is_none()); + + // the same for an RTV and, with no description, a view of the console's own format + let r = default_rtv(&rd(27, 1)).expect("the sRGB texture's own RTV"); + assert_eq!((r.Format.0, r.ViewDimension.0), (29, D3D12_RTV_DIMENSION_TEXTURE2D.0)); + let r = default_rtv(&rd(39, 3)).expect("the R9G9B9E5 target's own RTV"); + assert_eq!((r.Format.0, r.ViewDimension.0), (41, D3D12_RTV_DIMENSION_TEXTURE2DARRAY.0)); + assert_eq!(unsafe { r.Anonymous.Texture2DArray }.ArraySize, 3); + assert!(default_rtv(&rd(28, 1)).is_none()); + assert!(default_rtv(&rd(44, 1)).is_none(), "a depth buffer's views name it"); + } +} + #[cfg(test)] mod console_format_query_tests { use super::*; From 48111a1ad6707c5e4c8a56ee732e5a9afd4cf366 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:32:17 -0700 Subject: [PATCH 19/34] =?UTF-8?q?D3D12.X:=20review=20fixes=20=E2=80=93=20X?= =?UTF-8?q?R=5FBIAS=20is=20one=20XG=20models,=20and=20a=20typed=20RTV=20ne?= =?UTF-8?q?eds=20a=20format?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/xcl/src/hle/d3d12x/device_x.rs | 11 +++++------ crates/xcl/src/hle/d3d12x/real.rs | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 135731c..5882d50 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -864,14 +864,13 @@ fn standin_texture(x: &[u8; 0x38]) -> Option { } /// A PC format whose console layout stands in for one that the PC has none for, of the same -/// bits per texel: R1 (8), the packed 4:2:2 pair (16 a pixel), XR_BIAS (32), and the 96-bit -/// ones, which take the smallest the PC has above them (128). None: not one of those. +/// bits per texel: R1 (8), the packed 4:2:2 pair (16 a pixel), and the 96-bit ones, which take +/// the smallest the PC has above them (128). None: not one of those. pub fn pc_standin_format(f: u32) -> Option { Some(match f { 5..=8 => 2, // R32G32B32 family: R32G32B32A32_FLOAT 66 => 61, // R1_UNORM: R8_UNORM 68 | 69 => 56, // R8G8_B8G8 / G8R8_G8B8 (2 bytes a pixel): R16_UNORM - 89 => 28, // R10G10B10_XR_BIAS_A2_UNORM: R8G8B8A8_UNORM _ => return None, }) } @@ -1207,9 +1206,9 @@ mod tests { assert_eq!(format(&x), 72); // a format the PC has no layout for: a stand-in of the same bits a texel - assert_eq!((pc_standin_format(89), pc_standin_format(68), pc_standin_format(66), pc_standin_format(6)), (Some(28), Some(56), Some(61), Some(2))); - assert_eq!((pc_standin_format(28), pc_standin_format(0), pc_standin_format(130)), (None, None, None)); - for f in [89u32, 68, 66, 6] { + assert_eq!((pc_standin_format(68), pc_standin_format(66), pc_standin_format(6)), (Some(56), Some(61), Some(2))); + assert_eq!((pc_standin_format(28), pc_standin_format(0), pc_standin_format(89)), (None, None, None)); + for f in [68u32, 66, 6] { x[0x20..0x24].copy_from_slice(&f.to_le_bytes()); x[0x30..0x34].copy_from_slice(&0x1u32.to_le_bytes()); assert!(crate::hle::xg::Texture::new(&x).is_err(), "XG should not model {f}"); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a46f16b..c7505d2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4672,7 +4672,7 @@ fn default_rtv(d: &D3D12_RESOURCE_DESC) -> Option return None; } let f = super::device_x::pc_shader_view_format(rf, 0); - if f == rf { + if f == rf || f == 0 { return None; } let mut v = D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT(f as i32), ..Default::default() }; From a1eaed1e35f8209751b7d68fc10d8a9f062568ff Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:43:43 -0700 Subject: [PATCH 20/34] kernelx: the finest system timer for the title (choppy audio, #260) From ivall/xcl#300 by @AAigars, squashed. --- crates/xcl/src/hle/kernelx.rs | 46 +++++++++++++++++++++++++++++++++++ crates/xcl/src/host.rs | 1 + 2 files changed, 47 insertions(+) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0d4e64d..d499e54 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1360,6 +1360,8 @@ struct OsVersionInfoW { #[link(name = "ntdll", kind = "raw-dylib")] extern "system" { fn RtlGetVersion(info: *mut OsVersionInfoW) -> i32; + fn NtQueryTimerResolution(coarsest: *mut u32, finest: *mut u32, current: *mut u32) -> i32; + fn NtSetTimerResolution(desired: u32, set: u8, current: *mut u32) -> i32; } pub fn host_os_version() -> (u32, u32, u32) { @@ -1371,6 +1373,38 @@ pub fn host_os_version() -> (u32, u32, u32) { } } +/// The finest timer Windows offers (0.5 ms) for the title: with the default 15.6 ms tick every +/// sleep rounds up (a retail game's audio mixer ran at a third of real time). Windows 11 keeps +/// it while the window is hidden only when told to. +pub fn fine_timer() { + use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, ProcessPowerThrottling, SetProcessInformation, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, + }; + let state = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + StateMask: 0, + }; + let size = std::mem::size_of::() as u32; + let kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &state as *const _ as *const c_void, size) } != 0; + // in 100 ns units; "finest" is the smallest period the system supports + let (mut coarsest, mut finest, mut was) = (0u32, 0u32, 0u32); + if unsafe { NtQueryTimerResolution(&mut coarsest, &mut finest, &mut was) } < 0 || finest == 0 { + crate::xlog_warn!("timer: NtQueryTimerResolution failed – Windows' default resolution"); + return; + } + let mut now = 0u32; + let status = unsafe { NtSetTimerResolution(finest, 1, &mut now) }; + crate::xlog_info!( + "timer: {} (was {:.2} ms, now {:.2} ms; kept while the window is hidden: {})", + if status >= 0 { "finest resolution for the title" } else { "raising the resolution failed" }, + was as f64 / 10_000.0, + now as f64 / 10_000.0, + if kept { "yes" } else { "no" } + ); +} + pub unsafe extern "system" fn GetSystemOSVersion(out: *mut SystemOsVersionInfo) { if out.is_null() { return; @@ -1712,6 +1746,18 @@ pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { mod tests { use super::*; + #[test] + fn fine_timer_makes_short_sleeps_short() { + // Windows' Sleep (std::thread::sleep has its own high-resolution timer) + fine_timer(); + let t = std::time::Instant::now(); + for _ in 0..20 { + unsafe { windows_sys::Win32::System::Threading::Sleep(1) }; + } + let per = t.elapsed() / 20; + assert!(per < std::time::Duration::from_millis(5), "Sleep(1) took {per:?}: the 15.6 ms tick"); + } + #[test] fn affinity_masks_outside_the_process_are_fitted() { // a mask from the PC's processors is the title's choice diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 3208153..6dd5cb1 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -133,6 +133,7 @@ pub fn host_main(boot_path: &Path) -> i32 { } crate::stubs::init_db(&boot.config.stub_returns); crate::hle::init(&boot.config); + crate::hle::kernelx::fine_timer(); crate::loader::set_cache_dir(boot.cache_dir()); let mut dirs = vec![boot.game_root.clone()]; if let Some(p) = boot.exe_path.parent() { From 3d35428e2451801bf78151204fd2e65a5e25443e Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:43:43 -0700 Subject: [PATCH 21/34] xcl run: warn when title network access is enabled From ivall/xcl#299 by @SandimL, squashed. --- README.md | 3 +++ crates/xcl/src/launcher.rs | 8 ++++---- crates/xcl/src/preflight.rs | 17 ++++++++++++++++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e45055e..1aa2995 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,9 @@ next to `bathyal.exe`, directly next to `bathyal.exe`, in `%LOCALAPPDATA%\XCL\D3 size of 1.9's for translated compute programs and took an NVIDIA driver 1.4–2.2 times as long to build pipelines from ([#156](https://github.com/ivall/xcl/issues/156)). `bathyal run` prints the DXC it loaded, and `report.json` has it under `dxc`. +- **Network:** title network access is enabled by default. Use `XCL_NETWORK=0` when bringing up an + unfamiliar title: XCL blocks its WinHTTP and Winsock traffic while keeping loopback available. This + also prevents a title crash reporter from sending a process dump containing local paths and names. - **GPU:** developed on AMD RDNA4. The console's geometry and NGG programs run as a compute pass plus a mesh pass, so a GPU without mesh shaders draws none of them. On GPUs with 32-lane waves only (NVIDIA) console wave64 compute, geometry and mesh programs run as two 32-lane halves that exchange diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index c1b5592..5826dd6 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -484,10 +484,10 @@ fn summarize(boot: &Boot, code: u32, environment: &[crate::preflight::Check]) { println!(); println!("Game exited with code {code:#x} ({code})"); // repeated here: what the game printed in between has scrolled them away - let missing: Vec<_> = environment.iter().filter(|c| matches!(c.level, crate::preflight::Level::Warning | crate::preflight::Level::Error)).cloned().collect(); - if !missing.is_empty() { - println!("Missing on this PC (see the start of the run):"); - crate::preflight::print(&missing); + let warnings: Vec<_> = environment.iter().filter(|c| matches!(c.level, crate::preflight::Level::Warning | crate::preflight::Level::Error)).cloned().collect(); + if !warnings.is_empty() { + println!("Preflight warnings (see the start of the run):"); + crate::preflight::print(&warnings); } let Some(r) = report else { println!("No report – see the log: {}", boot.logs_dir().join("xcl.log").display()); diff --git a/crates/xcl/src/preflight.rs b/crates/xcl/src/preflight.rs index 230a29b..b2c00cf 100644 --- a/crates/xcl/src/preflight.rs +++ b/crates/xcl/src/preflight.rs @@ -47,6 +47,8 @@ pub struct Found { /// the DXC in that folder, for its version pub dxc_toolchain: crate::gpu::recomp::dxc::Toolchain, pub xgameruntime: bool, + /// Whether the title's WinHTTP and Winsock imports are blocked. + pub network_off: bool, pub gpu: Result, } @@ -93,6 +95,9 @@ pub fn checks(f: &Found) -> Vec { if !f.xgameruntime { v.push(check(Level::Warning, "no System32\\xgameruntime.dll: dialogs, text entry, game invites and game streaming are missing (XCL's own task queues, async and networking are used)", Some("install Gaming Services (Microsoft Store)"))); } + if !f.network_off { + v.push(check(Level::Warning, "title network access is enabled: a crash reporter may upload process memory", Some("set XCL_NETWORK=0 to block title network access (loopback remains available)"))); + } v } @@ -159,6 +164,7 @@ pub fn run(setting: &str) -> Vec { dxc: crate::gpu::recomp::dxc::location().map(|p| p.display().to_string()), dxc_toolchain: crate::gpu::recomp::dxc::toolchain(), xgameruntime: xgameruntime_present(), + network_off: crate::hle::netoff::enabled(), gpu: probe_gpu(setting), }; checks(&found) @@ -190,7 +196,7 @@ mod tests { } fn found(gpu: Gpu) -> Found { - Found { dxc: Ok(r"C:\dxc".into()), dxc_toolchain: dxc(1, 9), xgameruntime: true, gpu: Ok(gpu) } + Found { dxc: Ok(r"C:\dxc".into()), dxc_toolchain: dxc(1, 9), xgameruntime: true, network_off: true, gpu: Ok(gpu) } } fn dxc(major: u32, minor: u32) -> crate::gpu::recomp::dxc::Toolchain { @@ -248,6 +254,15 @@ mod tests { assert_eq!(checks(&f)[0].level, Level::Error); } + #[test] + fn network_access_is_a_warning_until_explicitly_disabled() { + let c = checks(&Found { network_off: false, ..found(gpu()) }); + let network = c.last().unwrap(); + assert_eq!(network.level, Level::Warning); + assert!(network.what.contains("network access is enabled"), "{network:?}"); + assert_eq!(network.fix.as_deref(), Some("set XCL_NETWORK=0 to block title network access (loopback remains available)")); + } + #[test] fn checks_round_trip_through_the_report() { let c = checks(&Found { dxc: Err("x".into()), ..found(gpu()) }); From bd13dc6279b2a733b556ec71d475d093d82692b0 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:44:31 -0700 Subject: [PATCH 22/34] KernelX / title textures: a GPU view of the title's CPU memory reads the CPU view (retail intro video, no green screen) From ivall/xcl#283 by @jessenic, squashed. The squash also carries #252, which #283 is stacked on (write-watched fallback for GPU-visible title memory outside the windows). Pairing is stricter than the PR: a no-access graphics reservation of 64 KiB pages is the GPU view of a same-size CPU reservation only when that one is the immediately preceding reservation and the only same-size CPU view without a GPU view; otherwise the reservation stays unpaired and a log line says so. Our `Entry::seq` from #269 is kept (uploads in placement order). --- CLAUDE.md | 16 -- CONTRIBUTING.md | 199 ------------------- crates/xcl/src/hle/d3d12x/title_textures.rs | 41 +++- crates/xcl/src/hle/kernelx.rs | 205 ++++++++++++++++++-- scripts/smoke.ps1 | 64 ------ 5 files changed, 222 insertions(+), 303 deletions(-) delete mode 100644 CLAUDE.md delete mode 100644 CONTRIBUTING.md delete mode 100644 scripts/smoke.ps1 diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index e30885a..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,16 +0,0 @@ -# Claude Code - -The instructions for agents in this repository are in `AGENTS.md`, and the rules for every -contributor are in `CONTRIBUTING.md`. Both apply to you: - -@AGENTS.md -@CONTRIBUTING.md - -Specific to Claude Code: - -- Plan a task that spans more than one subsystem or more than ~400 lines (plan mode), and propose - how to split it into PRs before you write code. -- Run the tests and report the real output; do not stop at "the tests should pass". -- Fill in the **AI use** section of the PR description with Claude Code and your exact model name. -- For a runtime change, run `scripts/smoke.ps1` on main and on the PR's head commit and paste both - `xcl-smoke` blocks; do not write or edit them by hand. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 75e48de..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,199 +0,0 @@ -# Contributing to XCL - -Thanks for helping. XCL gets far more pull requests than one maintainer can read carefully, so -these rules exist to make every PR **cheap to review and safe to merge**. A PR that ignores them -may be closed without a review, however good the code is. - -AI tools are welcome (see [AI-assisted contributions](#ai-assisted-contributions)). The rules are -the same for code written by hand and by an agent. - -## What a PR needs to be merged - -XCL gets more pull requests in an hour than anyone can test by hand, most of them written with AI -tools. So a PR is merged only when it shows that it was tested and that it breaks nothing. These are -checked before anything else; a PR that does not meet them waits (or is closed after a week). - -1. **Both required checks are green:** `CI` (build and tests on Windows, no GPU) and `PR checks` - (the description: the sections below, and the regression runs when they are needed). -2. **The whole suite ran on a GPU**, with the counts in **Tested** - (`cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored, and the SKIPPED tests). -3. **A PR that changes the runtime** (`crates/xcl/src` outside tests) **has a regression run on a real - title**: `scripts/smoke.ps1 -Game ` built from `main` and built from the PR's head - commit, both `xcl-smoke` blocks pasted under **Regression run**. The PR's block must name its head - commit with no uncommitted changes: rerun it after every push. It must show no device removal and - no crash, at least as many frames as `main` and no much higher peak commit. A run on a title that - does not reach the code the PR changes still counts as a regression check; say what it does not - cover under **Not tested**. -4. **No regression on the maintainer's run.** The maintainer merges in batches: the whole suite and a - retail title run again on the merged tree, on an AMD RDNA4 GPU. A PR that breaks either is taken - out of the batch and gets a comment with what failed. -5. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and - scope rules below. A PR that duplicates one already merged is closed. - -A test result that was not produced by a real run on the hardware named gets the PR closed. - -## Before you start - -1. **Search open PRs and issues first.** Several PRs have solved the same problem at once and all - but one were closed. If someone is already on it, review or test their PR instead. -2. **Say what you are doing.** For anything bigger than a small fix, comment on the issue (or open - one) with the plan in two or three lines before writing it. That avoids duplicate work and wasted - effort on a direction the maintainer would not take. -3. **One problem per PR.** If you find a second bug while working, it gets its own PR. - -## Pull requests: small and single-purpose - -The smaller the PR, the faster it gets reviewed and merged. - -- **One logical change per PR.** A fix, a feature, a refactor and a test-only change are four PRs, - not one. "While I was here" changes go into a separate PR. -- **Size target: under ~400 changed lines**, not counting generated files and test data. Over ~800 - lines, the description must say why it cannot be split. Most large PRs can be split. -- **How to split** a large piece of work, in roughly this order: - 1. preparation that changes no behaviour (moving code, a new helper, a renamed type), - 2. new code behind a check or not yet called, with its tests, - 3. turning it on, - 4. diagnostics, logging and env-var switches, each on its own. -- **Stacked PRs** are fine when one change depends on another. Open each PR against `main`, say - `Stacked on #N` at the top of the description, and make it clear which commits belong to this PR. - Each PR in the stack must make sense when reviewed on its own. -- **No drive-by reformatting.** The tree is not `rustfmt`-clean. Do not run `cargo fmt` on whole - files or the whole crate: format only the lines you change. Reformatting buries the real diff. -- **No unrelated churn:** no renames, reordering, comment rewrites or dependency bumps the change - does not need. -- Keep the PR up to date by rebasing onto `main`, not by merging `main` into it. -- Open the PR as a **draft** until it builds, its tests pass and you have checked it yourself. - -### PR description - -Use this outline: - -```markdown - - - -**What is in it** -- one bullet per commit or part, with the file it lives in - -**Tested** -- hardware (GPU + driver, CPU), Windows build, Rust version, debug/release -- commands run and their results, e.g. `cargo test --workspace -- --test-threads=4`: 541 passed, 0 failed, 21 ignored -- `SKIPPED` GPU tests on your adapter, if any -- game checked (if any), and what got better, with numbers if you have them - -**Regression run** -- for a runtime change: the two `xcl-smoke` blocks (main, this PR's head) – see above - -**Not tested** -- what you could not check, e.g. AMD / NVIDIA, the retail title, wave32-only GPUs - -**AI use** -- none / which tool and model (e.g. Claude Code with Claude Opus 5.5), and for what (see below) -``` - -"Not tested" is required. An honest "not tested on AMD" is fine. A test you did not run listed as -passing is not, and gets the PR closed. - -## Commits - -History is merged with merge commits, so every commit on a PR ends up in `main`. - -- **Scope prefix + outcome**, as in the existing history: - ``` - Recompiler: round f16 conversions and products to nearest-even by default - VFS: preserve the destination when an overlay rename fails - D3D12.X: draws with untranslated pipelines get the title's root signature - ``` - The prefix is the subsystem: `Recompiler`, `D3D12.X`, `DirectStorage`, `XGameRuntime`, - `kernelx`, `XAudio2`, `VFS`, `Memory`, `TLS`, `PE loader`, `Shaders`, `Frame clock`, `xcl run`, - `Tests`, `e2e`, `Scripts`, `README`, `Docs`, `Issue templates`. Use one that exists already when it fits. - No `fix:` / `feat(...)` style prefixes; this repo does not use Conventional Commits. -- Subject line of about 72 characters or less, saying what the change does, not "update file.rs" or - "fix bug". -- The body (optional for small changes) says **why**, and anything a reviewer could not see from the - diff: the root cause, what was measured, what was ruled out. -- **One logical change per commit.** Each commit builds and passes the tests on its own, so `git bisect` - works. -- **No fixup commits in the final PR**: squash "fix review", "wip", "fmt", "oops" commits into the - commit they fix before asking for review (`git rebase -i`, then force-push). -- Reference issues as `(#123)` in the subject or `Fixes #123` in the body. - -## Tests - -Add or change a test when the change touches logic: a bug fix gets a test that fails before the fix -and passes after it, and new behaviour gets a test that shows it working. Docs, comments, logging -and pure renames need no test. - -- **Unit tests** go in a `#[cfg(test)] mod tests` in the same file, the way the rest of the crate does it. -- **Integration / end-to-end tests** go in `crates/xcl/tests/`. The e2e test drives our own console - title in `tests/testtitle` / `tests/testgamedll`: extend it when a change concerns the path a title - takes. -- **GPU tests** must run without a GPU too: when the adapter cannot run them, call - `gpu::recomp::runner::skip_test("no GPU" | "no DXC" | "no wave64" | "no mesh shaders")` and return. - Never mark a test `#[ignore]` only so that it passes. -- **Tests on game data** read files the contributor owns through the `XCL_SAMPLE_*` variables - (see README / `scripts/test.ps1`), and pass without doing anything when the variable is not set. - **Never commit game data**, console SDK headers or binaries, or output dumped from a game. -- **Recompiler instructions** get a per-instruction GPU test compared against an expected result, - like the existing ones. -- Run the whole suite before opening the PR: - ```powershell - .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace - ``` - XCL builds and runs on Windows only. If you could not run the tests (e.g. you work on macOS or - Linux), say so in **Not tested**; a PR with no Windows test run waits until someone runs one. - -## Licence and provenance - -XCL is **GPL-2.0-only**. - -- Dependencies must be GPL-2.0-compatible (no Apache-2.0-only, no GPL-3.0). New dependencies need a - reason in the PR description; avoid them for a few lines of code. -- Code ported or adapted from another project needs a provenance note in the file (project, URL, - licence) and an entry in `THIRD_PARTY.md` when it is new. -- WinDurango (LGPL-3.0) is a reference only: no code is ported from it. -- Nothing from the console SDK: no headers, no binaries, no copied documentation. -- Generated files (`*_spec.rs`, tables) come with the script in `scripts/` that generates them, and - the PR says how they were generated. Do not edit them by hand. -- Nothing for decrypting or getting around DRM. - -## Docs - -- `README.md` tells users what works. Update it when your change makes something work (or stop - working) for them. -- `HANDOFF.md` and `docs/specs/` are the maintainer's design and status notes. Do not rewrite them in - a feature PR; if your change makes a statement in them wrong, point that out in the PR description. -- Everything in the repository (code, comments, commit messages, docs) is in English. - -## Reviews and test reports - -- **Test results on your GPU** go to [#42](https://github.com/ivall/xcl/issues/42), not a new issue. -- Testing someone else's PR helps the most when it follows the **Tested / Not tested** outline above - and names the exact commit tested. Post one comment and edit it when you rerun the tests; do not - post a new comment for every run. -- **AI-written test reports are welcome** when they come from a real run: the exact commit, the - hardware, the commands and their results. Say which tool and model wrote the report. -- **AI reviews:** check each point yourself, post only what you confirmed, and say that a tool helped. -- Reply to review comments in the thread, push the fix (squashed into the right commit), and mark the - thread resolved only once it is addressed. - -## AI-assisted contributions - -You can use any AI tool. In return: - -- **You are the author and you are responsible.** You have read every line of the diff, you - understand it, and you can answer questions about it without asking the tool again. "The AI wrote it" - is not an answer in a review. -- **Disclose it** in the PR's **AI use** section: the tool, the model, and what it did (wrote the - code, wrote the tests, wrote the description, only reviewed). A trailer in the commit naming the - model, such as `Co-Authored-By: ` or `Assisted-by: ()`, is welcome too. -- **The tests were run, not just written.** Results in the PR come from a run you did, on hardware - you name. -- **A person opens the PR.** No PRs or issues opened by an unattended agent. -- **Keep the description short and true.** Leave out generated filler, marketing tone and claims - nobody measured. A reviewer should be able to read the description in one minute. -- The same size and scope rules apply. An agent can write 2000 lines in an hour, and nobody can - review that in an hour. Split it. - -Agents working in this repository read [`AGENTS.md`](AGENTS.md) (and Claude Code also reads -[`CLAUDE.md`](CLAUDE.md)), which put these rules into instructions for them. diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 1e170a5..455344c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -43,12 +43,17 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address, layout, states) of an upload +/// (device, address its bytes are read from, layout, states) of an upload type Upload = (usize, usize, Arc, Vec); struct Entry { device: usize, + /// the title's address of the texture va: usize, + /// where its bytes are read and its CPU writes watched: `va`, or – for a texture in a GPU + /// view of the title's CPU memory with nothing mapped there – the same offset in the CPU + /// view (`kernelx::mirrors`) + src: usize, tex: Arc, /// the state the title's submitted work leaves the texture in (uploads leave it there): /// the creation state, then what its transitions give – one state for every subresource, @@ -135,8 +140,16 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, if ID3D12Resource::from_raw_borrowed(&res).is_none() { return Err("no resource".into()); } + let src = mirror_source(va); + if src != va { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a texture at {va:#x} lies in a GPU view of the title's CPU memory: kept in step with {src:#x} ({n} so far)"); + } + } let seq = SEQ.fetch_add(1, Ordering::Relaxed); - let e = Entry { device: device as usize, va, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, seq }; + let e = Entry { device: device as usize, va, src, tex: Arc::new(tex), states: vec![state], pending: true, gpu_written: false, seq }; { let mut t = TEXTURES.lock().unwrap(); if let Some(old) = t.insert(res as usize, e) { @@ -151,6 +164,16 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, Ok(()) } +/// Where a texture at `va` is read from: the CPU view behind a GPU view (`kernelx::mirrors`) +/// when nothing is mapped at `va` itself, else `va`. +fn mirror_source(va: usize) -> usize { + let Some(src) = crate::hle::kernelx::mirrors::source(va) else { return va }; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let mapped = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0 && m.State == MEM_COMMIT; + if mapped { va } else { src } +} + /// The title's GPU work writes texture `res` (a copy into it): on the console the memory then /// holds what the GPU wrote; here the CPU's view of it is stale, so it is not uploaded again /// (a CPU write elsewhere on its pages – a neighbour, an allocator's header – would upload the @@ -305,7 +328,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.va & !0xFFF, (e.va + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); wanted.extend(super::sparse::mapped_ranges()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); @@ -381,7 +404,7 @@ unsafe fn refresh_once(queue: *mut c_void) { let content = |e: &Entry| -> usize { let size = e.tex.size() as usize; (0..16usize) - .map(|k| e.va + (size.saturating_sub(4096)) * k / 15) + .map(|k| e.src + (size.saturating_sub(4096)) * k / 15) .filter(|&a| crate::gpu::shader::readable(a, 4096)) .map(|a| std::slice::from_raw_parts(a as *const u8, 4096).iter().filter(|&&b| b != 0).count()) .sum() @@ -423,8 +446,8 @@ unsafe fn refresh_once(queue: *mut c_void) { if e.gpu_written { return false; } - let i = dirty.partition_point(|&p| p + page as usize <= e.va); - dirty.get(i).is_some_and(|&p| p < e.va + e.tex.size() as usize) + let i = dirty.partition_point(|&p| p + page as usize <= e.src); + dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) }) .filter_map(|(&res, e)| { if e.pending { @@ -432,7 +455,7 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (e.seq, r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (e.seq, r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) }) .collect() }); @@ -529,7 +552,7 @@ pub unsafe fn probe_gpu_content(res: usize) { } g.push(res); } - let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.va, Arc::clone(&e.tex), e.gpu_written)) else { return }; + let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; @@ -739,7 +762,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, seq: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, seq: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5ee53b5..a86aa4e 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -156,6 +156,101 @@ pub fn in_graphics_reservation(p: usize) -> bool { const MEM_WRITE_WATCH: u32 = 0x20_0000; +/// GPU views of the title's CPU memory. A retail game reserves 24 GB of 64 KiB pages twice +/// in a row: once readable by the CPU (PAGE_READWRITE), once with PAGE_NOACCESS | +/// PAGE_GRAPHICS_NOACCESS. It maps physical pages only into the first, yet places GPU +/// resources at the same offset in the second (its Bink video planes: the decoder writes the +/// first view, the video shader samples textures in the second). On the console the second +/// reservation is a GPU-only view of the first; here it is separate, empty memory – the +/// video was its colour of zero luma and chroma, a green screen. `source` names the CPU view +/// behind an address of such a GPU view, which `d3d12x::title_textures` reads and watches. +pub mod mirrors { + use std::collections::BTreeMap; + use std::sync::Mutex; + + /// MEM_LARGE_PAGES | MEM_PHYSICAL: the console's 64 KiB pages + const PAGES_64K: u32 = 0x2040_0000; + /// PAGE_GRAPHICS_NOACCESS + const GRAPHICS_NOACCESS: u32 = 0x800; + + struct State { + /// CPU-readable reservations of 64 KiB pages, oldest first: (sequence, base, size) + cpu: Vec<(u64, usize, usize)>, + /// GPU view base → (size, CPU view base) + gpu: BTreeMap, + /// the next reservation's sequence number + next: u64, + /// the most recent reservation while it lives: (sequence, base, size) + last: Option<(u64, usize, usize)>, + } + static STATE: Mutex = Mutex::new(State { cpu: Vec::new(), gpu: BTreeMap::new(), next: 0, last: None }); + + /// A reservation of `size` bytes at `base` with allocation type `t` and protection `p`. + /// + /// A no-access graphics reservation of 64 KiB pages is paired with a CPU-readable one of + /// its size only when that one is the reservation immediately before it and is the only + /// CPU view of that size without a GPU view: with several candidates it is not known + /// which one the title means, and a texture read from the wrong one shows wrong texels. + /// A reservation that is not paired leaves its textures as they are. + pub fn reserved(base: usize, size: usize, t: u32, p: u32) { + if t & PAGES_64K != PAGES_64K || t & 0x1000 != 0 { + return; + } + let mut s = STATE.lock().unwrap(); + let seq = s.next; + s.next += 1; + if p & GRAPHICS_NOACCESS != 0 && p & 0xFF == super::mem::PAGE_NOACCESS { + // CPU views of its size that are not the GPU view of anything yet + let taken: Vec = s.gpu.values().map(|&(_, c)| c).collect(); + let candidates: Vec<(u64, usize)> = s + .cpu + .iter() + .filter(|&&(_, b, n)| n == size && !taken.contains(&b)) + .map(|&(q, b, _)| (q, b)) + .collect(); + // the immediately preceding reservation, while it is still one of them + let preceded = s.last.filter(|&(q, _, n)| n == size && candidates.iter().any(|&(cq, _)| cq == q)); + match (candidates.as_slice(), preceded) { + ([(_, cpu)], Some(_)) => { + s.gpu.insert(base, (size, *cpu)); + crate::xlog_info!("kernelx: reservation {base:#x} ({size:#x} bytes, no CPU access) is the GPU view of {cpu:#x}"); + } + (candidates, _) => { + static SKIPPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = SKIPPED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "kernelx: reservation {base:#x} ({size:#x} bytes, no CPU access) is not paired: {} same-size CPU view(s), not exactly the reservation before it – a texture there stays as it is ({n} so far)", + candidates.len() + ); + } + } + } + } else if p & 0xFF != super::mem::PAGE_NOACCESS { + s.cpu.push((seq, base, size)); + } + s.last = Some((seq, base, size)); + } + + /// The reservation at `base` was released. + pub fn released(base: usize) { + let mut s = STATE.lock().unwrap(); + s.cpu.retain(|&(_, b, _)| b != base); + s.gpu.remove(&base); + s.gpu.retain(|_, &mut (_, c)| c != base); + if s.last.is_some_and(|(_, b, _)| b == base) { + s.last = None; + } + } + + /// The CPU-view address behind `va` when `va` lies in a GPU view. + pub fn source(va: usize) -> Option { + let s = STATE.lock().unwrap(); + let (&gpu, &(size, cpu)) = s.gpu.range(..=va).next_back()?; + (va < gpu + size).then(|| cpu + (va - gpu)) + } +} + /// Graphics memory (MEM_GRAPHICS, committed, no fixed address) comes from the unified /// memory region the GPU uses directly (`gpu::uma`); a graphics reservation (no commit) is /// write-watched address space of Windows; everything else from Windows. @@ -280,11 +375,10 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: // (`d3d12x::title_textures`), which needs its CPU writes to be seen: it is write-watched // like a graphics reservation. Without that such a texture was uploaded once, empty, and // never again (the game's glyph atlas: its menus lost their x-height letters). - if addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_ANY != 0) { - let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t) | MEM_WRITE_WATCH, sanitize_protect(p)); + if gpu_visible_fallback(addr, t, p) { + let q = reserve_watched(size, t, p); if !q.is_null() { - GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); - GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + mirrors::reserved(q as usize, size, t, p); trace_mem("VirtualAlloc (GPU-visible, write-watched)", addr as usize, size, t as u64, p, q as usize); return q; } @@ -298,6 +392,25 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: q } +/// Whether a VirtualAlloc that reached the plain-memory fallback is GPU-visible title memory +/// (a reservation with MEM_GRAPHICS, MEM_LARGE_PAGES / MEM_64K_PAGES or a PAGE_GRAPHICS_* +/// protection, at no fixed address), which is reserved write-watched (`reserve_watched`). +fn gpu_visible_fallback(addr: *const c_void, t: u32, p: u32) -> bool { + addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_ANY != 0) +} + +/// Plain memory for GPU-visible title memory, write-watched and recorded with the graphics +/// reservations (whose ranges `title_textures` watches; `VirtualFree` forgets it). Null if +/// Windows refuses it. +unsafe fn reserve_watched(size: usize, t: u32, p: u32) -> *mut c_void { + let q = mem::VirtualAlloc(std::ptr::null(), size, sanitize_alloc_type(t) | MEM_WRITE_WATCH, sanitize_protect(p)); + if !q.is_null() { + GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + } + q +} + /// PAGE_GRAPHICS_NOACCESS … PAGE_GRAPHICS_NOCACHE (0x800 – 0x40000): the console's protection of /// GPU-visible memory const PAGE_GRAPHICS_ANY: u32 = 0x7_F800; @@ -386,6 +499,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 let ok = mem::VirtualFree(addr, size, t); if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + mirrors::released(addr as usize); } ok } @@ -2350,23 +2464,84 @@ mod tests { } } - /// GPU-visible title memory that falls back to plain memory (64 KiB pages, large pages, a - /// graphics protection) is write-watched: a texture placed there sees the CPU's writes. + /// the `mirrors` tests share its state (the reservation before a GPU view is process-wide): + /// one at a time + static MIRRORS_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// A no-access graphics reservation of 64 KiB pages is the GPU view of the CPU-readable one + /// of its size immediately before it: textures there read the CPU view (`title_textures`). + #[test] + fn gpu_view_reservations_name_their_cpu_view() { + let _one = MIRRORS_TEST.lock().unwrap(); + // (addresses far above anything Windows hands out: only the bookkeeping is tested) + let (a, b, size) = (0x7000_0000_0000usize, 0x7006_0000_0000usize, 0x6_0000_0000usize); + let other = 0x7010_0000_0000usize; + mirrors::reserved(other, 0x1000_0000, 0x2040_2000, mem::PAGE_READWRITE); // another size + mirrors::reserved(a, size, 0x2040_2000, mem::PAGE_READWRITE); + assert_eq!(mirrors::source(b + 0x1234_0000), None, "no GPU view yet"); + mirrors::reserved(b, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(b), Some(a)); + assert_eq!(mirrors::source(b + 0x4524_0000), Some(a + 0x4524_0000)); + assert_eq!(mirrors::source(b + size), None, "past its end"); + assert_eq!(mirrors::source(a + 0x10), None, "the CPU view is no GPU view"); + // committed memory or other protections are no GPU views + let c = 0x7020_0000_0000usize; + mirrors::reserved(c, size, 0x2040_3000, 0x801); + assert_eq!(mirrors::source(c), None); + mirrors::released(a); + assert_eq!(mirrors::source(b), None, "released with its CPU view"); + mirrors::released(other); + } + + /// A GPU view is paired only with the reservation immediately before it and only when that + /// is the single CPU view of its size: otherwise it stays unpaired (textures there are not + /// read from a view the title may not mean). + #[test] + fn ambiguous_gpu_views_stay_unpaired() { + let _one = MIRRORS_TEST.lock().unwrap(); + let size = 0x2_0000_0000usize; + // two CPU views of the same size: which one the GPU view means is not known + let (x, y, g) = (0x7100_0000_0000usize, 0x7104_0000_0000usize, 0x7108_0000_0000usize); + mirrors::reserved(x, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(y, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(g, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(g), None, "two same-size CPU views"); + // a reservation of another size in between: the GPU view is not a view of the one + // before that gap + let size = 0x1_0000_0000usize; + let (p, q, h) = (0x7200_0000_0000usize, 0x7210_0000_0000usize, 0x7220_0000_0000usize); + mirrors::reserved(p, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(q, 0x1000_0000, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(h, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(h), None, "not the reservation immediately before it"); + for b in [x, y, g, p, q, h] { + mirrors::released(b); + } + } + + /// GPU-visible title memory that reaches the plain-memory fallback (64 KiB pages, large + /// pages, a graphics protection) is write-watched: a texture placed there sees the CPU's + /// writes. The fallback is called directly: through `VirtualAlloc` these sizes land in a + /// unified-memory window whenever one has room (once any test has made the windows). #[test] fn gpu_visible_fallback_memory_is_write_watched() { + let null = std::ptr::null(); + // (MEM_64K_PAGES | MEM_RESERVE; MEM_LARGE_PAGES | MEM_RESERVE | MEM_COMMIT with a + // PAGE_GRAPHICS_* protection; MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT) + let gpu = [(0x2040_2000u32, mem::PAGE_READWRITE), (0x2000_3000, 0x2404), (MEM_GRAPHICS | 0x3000, mem::PAGE_READWRITE)]; + for &(t, p) in &gpu { + assert!(gpu_visible_fallback(null, t, p), "flags {t:#x} protect {p:#x}"); + } + // plain memory stays plain: CPU-only reservations, commits at a fixed address + assert!(!gpu_visible_fallback(null, 0x3000, mem::PAGE_READWRITE)); + assert!(!gpu_visible_fallback(null, 0x1000, 0x2404), "a commit without a reservation"); + assert!(!gpu_visible_fallback(0x1_0000 as *const c_void, 0x2040_2000, mem::PAGE_READWRITE), "a fixed address"); unsafe { - // (MEM_64K_PAGES | MEM_RESERVE; MEM_LARGE_PAGES | MEM_RESERVE | MEM_COMMIT with a - // PAGE_GRAPHICS_* protection; MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT) - for (t, p) in [(0x2040_2000u32, mem::PAGE_READWRITE), (0x2000_3000, 0x2404), (MEM_GRAPHICS | 0x3000, mem::PAGE_READWRITE)] { + for (t, p) in gpu { let size = 0x40_0000; - let q = VirtualAlloc(std::ptr::null(), size, t, p); + let q = reserve_watched(size, t, p); assert!(!q.is_null(), "flags {t:#x}"); let a = q as usize; - if crate::gpu::uma::get().is_some_and(|u| u.contains(a) || u.is_sparse(a)) { - // a window had room: write-watched there (`uma::watch_regions`) - VirtualFree(q, 0, mem::MEM_RELEASE); - continue; - } assert!(in_graphics_reservation(a), "flags {t:#x}: a fallback allocation is watched"); if t & 0x1000 == 0 { assert!(!VirtualAlloc((a + 0x2_0000) as *const c_void, 0x1_0000, 0x1000, mem::PAGE_READWRITE).is_null()); diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 deleted file mode 100644 index a4f668a..0000000 --- a/scripts/smoke.ps1 +++ /dev/null @@ -1,64 +0,0 @@ -# Regression run of a title for a pull request: runs it for a fixed time, reads XCL's log and -# prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built -# from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). -# -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] -# -# Networking is off (XCL_NETWORK=0). Build first: cargo build --release -p xcl -param( - [Parameter(Mandatory = $true)][string]$Game, - [int]$Seconds = 60, - [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe') -) -$ErrorActionPreference = 'Stop' - -if (-not (Test-Path $Xcl)) { throw "no $Xcl - build it first (cargo build --release -p xcl)" } -$root = Split-Path $PSScriptRoot -Parent -$commit = (git -C $root rev-parse HEAD).Trim() -$dirty = [bool](git -C $root status --porcelain --untracked-files=no -- crates Cargo.toml Cargo.lock) - -$out = New-TemporaryFile -$err = New-TemporaryFile -$env:XCL_NETWORK = '0' -$env:XCL_RUN_SECONDS = "$Seconds" -$env:XCL_ACTIVITY = '1' -$p = Start-Process -FilePath $Xcl -ArgumentList @('run', "`"$Game`"") -NoNewWindow -PassThru -RedirectStandardOutput $out -RedirectStandardError $err -$null = $p.Handle # (without it ExitCode stays empty) -if (-not $p.WaitForExit(($Seconds + 120) * 1000)) { - Stop-Process -Id $p.Id -Force - $timedOut = $true -} -Remove-Item Env:XCL_RUN_SECONDS, Env:XCL_ACTIVITY - -$stdout = Get-Content $out -Raw -Encoding utf8 -Remove-Item $out, $err -$logLine = ($stdout -split "`n" | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) -if (-not $logLine) { throw "XCL printed no log path; its output:`n$stdout" } -$log = ($logLine -replace '^Log:\s+', '').Trim() -$text = Get-Content $log -Raw -Encoding utf8 - -$frames = if ($text -match '\((\d+) frames shown, (\d+) PresentX calls\)') { "$($Matches[1]) (PresentX $($Matches[2]))" } else { 'none logged (the run did not reach its end)' } -$presents = [regex]::Matches($text, 'activity \(2 s\): (\d+) presents') | ForEach-Object { [int]$_.Groups[1].Value } -$lastPresents = ($presents | Select-Object -Last 3) -join ' ' -$commits = [regex]::Matches($text, 'memory: (\d+) MB committed') | ForEach-Object { [int]$_.Groups[1].Value } -$peak = if ($commits) { ($commits | Measure-Object -Maximum).Maximum } else { 'n/a' } -$removals = ([regex]::Matches($text, 'device removed')).Count -$crashes = ([regex]::Matches($text, 'unhandled exception|process ends with status')).Count -$gpu = (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1).Name -$code = if ($timedOut) { 'killed (no exit)' } else { '0x{0:x}' -f $p.ExitCode } - -@" -`````` -xcl-smoke v1 -commit: $commit$(if ($dirty) { ' (uncommitted changes)' }) -gpu: $gpu -title: $(Split-Path $Game -Leaf) -seconds: $Seconds -exit: $code -frames shown: $frames -presents per 2 s (last 3): $lastPresents -device removals: $removals -crashes: $crashes -peak commit: $peak MB -`````` -"@ From 17d4c43bfa5e38c39f2e3d787d3be02d18204a84 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:44:30 -0700 Subject: [PATCH 23/34] Audio: decode the title's Opus packets in xapu and play them on the PC The console audio path is xapu (the hardware Opus decoder) into SHAPE (the console mixer). XCL answered every xapu Process command with silence and never ran SHAPE, so a title that mixes through the console stayed mute. xapu now decodes each Process command's Opus packet with hle::opus (Windows' Media Foundation decoder; libopus from opus.dll where Windows has none) into the title's float32 output buffer, honoring first_frame (the pre-skip), and hle::xaudio2::console_pcm plays each decoder stream on a system XAudio2 engine of its own, one float voice per stream. SHAPE is still not run: the streams play without the console mixer's volumes, panning and effects. report.json gets xapu_* and console_pcm_* counters; xcl.log a summary line every 5 s. XCL_TRACE_APU=1 logs the commands and their structures. Ported from ivall/xcl#294 (simnJS). Unit tests cover the pre-skip copy and the Process output contract. --- THIRD_PARTY.md | 1 + crates/xcl/src/hle/acphal.rs | 370 ++++++++++++++++++++++++++++++++-- crates/xcl/src/hle/opus.rs | 190 ++++++++++++++++- crates/xcl/src/hle/xaudio2.rs | 194 ++++++++++++++++++ 4 files changed, 733 insertions(+), 22 deletions(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index fd42e6a..5ea31ec 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -19,6 +19,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | Windows XGameRuntime (`System32\xgameruntime.dll`) | system | class GUIDs and slot order of the GDK thunk protocol in `hle/xgameruntime/api.rs` (facts, determined by analysis); APIs XCL does not implement are forwarded to it at runtime | interoperability; not distributed | | docs.xbox.com | documentation | signatures, enums, structs written independently | reference | | Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked | +| [libopus](https://opus-codec.org/) (`opus.dll`) | BSD-3-Clause | Opus decoding where Windows has no `MSOpusDecoder.dll` (Wine): loaded at runtime from `%XCL_OPUS_DIR%` / next to xcl.exe (`hle/opus.rs`) | **not** distributed with XCL | | DXC (`dxcompiler.dll`, `dxil.dll`) from the Windows SDK | NCSA (dxcompiler) / Microsoft (dxil) | HLSL → DXIL compilation at runtime | loaded from the user's SDK, **not** distributed with XCL | | Windows system libraries (d3d12, dxgi, xaudio2_9, mfplat, MSOpusDecoder, ole32 …) | system | target APIs | GPL-2.0 "system library" exception | diff --git a/crates/xcl/src/hle/acphal.rs b/crates/xcl/src/hle/acphal.rs index f43e43c..5961210 100644 --- a/crates/xcl/src/hle/acphal.rs +++ b/crates/xcl/src/hle/acphal.rs @@ -1,12 +1,45 @@ //! The console's audio processor (`acphal.dll`, `xapu.dll`): memory the audio hardware //! addresses, the processor's command / message channel, SHAPE contexts and the decoder queue. //! -//! Nothing is decoded or mixed here – the processor answers as hardware with no work to do: -//! commands are acknowledged, audio frames tick (one every 128 samples at 48 kHz), SHAPE -//! context arrays exist, and the decoder returns silence of the length asked for. A title's -//! audio engine then starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole -//! audio setup), sounds decoded in software go wherever the engine sends them, and nothing -//! waits forever on the processor. Audio through the console's mixer (SHAPE) stays silent. +//! The processor answers as hardware with little to do: commands are acknowledged, audio frames +//! tick (one every 128 samples at 48 kHz), SHAPE context arrays exist. A title's audio engine then +//! starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole audio setup), and +//! nothing waits forever on the processor. The SHAPE mixer is not run. +//! +//! What runs is the decoder (xapu): Opus packets a title sends are decoded (`hle::opus`, Windows' +//! Media Foundation decoder – without it the decoder answers silence, logged once) and the PCM is +//! played on the PC by `hle::xaudio2::console_pcm`, one voice per decoder stream, without the +//! SHAPE mixer's volumes / panning / effects. `XCL_TRACE_APU=1` logs what a title sends (acphal +//! commands, xapu commands with their structures and the start of the Opus input, the caller in the +//! title, the rate per kind of command). +//! +//! # The decoder's commands as a retail title sends them (observed with `XCL_TRACE_APU=1`) +//! +//! Every command starts with the 24-byte `XApuCommand` (`kind`, `stream`, `sequence`, `options`, +//! `context` u64); the title builds it on its stack and sets only the fields it uses (`kind` and +//! `stream`, the others are left as they were – `sequence`, `options`, `context` mean nothing to it), +//! then calls `XApuEnqueueCommand(handle, &command, &count)` and polls `XApuDequeueResult`. +//! That title drives stream 0 only (so far) and is on one thread. +//! +//! * kind 1, Activate: `u32 channels` at +24 (1: mono, 2: stereo), the output rate 48000 at +56 (the +//! decoder is 48 kHz). Starts a stream. +//! * kind 3, Process: one Opus packet (RFC 6716, no length prefix, no container: 80 / 160 B mono +//! CELT full band 20 ms, TOC 0xF8; 320 B stereo, TOC 0xFC) in `input` / `input_bytes`; `frames` = 960 +//! (one packet), `first_frame` = 312 on the first command of a stream (the Opus pre-skip: decoded +//! frames to leave out), 0 after; the output is `frames × channels` float32 at `output` +//! (3 840 B mono). The input and output buffers are the same two for every command of the stream +//! (a ring the title refills); `ramp` is 0, the f32 "pitch" field holds 48000.0. A command every ~20 ms +//! once the title's own prefetch (a burst of ~20 commands, 4–6 ms apart) is done. +//! * kind 2, Deactivate: nothing after the header (the 40 bytes behind are the title's stack); the +//! title sends it when it releases the stream (`kind`, `stream`, sequence 0), then frees the +//! stream's slot. Activate / Deactivate alternate with no Process in between for short sounds. +//! * results: `state` bits 0 (output ready) and 1 (more input wanted), `frames` / `output_bytes` +//! the frames written (those after `first_frame`), `input` / `input_bytes` as sent. +//! * acphal: one command (`type` 2, id 0xF0F0F0F0, no data) right after `Connect`, nothing after +//! it during menus / sound (the SHAPE contexts are written in APU memory, not through commands); +//! the DSP (chad) gets nothing. +//! * APU memory: `ApuCreateHeap`, then `ApuAlloc` of 0x5780 (align 0x100), 0x222E00 (align 0x800, +//! flags 2) and 0x1913AFA0 (align 0x800, flags 1); `ApuMapVirtualAddress` is not called. //! //! Interfaces as titles call them (observed on retail titles; another project's notes on //! the same titles agree): `ApuAlloc(&va, &apu, size, alignment, flags)`, @@ -27,6 +60,7 @@ use std::ffi::c_void; use std::sync::Mutex; use std::time::{Duration, Instant}; +use crate::hle::{opus, xaudio2}; use crate::util::{HRESULT, S_OK}; const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; @@ -38,6 +72,99 @@ const XAPU_NO_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; /// one audio frame: 128 samples at 48 kHz const FRAME: Duration = Duration::from_micros(2667); +// --------------------------------------------------------------------------------------- +// XCL_TRACE_APU=1: what the title sends the audio processor and the decoder +// --------------------------------------------------------------------------------------- + +/// `XCL_TRACE_APU` set (not "0"): log the commands, their structures and buffers +fn trace_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_APU").is_ok_and(|v| !v.is_empty() && v != "0")) +} + +/// Per kind of command: how many came, when the first and the last did (for the call frequency), +/// and how many were logged in full. +#[derive(Default)] +struct TraceKind { + count: u64, + logged: u32, + first: Option, + last_report: Option, + since_report: u64, +} + +/// the first commands of each kind are logged in full, then one line per second and kind +struct Tracer { + kinds: Vec<(&'static str, u32, TraceKind)>, +} + +static TRACER: Mutex = Mutex::new(Tracer { kinds: Vec::new() }); +/// commands of one kind logged in full +const TRACE_FULL: u32 = 24; + +/// true: log this command in full; false: tracing is off, or the command is only counted (a rate line +/// is logged here when due) +fn trace_command(origin: &'static str, kind: u32) -> bool { + if !trace_on() { + return false; + } + let now = Instant::now(); + let mut t = TRACER.lock().unwrap(); + let i = match t.kinds.iter().position(|k| k.0 == origin && k.1 == kind) { + Some(i) => i, + None => { + t.kinds.push((origin, kind, TraceKind::default())); + t.kinds.len() - 1 + } + }; + let k = &mut t.kinds[i].2; + k.count += 1; + k.since_report += 1; + k.first.get_or_insert(now); + if k.logged < TRACE_FULL { + k.logged += 1; + return true; + } + match k.last_report { + None => k.last_report = Some(now), + Some(r) if now.duration_since(r) >= Duration::from_secs(5) => { + let rate = k.since_report as f64 / now.duration_since(r).as_secs_f64(); + crate::xlog_info!("apu-trace: {origin} command {kind:#x}: {} so far, {rate:.1}/s", k.count); + k.last_report = Some(now); + k.since_report = 0; + } + _ => {} + } + false +} + +/// the return addresses of the call into the decoder's queue (`module+offset`), for the first +/// commands of a kind: where in the title's code it comes from +unsafe fn trace_callers(kind: u32) { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + static LOGGED: Mutex> = Mutex::new(Vec::new()); + { + let mut l = LOGGED.lock().unwrap(); + if l.iter().filter(|&&k| k == kind).count() >= 2 { + return; + } + l.push(kind); + } + let mut frames = [std::ptr::null_mut::(); 8]; + let n = RtlCaptureStackBackTrace(1, frames.len() as u32, frames.as_mut_ptr(), std::ptr::null_mut()); + let list: Vec = frames[..n as usize].iter().map(|&f| crate::modules::describe_address(f as usize)).collect(); + crate::xlog_info!("apu-trace: command {kind:#x} called from {}", list.join(" < ")); +} + +/// up to `n` bytes at `p`, in hex (null: "null") +unsafe fn hex(p: *const c_void, n: usize) -> String { + if p.is_null() { + return "null".into(); + } + let b = std::slice::from_raw_parts(p as *const u8, n); + b.iter().map(|x| format!("{x:02x}")).collect::>().join("") +} + // --------------------------------------------------------------------------------------- // memory the audio processor addresses (32-bit APU addresses) // --------------------------------------------------------------------------------------- @@ -175,6 +302,9 @@ pub unsafe extern "system" fn ApuAlloc(va: *mut *mut c_void, apu: *mut u32, size if !apu.is_null() { *apu = a; } + if trace_command("ApuAlloc", 0) { + crate::xlog_info!("apu-trace: ApuAlloc({size:#x}, align {alignment:#x}, flags {_flags:#x}) -> va {p:#x} apu {a:#x}"); + } S_OK } @@ -208,6 +338,9 @@ pub unsafe extern "system" fn ApuMapVirtualAddress(apu: *mut u32, va: *mut c_voi return E_OUTOFMEMORY; }; *apu = a; + if trace_command("ApuMapVirtualAddress", 0) { + crate::xlog_info!("apu-trace: ApuMapVirtualAddress({va:p}, {size:#x}) -> apu {a:#x}"); + } S_OK } @@ -415,7 +548,11 @@ unsafe extern "system" fn hal_disconnect(h: *mut Hal) -> HRESULT { S_OK } -unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, _frame: u32, _data: *const c_void, _size: u32) -> HRESULT { +unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, frame: u32, data: *const c_void, size: u32) -> HRESULT { + if trace_command("acphal", kind) { + let dump = if data.is_null() || size == 0 { "none".to_string() } else { hex(data, (size as usize).min(96)) }; + crate::xlog_info!("apu-trace: acphal command {kind:#x} id {id:#x} frame {frame} data {data:p} size {size}: {dump}"); + } static SEEN: Mutex> = Mutex::new(Vec::new()); { let mut s = SEEN.lock().unwrap(); @@ -437,14 +574,22 @@ unsafe extern "system" fn hal_pop(h: *mut Hal, m: *mut Message) -> bool { } match (*h).channel.lock().unwrap().pop(Instant::now()) { Some(x) => { + if trace_command("acphal-pop", x.kind) { + let (kind, value, id) = (x.kind, x.value, x.id); + crate::xlog_info!("apu-trace: acphal PopMessage -> kind {kind:#x} value {value:#x} id {id:#x}"); + } *m = x; true } - None => false, + None => { + trace_command("acphal-pop", 0xFFFF_FFFF); + false + } } } unsafe extern "system" fn hal_count(h: *mut Hal) -> u32 { + trace_command("acphal-count", 0); (*h).channel.lock().unwrap().count(Instant::now()) } @@ -537,11 +682,20 @@ pub struct XApuConnectOutput { } const XAPU_ACTIVATE: u32 = 1; +const XAPU_DEACTIVATE: u32 = 2; const XAPU_PROCESS: u32 = 3; +/// What one decoder stream holds between commands. +struct XApuStream { + /// 1 or 2 (what Activate asked for) + channels: u32, + /// the Opus decoder of the stream (made by Activate; none: no decoder in this process) + decoder: Option, +} + struct XApu { results: Mutex>, - channels: Mutex>, + channels: Mutex>, data: usize, ready: usize, frames_per_output: u32, @@ -602,15 +756,98 @@ where clear_out(); return E_OUTOFMEMORY; } - channels.resize(n_streams, 2); + channels.resize_with(n_streams, || XApuStream { channels: 2, decoder: None }); let x = Box::new(XApu { results: Mutex::new(VecDeque::new()), channels: Mutex::new(channels), data, ready, frames_per_output: i.frames_per_output }); std::ptr::write_unaligned(output, XApuConnectOutput { data: data as *mut c_void, ready: ready as *mut c_void }); *handle = Box::into_raw(x) as *mut c_void; let (process, streams) = (i.process, i.streams); - crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – it answers with silence"); + if trace_on() { + let (data_bytes, per_stream, frames, options) = (i.data_bytes, i.commands_per_stream, i.frames_per_output, i.options); + crate::xlog_info!("apu-trace: XApuConnect: data {data_bytes:#x} B at {data:#x}, {per_stream} commands per stream, {frames} frames per output, options {options:#x}"); + } + crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – Opus packets are decoded and played on the PC (silence without an Opus decoder)"); S_OK } +/// The Opus decoder of a stream Activate (re)started. None when the process has no decoder (logged once). +fn new_decoder(stream: u32, channels: u32) -> Option { + static WARNED: std::sync::Once = std::sync::Once::new(); + match opus::Decoder::new(channels as u16, 48_000, &[]) { + Ok(d) => Some(d), + Err(e) => { + WARNED.call_once(|| crate::xlog_warn!("xapu: no Opus decoder ({e}) – the decoder answers with silence")); + crate::xlog_debug!("xapu: stream {stream} without decoder"); + None + } + } +} + +/// Writes the frames of `pcm` after the first `first_frame` into `out` (float32, `channels` +/// interleaved), scaled from PCM16, and returns the frames written and how many of their samples +/// are not 0. Frames `out` has no room for are not written; what the decoder did not produce stays +/// as `out` was (the caller fills it with silence before). +fn write_decoded(pcm: &[i16], channels: usize, first_frame: usize, out: &mut [f32]) -> (usize, u64) { + let ch = channels.max(1); + let frames = pcm.len() / ch; + let skip = first_frame.min(frames); + let produced = (frames - skip).min(out.len() / ch); + let mut nonzero = 0u64; + if produced != 0 { + for (o, &v) in out.iter_mut().zip(pcm[skip * ch..(skip + produced) * ch].iter()) { + *o = v as f32 / 32768.0; + nonzero += (v != 0) as u64; + } + } + (produced, nonzero) +} + +/// Decodes a Process command's input (Opus packets) into `out` (float32 samples, `channels` interleaved): +/// `first_frame` frames of what the decoder produces are skipped, the rest fills `out` (what is not +/// produced stays silent). Returns the frames written (None: nothing was decoded). +unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out: &mut [f32]) -> Option { + let (input, input_bytes, first_frame) = (p.input, p.input_bytes, p.first_frame); + let dec = s.decoder.as_mut()?; + if input.is_null() || input_bytes == 0 { + return None; + } + let packet = std::slice::from_raw_parts(input as *const u8, input_bytes as usize); + let mut pcm: Vec = Vec::with_capacity(960 * 2); + match dec.decode_packet(packet, &mut pcm) { + Ok(frames) if frames > 0 => { + let (produced, nonzero) = write_decoded(&pcm, s.channels as usize, first_frame as usize, out); + xaudio2::note_console_decode(1, 0, produced as u64, nonzero); + Some(produced) + } + other => { + xaudio2::note_console_decode(0, 1, 0, 0); + if trace_on() { + crate::xlog_info!("apu-trace: stream {stream}: {input_bytes} B did not decode ({other:?})"); + } + None + } + } +} + +/// Every 5 s while the decoder works: what it decoded and what was played (the log is what a +/// run that is cut short leaves; report.json is written at the start). +fn report_progress() { + static LAST: Mutex> = Mutex::new(None); + let now = Instant::now(); + { + let mut l = LAST.lock().unwrap(); + match *l { + Some(t) if now.duration_since(t) < Duration::from_secs(5) => return, + _ => *l = Some(now), + } + } + let a = xaudio2::stats(); + crate::xlog_info!( + "xapu: {} Opus packets decoded ({} errors), {} frames, {} non-zero samples; played on the PC: {} samples ({} non-zero, {} dropped, {} errors, {} voices)", + a.xapu_packets_decoded, a.xapu_decode_errors, a.xapu_frames, a.xapu_nonzero_samples, + a.console_pcm_samples, a.console_pcm_nonzero_samples, a.console_pcm_dropped, a.console_pcm_errors, a.console_pcm_voices + ); +} + /// XApuConnect(&input, &output, &handle) pub unsafe extern "system" fn XApuConnect(input: *const XApuConnectInput, output: *mut XApuConnectOutput, handle: *mut *mut c_void) -> HRESULT { use windows_sys::Win32::System::Threading::CreateEventW; @@ -645,20 +882,44 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * } let x = &*(handle as *const XApu); let c = std::ptr::read_unaligned(command); + if trace_command("xapu", c.kind) { + let (kind, stream, seq, opts, ctx) = (c.kind, c.stream, c.sequence, c.options, c.context); + crate::xlog_info!("apu-trace: xapu command {kind:#x} stream {stream} seq {seq} options {opts:#x} context {ctx:p}: {}", hex(command as *const c_void, 64)); + trace_callers(kind); + if kind == XAPU_PROCESS { + let p = std::ptr::read_unaligned(command as *const XApuProcess); + let (ramp, pitch, first, frames, ib, input, ob, output) = (p.ramp, p.pitch, p.first_frame, p.frames, p.input_bytes, p.input, p.output_bytes, p.output); + crate::xlog_info!( + "apu-trace: process ramp {ramp} pitch {pitch} first_frame {first} frames {frames} input {ib} B at {input:p} output {ob} B at {output:p}; input starts {}", + hex(input, (ib as usize).min(512)) + ); + } + } let mut r = XApuResult { id: c, state: 0, state_data: 0, time: 0, error: S_OK, frames: 0, output_bytes: 0, output: std::ptr::null_mut(), pitch: 1.0, input_bytes: 0, input: std::ptr::null_mut() }; { let mut ch = x.channels.lock().unwrap(); let s = if (c.stream as usize) < ch.len() { c.stream as usize } else { 0 }; if c.kind == XAPU_ACTIVATE { let n = std::ptr::read_unaligned(command as *const XApuActivate).channels; - ch[s] = if n == 1 { 1 } else { 2 }; + let channels = if n == 1 { 1 } else { 2 }; + ch[s].channels = channels; + ch[s].decoder = new_decoder(c.stream, channels); + } else if c.kind == XAPU_DEACTIVATE { + ch[s].decoder = None; } else if c.kind == XAPU_PROCESS { let p = std::ptr::read_unaligned(command as *const XApuProcess); - let frame_bytes = ch[s] * 4; + let frame_bytes = ch[s].channels * 4; let asked = if p.frames != 0 { p.frames } else { x.frames_per_output }; let frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes); + let mut frames = frames; if !p.output.is_null() && frames != 0 { - std::ptr::write_bytes(p.output as *mut u8, 0, (frames * frame_bytes) as usize); + let out = std::slice::from_raw_parts_mut(p.output as *mut f32, (frames * ch[s].channels) as usize); + out.fill(0.0); + // decoded: the frames after first_frame; not decoded: silence of the length asked for + if let Some(n) = decode_into(&mut ch[s], c.stream, &p, out) { + frames = n as u32; + xaudio2::console_pcm(c.stream, ch[s].channels as u16, &out[..n * ch[s].channels as usize]); + } } // output ready, more input wanted r.state = 1 | 2; @@ -668,6 +929,7 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * r.pitch = p.pitch; r.input_bytes = p.input_bytes; r.input = p.input; + report_progress(); } } let n = { @@ -689,6 +951,7 @@ pub unsafe extern "system" fn XApuDequeueResult(handle: *mut c_void, result: *mu if handle.is_null() || result.is_null() { return E_INVALIDARG; } + trace_command("xapu-dequeue", 0); match (*(handle as *const XApu)).results.lock().unwrap().pop_front() { Some(r) => { std::ptr::write_unaligned(result, r); @@ -747,7 +1010,10 @@ pub unsafe extern "system" fn XDspDisconnect(handle: *mut c_void) -> HRESULT { S_OK } -pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspActivate(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { + if trace_command("dsp", 0xA0) { + crate::xlog_info!("apu-trace: XDspActivate({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { E_INVALIDARG } else { @@ -763,8 +1029,11 @@ pub unsafe extern "system" fn XDspDeactivate(handle: *mut c_void, _a: usize, _b: } } -pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, _a: usize, _b: usize, _c: usize) -> HRESULT { +pub unsafe extern "system" fn XDspSubmitCommand(handle: *mut c_void, a: usize, b: usize, c: usize) -> HRESULT { static FIRST: std::sync::Once = std::sync::Once::new(); + if trace_command("dsp", 0x5C) { + crate::xlog_info!("apu-trace: XDspSubmitCommand({a:#x}, {b:#x}, {c:#x})"); + } if handle.is_null() { return E_INVALIDARG; } @@ -881,6 +1150,75 @@ mod tests { } } + #[test] + fn decoded_pcm_skips_the_pre_skip_and_scales() { + // mono: skip 2 frames (the Opus pre-skip), write the other 2, no more room than that + let pcm = [-32768i16, 0, 16384, 32767]; + let mut out = [1.0f32; 4]; + assert_eq!(write_decoded(&pcm, 1, 2, &mut out), (2, 2)); + assert_eq!(out, [0.5, 32767.0 / 32768.0, 1.0, 1.0], "frames not produced stay as they were"); + // more frames than the output holds: cut at the buffer + let mut small = [0.0f32; 3]; + assert_eq!(write_decoded(&pcm, 1, 0, &mut small).0, 3); + assert_eq!(small, [-1.0, 0.0, 0.5]); + // stereo stays interleaved, the pre-skip counts frames, not samples + let stereo = [1i16, -1, 2, -2, 3, -3]; + let mut out = [0.0f32; 4]; + assert_eq!(write_decoded(&stereo, 2, 1, &mut out), (2, 4)); + assert_eq!(out, [2.0 / 32768.0, -2.0 / 32768.0, 3.0 / 32768.0, -3.0 / 32768.0]); + // nothing decoded, nothing written + assert_eq!(write_decoded(&[], 2, 0, &mut out), (0, 0)); + } + + #[test] + fn xapu_activate_starts_a_decoder_and_process_keeps_the_output_contract() { + unsafe { + let input = XApuConnectInput { process: 1, streams: 1, commands_per_stream: 4, data_bytes: 0, frames_per_output: 0, options: 0 }; + let mut out = XApuConnectOutput { data: std::ptr::null_mut(), ready: std::ptr::null_mut() }; + let mut h = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut out, &mut h), S_OK); + let mut n = 0; + let a = XApuActivate { id: XApuCommand { kind: XAPU_ACTIVATE, stream: 0, sequence: 0, options: 0, context: std::ptr::null_mut() }, channels: 1 }; + assert_eq!(XApuEnqueueCommand(h, &a as *const _ as *const XApuCommand, &mut n), S_OK); + // Activate queues a result of its own: take it before the Process result is asked for + let mut r: XApuResult = std::mem::zeroed(); + assert_eq!(XApuDequeueResult(h, &mut r), S_OK); + { + let x = &*(h as *const XApu); + let ch = x.channels.lock().unwrap(); + assert_eq!(ch[0].channels, 1, "Activate's channel count"); + assert_eq!(ch[0].decoder.is_some(), opus::is_available(), "a decoder where the process has one"); + } + // a packet that is not Opus (or no decoder at all): silence of the length asked, and + // the buffer past what the result says was written is untouched + let mut packet = [0xFFu8; 2]; + let mut buf = vec![0xAAu8; 4096]; + let p = XApuProcess { + id: XApuCommand { kind: XAPU_PROCESS, stream: 0, sequence: 1, options: 0, context: std::ptr::null_mut() }, + ramp: 0.0, + pitch: 48_000.0, + first_frame: 0, + frames: 0, + input_bytes: packet.len() as u32, + input: packet.as_mut_ptr() as *mut c_void, + output_bytes: buf.len() as u32, + output: buf.as_mut_ptr() as *mut c_void, + }; + assert_eq!(XApuEnqueueCommand(h, &p as *const _ as *const XApuCommand, &mut n), S_OK); + let mut r: XApuResult = std::mem::zeroed(); + assert_eq!(XApuDequeueResult(h, &mut r), S_OK); + let (frames, bytes) = (r.frames, r.output_bytes); + assert!(frames <= 960, "never more than the packet can hold"); + assert_eq!(bytes, frames * 4, "mono float32"); + assert!(buf[bytes as usize..].iter().all(|&b| b == 0xAA), "the rest of the output is untouched (frames {frames}, bytes {bytes})"); + // Deactivate drops the stream's decoder + let d = XApuCommand { kind: XAPU_DEACTIVATE, stream: 0, sequence: 0, options: 0, context: std::ptr::null_mut() }; + assert_eq!(XApuEnqueueCommand(h, &d as *const _ as *const XApuCommand, &mut n), S_OK); + assert!((*(h as *const XApu)).channels.lock().unwrap()[0].decoder.is_none()); + assert_eq!(XApuDisconnect(h), S_OK); + } + } + #[test] fn apu_address_prevents_overflow_overlap_and_rejects_null_va() { // u32::MAX cannot fit within [APU_BASE, 4 GiB) without wrapping. diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index c2d1018..097d494 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -826,9 +826,187 @@ fn mf_runtime() -> Result<&'static MfRuntime, String> { .map_err(|e| e.clone()) } -/// Whether Windows' built-in `MSOpusDecoder.dll` + Media Foundation runtime is available. +/// Whether an Opus decoder is available: Windows' built-in `MSOpusDecoder.dll` + Media Foundation +/// runtime, or libopus loaded from `opus.dll` (see [`libopus`]). pub fn is_available() -> bool { - mf_runtime().is_ok() + mf_runtime().is_ok() || libopus().is_ok() +} + +/// The decoder in use ("Windows MSOpusDecoder", "libopus (path)"), or why there is none. Logged once. +pub fn backend() -> String { + match (mf_runtime(), libopus()) { + (Ok(_), _) => "Windows' MSOpusDecoder (Media Foundation)".to_string(), + (_, Ok(l)) => format!("libopus ({})", l.path), + (Err(a), Err(b)) => format!("none ({a}; {b})"), + } +} + +// --------------------------------------------------------------------------------------- +// libopus from `opus.dll`, loaded at run time (where Windows' decoder does not exist: Wine) +// --------------------------------------------------------------------------------------- +// +// Not distributed with XCL (like DXC): `opus.dll` – libopus (BSD-3-Clause), built for Windows – is +// looked for in `%XCL_OPUS_DIR%`, then next to xcl.exe (`opus.dll`, `libopus.dll`, `libopus-0.dll`). +// Windows' own decoder is used first when the system has it. Only the decoder is used. + +type OpusDecoderCreateFn = unsafe extern "C" fn(i32, i32, *mut i32) -> *mut c_void; +type OpusDecodeFn = unsafe extern "C" fn(*mut c_void, *const u8, i32, *mut i16, i32, i32) -> i32; +type OpusDecoderDestroyFn = unsafe extern "C" fn(*mut c_void); +type OpusDecoderCtlFn = unsafe extern "C" fn(*mut c_void, i32, ...) -> i32; + +/// `OPUS_RESET_STATE`: the decoder starts again +const OPUS_RESET_STATE: i32 = 4028; + +struct LibOpus { + path: String, + create: OpusDecoderCreateFn, + decode: OpusDecodeFn, + destroy: OpusDecoderDestroyFn, + ctl: OpusDecoderCtlFn, +} + +static LIBOPUS: OnceLock> = OnceLock::new(); + +fn libopus() -> Result<&'static LibOpus, String> { + LIBOPUS + .get_or_init(|| unsafe { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::System::LibraryLoader::LoadLibraryW; + let mut dirs: Vec = Vec::new(); + if let Some(d) = std::env::var_os("XCL_OPUS_DIR") { + dirs.push(d.into()); + } + if let Some(d) = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf())) { + dirs.push(d); + } + for dir in &dirs { + for name in ["opus.dll", "libopus.dll", "libopus-0.dll"] { + let path = dir.join(name); + if !path.is_file() { + continue; + } + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let h = LoadLibraryW(wide.as_ptr()) as usize; + if h == 0 { + continue; + } + let f = |n: &str| crate::resolver::system_proc_in(h, &crate::pe::ImportName::Name { hint: 0, name: n.into() }); + let (Some(create), Some(decode), Some(destroy), Some(ctl)) = + (f("opus_decoder_create"), f("opus_decode"), f("opus_decoder_destroy"), f("opus_decoder_ctl")) + else { + continue; + }; + return Ok(LibOpus { + path: path.display().to_string(), + create: std::mem::transmute::(create), + decode: std::mem::transmute::(decode), + destroy: std::mem::transmute::(destroy), + ctl: std::mem::transmute::(ctl), + }); + } + } + Err("no opus.dll (libopus) in %XCL_OPUS_DIR% or next to xcl.exe".to_string()) + }) + .as_ref() + .map_err(|e| e.clone()) +} + +/// One libopus decoder (1 or 2 channels), the same job as [`MftDecoder`]. +struct LibDecoder { + lib: &'static LibOpus, + state: *mut c_void, + channels: u16, + output_rate: u32, +} + +impl LibDecoder { + fn new(channels: u16, sample_rate: u32) -> Result { + let lib = libopus()?; + let ch = channels.clamp(1, 2); + // libopus decodes to 8, 12, 16, 24 or 48 kHz + let rate = if matches!(sample_rate, 8_000 | 12_000 | 16_000 | 24_000 | 48_000) { sample_rate } else { 48_000 }; + let mut err = 0i32; + let state = unsafe { (lib.create)(rate as i32, ch as i32, &mut err) }; + if state.is_null() || err != 0 { + return Err(format!("opus_decoder_create: {err}")); + } + Ok(Self { lib, state, channels: ch, output_rate: rate }) + } + + fn flush(&mut self) { + unsafe { + (self.lib.ctl)(self.state, OPUS_RESET_STATE); + } + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + let max_frames = (MAX_PACKET_SAMPLES_48K as usize * self.output_rate as usize) / 48_000; + let ch = self.channels as usize; + let start = out.len(); + out.resize(start + max_frames * ch, 0); + let n = unsafe { (self.lib.decode)(self.state, packet.as_ptr(), packet.len() as i32, out[start..].as_mut_ptr(), max_frames as i32, 0) }; + if n < 0 { + out.truncate(start); + return Err(format!("opus_decode: {n}")); + } + out.truncate(start + n as usize * ch); + Ok(n as usize) + } +} + +impl Drop for LibDecoder { + fn drop(&mut self) { + unsafe { (self.lib.destroy)(self.state) } + } +} + +// SAFETY: a libopus decoder state is used by one thread at a time (`&mut self`). +unsafe impl Send for LibDecoder {} + +/// One single-stream decoder: Windows' MFT where there is one, else libopus. +enum SingleStreamDecoder { + Mft(MftDecoder), + Lib(LibDecoder), +} + +impl SingleStreamDecoder { + fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { + static CHOICE: std::sync::Once = std::sync::Once::new(); + CHOICE.call_once(|| crate::xlog_info!("Opus: decoder = {}", backend())); + match MftDecoder::new(channels, sample_rate, head_bytes) { + Ok(d) => Ok(Self::Mft(d)), + Err(mft) => LibDecoder::new(channels, sample_rate).map(Self::Lib).map_err(|lib| format!("{mft}; {lib}")), + } + } + + fn output_rate(&self) -> u32 { + match self { + Self::Mft(d) => d.output_rate, + Self::Lib(d) => d.output_rate, + } + } + + /// stream time of the next packet (0: nothing decoded since the start / the last flush) + fn timestamp_100ns(&self) -> i64 { + match self { + Self::Mft(d) => d.timestamp_100ns, + Self::Lib(_) => 0, + } + } + + fn flush(&mut self) { + match self { + Self::Mft(d) => d.flush(), + Self::Lib(d) => d.flush(), + } + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + match self { + Self::Mft(d) => d.decode_packet(packet, out), + Self::Lib(d) => d.decode_packet(packet, out), + } + } } fn mf_create_media_type(rt: &MfRuntime) -> Result { @@ -882,7 +1060,7 @@ enum OutputSampleFormat { Float32, } -struct SingleStreamDecoder { +struct MftDecoder { mft: IMFTransform, channels: u16, output_rate: u32, @@ -892,7 +1070,7 @@ struct SingleStreamDecoder { timestamp_100ns: i64, } -impl SingleStreamDecoder { +impl MftDecoder { fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { let rt = mf_runtime()?; let mft = create_opus_mft(rt)?; @@ -1163,7 +1341,7 @@ impl Decoder { streams.push(SingleStreamDecoder::new(sch, rate, Some(&ud))?); } } - let output_rate = streams[0].output_rate; + let output_rate = streams[0].output_rate(); let pre_skip_scaled = ((head.pre_skip as u64 * output_rate as u64) / 48_000) as usize; let output_gain_scale = gain_scale(head.output_gain); @@ -1291,7 +1469,7 @@ impl Decoder { && t.head.coupled_count == self.coupled_count && t.head.mapping == self.mapping && gain_scale(t.head.output_gain) == self.output_gain_scale - && self.streams.iter().all(|s| s.timestamp_100ns == 0) + && self.streams.iter().all(|s| s.timestamp_100ns() == 0) }); if let Some(timing) = timing { for pkt in &packets { diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index f762160..932e0ef 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -67,6 +67,7 @@ const CO_E_NOTINITIALIZED: HRESULT = 0x8004_01F0u32 as i32; const ENGINE_CREATE_SOURCE_VOICE: usize = 5; const ENGINE_CREATE_MASTERING_VOICE: usize = 7; const VOICE_DESTROY: usize = 18; +const VOICE_START: usize = 19; const VOICE_SUBMIT_SOURCE_BUFFER: usize = 21; const VOICE_FLUSH_SOURCE_BUFFERS: usize = 22; const VOICE_GET_STATE: usize = 25; @@ -171,6 +172,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { // --------------------------------------------------------------------------------------- #[derive(Debug, Default, Clone, Serialize, Deserialize)] +#[serde(default)] pub struct AudioStats { pub engines: u64, pub engine_errors: u64, @@ -197,6 +199,19 @@ pub struct AudioStats { pub source_voice_errors: u64, /// console-only flags we dropped, e.g. "XAudio2Create:0x1" pub dropped_flags: Vec, + /// the console's decoder (xapu, `hle::acphal`): Opus packets decoded, packets that failed (silence + /// went out), frames produced, samples that are not 0 + pub xapu_packets_decoded: u64, + pub xapu_decode_errors: u64, + pub xapu_frames: u64, + pub xapu_nonzero_samples: u64, + /// the console decoder's PCM played here: voices, samples (and the non-zero ones) submitted to + /// XAudio2, buffers dropped (queue full or no device), errors + pub console_pcm_voices: u64, + pub console_pcm_samples: u64, + pub console_pcm_nonzero_samples: u64, + pub console_pcm_dropped: u64, + pub console_pcm_errors: u64, } static ENGINES: AtomicU64 = AtomicU64::new(0); @@ -236,6 +251,15 @@ pub fn stats() -> AudioStats { buffers_silenced: SILENCED.load(Ordering::Relaxed), source_voice_errors: SOURCE_ERRORS.load(Ordering::Relaxed), dropped_flags: DROPPED.lock().map(|d| d.clone()).unwrap_or_default(), + xapu_packets_decoded: PCM_PACKETS.load(Ordering::Relaxed), + xapu_decode_errors: PCM_PACKET_ERRORS.load(Ordering::Relaxed), + xapu_frames: PCM_DECODED_FRAMES.load(Ordering::Relaxed), + xapu_nonzero_samples: PCM_NONZERO.load(Ordering::Relaxed), + console_pcm_voices: SINK_VOICES.load(Ordering::Relaxed), + console_pcm_samples: SINK_SAMPLES.load(Ordering::Relaxed), + console_pcm_nonzero_samples: SINK_NONZERO.load(Ordering::Relaxed), + console_pcm_dropped: SINK_DROPPED.load(Ordering::Relaxed), + console_pcm_errors: SINK_ERRORS.load(Ordering::Relaxed), } } @@ -1168,6 +1192,176 @@ unsafe extern "system" fn destroy_voice(this: *mut c_void) { } } +// --------------------------------------------------------------------------------------- +// the console audio processor's PCM out (hle::acphal): decoded streams played on the PC +// --------------------------------------------------------------------------------------- +// +// A title that uses the console's audio hardware (xapu decoder, SHAPE mixer) has no XAudio2 +// engine of its own. What xapu decodes is played here: one float32 source voice per decoder +// stream on an engine of this module's own (system XAudio2), mixed by Windows. It runs on a thread +// of its own (COM, the device and the queue never hold up the title's audio thread). The SHAPE +// mixer's volumes, panning and effects are not applied – the decoded stream plays as it is. + +use std::sync::mpsc::{channel, Sender}; + +/// float32 samples a title's decoder stream hands over: (decoder stream, channels, interleaved samples) +type SinkItem = (u32, u16, Vec); + +/// buffers of one sink voice: a queue deeper than this drops the newest samples +const SINK_RING: usize = 24; + +static SINK: OnceLock>>> = OnceLock::new(); +static SINK_SAMPLES: AtomicU64 = AtomicU64::new(0); +static SINK_NONZERO: AtomicU64 = AtomicU64::new(0); +static SINK_DROPPED: AtomicU64 = AtomicU64::new(0); +static SINK_ERRORS: AtomicU64 = AtomicU64::new(0); +static SINK_VOICES: AtomicU64 = AtomicU64::new(0); +static PCM_DECODED_FRAMES: AtomicU64 = AtomicU64::new(0); +static PCM_NONZERO: AtomicU64 = AtomicU64::new(0); +static PCM_PACKETS: AtomicU64 = AtomicU64::new(0); +static PCM_PACKET_ERRORS: AtomicU64 = AtomicU64::new(0); + +/// What the console decoder (xapu) did: `packets` Opus packets decoded to `frames` frames of which +/// `nonzero` samples are not 0, `errors` packets that did not decode (silence went out). +pub fn note_console_decode(packets: u64, errors: u64, frames: u64, nonzero: u64) { + PCM_PACKETS.fetch_add(packets, Ordering::Relaxed); + PCM_PACKET_ERRORS.fetch_add(errors, Ordering::Relaxed); + PCM_DECODED_FRAMES.fetch_add(frames, Ordering::Relaxed); + PCM_NONZERO.fetch_add(nonzero, Ordering::Relaxed); +} + +/// Plays what a console decoder stream produced (interleaved float32, 48 kHz). Never blocks. +pub fn console_pcm(stream: u32, channels: u16, samples: &[f32]) { + if samples.is_empty() || !(1..=2).contains(&channels) { + return; + } + let tx = SINK.get_or_init(|| { + let (tx, rx) = channel::(); + match std::thread::Builder::new().name("console-audio".into()).spawn(move || sink_thread(rx)) { + Ok(_) => Mutex::new(Some(tx)), + Err(_) => { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + Mutex::new(None) + } + } + }); + if let Some(t) = tx.lock().unwrap().as_ref() { + let _ = t.send((stream, channels, samples.to_vec())); + } +} + +/// a voice's method: the system's, whatever this module patched in the shared vtable +unsafe fn voice_fn(obj: *mut c_void, slot: usize) -> usize { + original(obj, slot).unwrap_or_else(|| vtable(obj).add(slot).read()) +} + +struct SinkVoice { + voice: *mut c_void, + channels: u16, + ring: Vec>, + next: usize, +} + +unsafe fn sink_engine() -> Option<(*mut c_void, *mut c_void)> { + use windows_sys::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED}; + CoInitializeEx(std::ptr::null(), COINIT_MULTITHREADED as u32); + let (with_version, plain) = system_create()?; + let mut engine: *mut c_void = std::ptr::null_mut(); + let hr = match (with_version, plain) { + (Some(f), _) => f(&mut engine, 0, XAUDIO2_DEFAULT_PROCESSOR, NTDDI_WIN10_RS5), + (None, Some(f)) => f(&mut engine, 0, XAUDIO2_DEFAULT_PROCESSOR), + _ => E_FAIL, + }; + if hr < 0 || engine.is_null() { + crate::xlog_warn!("console audio: no XAudio2 engine ({:#x}) – decoded sound is not played", hr as u32); + return None; + } + let create_mastering: CreateMasteringVoiceFn = std::mem::transmute(voice_fn(engine, ENGINE_CREATE_MASTERING_VOICE)); + let mut mastering: *mut c_void = std::ptr::null_mut(); + let hr = create_mastering(engine, &mut mastering, 0, 0, 0, std::ptr::null(), std::ptr::null(), AUDIO_CATEGORY_GAME_EFFECTS); + if hr < 0 || mastering.is_null() { + crate::xlog_warn!("console audio: no mastering voice ({:#x}) – no audio device? decoded sound is not played", hr as u32); + return None; + } + crate::xlog_info!("console audio: XAudio2 engine and mastering voice created – the console decoder's PCM is played"); + Some((engine, mastering)) +} + +fn sink_thread(rx: std::sync::mpsc::Receiver) { + unsafe { + let Some((engine, _mastering)) = sink_engine() else { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + // keep draining so the title's side never queues without bound + for _ in rx { + SINK_DROPPED.fetch_add(1, Ordering::Relaxed); + } + return; + }; + let mut voices: HashMap = HashMap::new(); + for (stream, channels, samples) in rx { + let need_new = voices.get(&stream).is_none_or(|v| v.channels != channels); + if need_new { + if let Some(old) = voices.remove(&stream) { + let destroy: DestroyVoiceFn = std::mem::transmute(voice_fn(old.voice, VOICE_DESTROY)); + destroy(old.voice); + } + let fmt = WaveFormatEx { + tag: WAVE_FORMAT_IEEE_FLOAT, + channels, + rate: 48_000, + avg_bytes: 48_000 * 4 * channels as u32, + block_align: 4 * channels, + bits: 32, + cb_size: 0, + }; + let create: CreateSourceVoiceFn = std::mem::transmute(voice_fn(engine, ENGINE_CREATE_SOURCE_VOICE)); + let mut voice: *mut c_void = std::ptr::null_mut(); + let hr = create(engine, &mut voice, &fmt, 0, 1.0, std::ptr::null_mut(), std::ptr::null(), std::ptr::null()); + if hr < 0 || voice.is_null() { + crate::xlog_warn!("console audio: stream {stream}: no source voice ({:#x})", hr as u32); + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + continue; + } + let start: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT = std::mem::transmute(voice_fn(voice, VOICE_START)); + start(voice, 0, 0); + SINK_VOICES.fetch_add(1, Ordering::Relaxed); + voices.insert(stream, SinkVoice { voice, channels, ring: vec![Vec::new(); SINK_RING], next: 0 }); + } + let Some(v) = voices.get_mut(&stream) else { continue }; + let mut st = XAudio2VoiceState { current_buffer_context: std::ptr::null_mut(), buffers_queued: 0, samples_played: 0 }; + let get_state: GetStateFn = std::mem::transmute(voice_fn(v.voice, VOICE_GET_STATE)); + get_state(v.voice, &mut st, 0x100 /* XAUDIO2_VOICE_NOSAMPLESPLAYED */); + let queued = st.buffers_queued; + if queued as usize >= SINK_RING - 1 { + SINK_DROPPED.fetch_add(1, Ordering::Relaxed); + continue; + } + let slot = &mut v.ring[v.next]; + v.next = (v.next + 1) % SINK_RING; + *slot = samples; + let b = XAudio2Buffer { + flags: 0, + audio_bytes: (slot.len() * 4) as u32, + audio_data: slot.as_ptr() as *const u8, + play_begin: 0, + play_length: 0, + loop_begin: 0, + loop_length: 0, + loop_count: 0, + context: std::ptr::null_mut(), + }; + let submit: SubmitSourceBufferFn = std::mem::transmute(voice_fn(v.voice, VOICE_SUBMIT_SOURCE_BUFFER)); + let hr = submit(v.voice, &b, std::ptr::null()); + if hr < 0 { + SINK_ERRORS.fetch_add(1, Ordering::Relaxed); + } else { + SINK_SAMPLES.fetch_add(slot.len() as u64, Ordering::Relaxed); + SINK_NONZERO.fetch_add(slot.iter().filter(|&&x| x != 0.0).count() as u64, Ordering::Relaxed); + } + } + } +} + #[cfg(test)] mod tests { use super::*; From c3b3d04a382ea7c1f69e8cebf939d8201b1fc520 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:46:34 -0700 Subject: [PATCH 24/34] D3D12.X: 9E5 targets stay half floats, and the allocation stand-in reaches creation Revert the R9G9B9E5_SHAREDEXP targets from R32_TYPELESS back to R16G16B16A16_FLOAT, as on the base: an SRV of the typeless resource was R32_FLOAT over the packed bits, and its RTV lost G, B and A. A shader view with no description of a texture `pc_resource_desc` made typeless now names the format the title created it with (recorded per resource at creation), so an sRGB texture with UAVs is read as sRGB instead of naming a typeless format or format 0. CreatePlacedResourceX creates a format the PC has no layout for (5..8, 66, 68, 69) with the same stand-in its allocation query answered for, so creation no longer fails after the query succeeded. Tests: srgb_uavs_and_unsupported_allocation_formats, unsupported_formats_are_created_with_the_query_standin, typeless_resources_get_typed_uav_descs. --- crates/xcl/src/hle/d3d12x/device_x.rs | 90 ++++++++++++++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 82 +++++++++++++++++------- 2 files changed, 135 insertions(+), 37 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 5882d50..46ed05a 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -676,11 +676,9 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { } // R9G9B9E5_SHAREDEXP targets: the PC renders into the format neither as a target nor through // unordered access (a retail game's 1920x1080 one on the Series S profile, flags 0x300005: - // E_INVALIDARG, then its assertion). R32_TYPELESS, the console's 32 bits a texel: its views - // are R32_FLOAT for the shaders that write shared-exponent values as floats (exact, every - // 9E5 value is), and R32_UINT for those that write the packed 32 bits themselves + // E_INVALIDARG, then its assertion) – half floats hold every shared-exponent value exactly if format == 67 && flags & 5 != 0 { - d[0x20..0x24].copy_from_slice(&39u32.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&10u32.to_le_bytes()); } // sRGB textures the console also lets shaders write: the PC has no sRGB unordered access // (a retail game's 2048x2048 R8G8B8A8 one: E_INVALIDARG) – typeless, so the UAV views are @@ -731,7 +729,7 @@ fn depth_typeless(f: u32) -> Option { pub fn pc_target_format(f: u32) -> u32 { match f { 86 | 115 => 28, - 67 => 41, + 67 => 10, f => pc_view_format(f), } } @@ -786,8 +784,8 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (53 | 55, 0 | 53 | 55) => 56, // a target made R8G8B8A8 (`pc_resource_desc`) (28, 86 | 115) => 28, - // an R9G9B9E5 target made R32_TYPELESS: floats, and a view that names the format itself - (39, 67) => 41, + // an R9G9B9E5 target made half floats + (10, 67) => 10, // an sRGB texture made typeless for its UAVs: its own views stay sRGB (27, 0) => 29, (90, 0) => 91, @@ -875,6 +873,22 @@ pub fn pc_standin_format(f: u32) -> Option { }) } +/// The desc a texture is created with: `pc_resource_desc`, and a format the PC has no layout +/// for (the allocation query's stand-in, `pc_standin_format`) – the same stand-in, so creation +/// does not fail once the query has answered. Buffers: as `pc_resource_desc` has them (their +/// format field is a structure stride). +pub fn pc_creation_desc(x: &[u8; 0x38]) -> [u8; 0x38] { + let mut d = pc_resource_desc(x); + if u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { + return d; + } + let f = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + if let Some(t) = pc_standin_format(f) { + d[0x20..0x24].copy_from_slice(&t.to_le_bytes()); + } + d +} + /// device #108 (a retail game) GetResourceAllocationInfo2(visible mask, count, D3D12_RESOURCE_DESC1s, /// D3D12_RESOURCE_ALLOCATION_INFO1* each) -> {size, alignment} of them all, returned like #25's; /// each resource's {offset, alignment, size} goes to the last argument when there is one. @@ -940,12 +954,30 @@ fn note_alias(va: usize, x: &[u8; 0x38]) { /// memory (placed in its UMA heap); a texture gets a PC texture kept in step with the memory /// (`title_textures`: detiled as the console lays it out, uploaded again after CPU writes). pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = create_placed_resource_inner(this, va, desc, state, clear, riid, ppv); + // the format the title named, for a shader view of it that names none (`real::title_format`) + if hr >= 0 && !desc.is_null() && crate::gpu::shader::readable(desc as usize, 0x38) { + record_title_format(ppv, &(desc as *const [u8; 0x38]).read_unaligned()); + } + hr +} + +/// The format `x` names on the resource `ppv` just created, unless it is a buffer (its format +/// field is a structure stride) or `ppv` holds none. +pub(super) unsafe fn record_title_format(ppv: *mut *mut c_void, x: &[u8; 0x38]) { + if ppv.is_null() || (*ppv).is_null() || u32::from_le_bytes(x[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { + return; + } + real::note_title_format(*ppv as usize, u32::from_le_bytes(x[0x20..0x24].try_into().unwrap())); +} + +unsafe fn create_placed_resource_inner(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { static N: AtomicU64 = AtomicU64::new(0); if desc.is_null() || ppv.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) { return E_INVALIDARG; } let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - let d = pc_resource_desc(&x); + let d = pc_creation_desc(&x); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; note_alias(va as usize, &x); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the @@ -1154,15 +1186,13 @@ mod tests { x[0x20] = 86; // B5G5R5A1 target that is also a UAV x[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); assert_eq!(desc(&x), (28, 0x5)); - x[0x20] = 67; // R9G9B9E5 target that is also a UAV (and console bits): R32_TYPELESS + x[0x20] = 67; // R9G9B9E5 target that is also a UAV (and console bits): half floats x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); - assert_eq!(desc(&x), (39, 0x5)); + assert_eq!(desc(&x), (10, 0x5)); x[0x30..0x34].copy_from_slice(&0x0u32.to_le_bytes()); // a sampled one stays R9G9B9E5 assert_eq!(desc(&x), (67, 0)); - // its target views are floats; a shader's own-format and packed-uint views are too / - // as they are (the same 32 bits a texel) - assert_eq!((pc_shader_view_format(39, 67), pc_shader_view_format(67, 67), pc_target_format(67)), (41, 67, 41)); - assert_eq!((pc_shader_view_format(39, 0), pc_shader_view_format(39, 42)), (41, 42)); + // its views are the half floats' (the same values, exactly) + assert_eq!((pc_shader_view_format(10, 67), pc_shader_view_format(67, 67), pc_target_format(67)), (10, 67, 10)); // views: a D24S8 format or R16_UNORM of the D16S8 buffer read depth; stencil formats plane 1 assert_eq!(pc_shader_view_format(44, 45), 46); assert_eq!(pc_shader_view_format(44, 56), 46); @@ -1221,6 +1251,38 @@ mod tests { assert!(standin_texture(&x).is_none()); } + /// The texture a title places (`CreatePlacedResourceX`) in a format the PC has no layout for + /// is created with the stand-in its allocation query answered for: the query's answer and + /// the creation ask the PC the same format. Buffers keep their stride field. + #[test] + fn unsupported_formats_are_created_with_the_query_standin() { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&2048u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&2048u32.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + let format = |x: &[u8; 0x38]| u32::from_le_bytes(pc_creation_desc(x)[0x20..0x24].try_into().unwrap()); + for (f, stand_in) in [(68u32, 56u32), (69, 56), (66, 61), (6, 2), (8, 2)] { + x[0x20..0x24].copy_from_slice(&f.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&0x1u32.to_le_bytes()); + assert_eq!(format(&x), stand_in, "format {f}"); + // the stand-in is what the query's console layout was taken in + let t = standin_texture(&x).unwrap_or_else(|| panic!("no stand-in for {f}")); + assert!(t.size() > 0, "{f}"); + } + // a format the PC has, and one the rewrite made typeless, as `pc_resource_desc` has them + x[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); + assert_eq!(format(&x), 28); + x[0x20..0x24].copy_from_slice(&29u32.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&0x4u32.to_le_bytes()); // sRGB with UAVs + assert_eq!(format(&x), 27); + // a buffer: its format field is a stride, left alone + x[0..4].copy_from_slice(&1u32.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&6u32.to_le_bytes()); + assert_eq!(format(&x), 6); + } + #[test] fn derived_pipeline_patches_land_on_the_desc_parts() { use std::mem::{offset_of, size_of}; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c7505d2..a42fe5f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1556,6 +1556,20 @@ pub(super) fn note_title_address(res: usize, va: usize) { TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va); } +/// The format each texture was created with, in the title's own name: `device_x::pc_resource_desc` +/// may have made it typeless for its views (an sRGB one with UAVs), so a shader view that names +/// no format has to name this one. +static TITLE_FORMAT: Mutex>> = Mutex::new(None); + +/// The format the title created a texture with (None: not one XCL recorded). +pub(super) fn title_format(res: usize) -> Option { + TITLE_FORMAT.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()) +} + +pub(super) fn note_title_format(res: usize, format: u32) { + TITLE_FORMAT.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, format); +} + /// resources whose Map gave their unified-memory address (no PC mapping to undo) static UNMAPPABLE: Mutex>> = Mutex::new(None); @@ -1934,9 +1948,10 @@ fn default_dsv(d: &D3D12_RESOURCE_DESC) -> Option Some(v) } -/// A shader view `v` (None: the resource's default one) of `rd` with the PC's format names -/// (`device_x::pc_shader_view_format`) – None: as it is. -fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option { +/// A shader view `v` (None: the resource's default one) of `rd`, created as the title's `created` +/// format (`real::title_format`), with the PC's format names (`device_x::pc_shader_view_format`) +/// – None: as it is. +fn pc_srv(created: Option, rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option { use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; if rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { return None; @@ -1950,7 +1965,17 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) if !matches!(rf, 19 | 39 | 44 | 53) && !super::device_x::typeless_format(rf) { return None; } - let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; + // the console's default view is the format the title created the texture with, not + // its typeless PC one (an sRGB texture with UAVs is read as sRGB); with no record of + // it, the family's own readable format + let own = created.unwrap_or(0); + let own = super::device_x::pc_shader_view_format(rf, own); + let own = if own == 0 || super::device_x::typeless_format(own) { rf } else { own }; + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(super::device_x::pc_view_format(own) as i32), + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; if rd.DepthOrArraySize > 1 { v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: u32::MAX, ArraySize: rd.DepthOrArraySize as u32, ..Default::default() }; @@ -1966,7 +1991,7 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) } let f = super::device_x::pc_shader_view_format(rf, out.Format.0 as u32); // a typeless resource whose family has no obvious view (none of the console's): as it was - if f == 0 { + if f == 0 || super::device_x::typeless_format(f) { return None; } let stencil = super::device_x::stencil_view(rf, f); @@ -1993,7 +2018,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } // a depth buffer's view in the formats the PC has for it (a D24S8 format itself, R16_UNORM of // a D16S8 buffer …: an invalid call, the device removed) - if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { + if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(title_format(res as usize), &r.GetDesc(), copy.as_ref())) { copy = Some(v); } let desc = copy.as_ref().map_or(desc, |c| c as *const _); @@ -2172,7 +2197,7 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI /// A UAV view desc `d` (None: the resource's own) of `rd` with the PC's format names /// (`device_x::pc_shader_view_format`, `device_x::pc_unorm_format`) – None: as it is. A resource -/// the PC holds typeless (`pc_resource_desc`: an R9G9B9E5 target, an sRGB one with UAVs) needs a +/// the PC holds typeless (`pc_resource_desc`: an sRGB one with UAVs) needs a /// typed desc of its own. fn pc_uav_desc(rd: &D3D12_RESOURCE_DESC, d: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>) -> Option { use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; @@ -2288,7 +2313,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: mip, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, }; - if let Some(v) = pc_srv(&rd, Some(&srv)) { + if let Some(v) = pc_srv(title_format(res as usize), &rd, Some(&srv)) { srv = v; } let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); @@ -2336,6 +2361,7 @@ unsafe fn create_display_target(this: *mut c_void, props: usize, desc: usize, st return hr; } let size = crate::hle::xg::Texture::new(&x).map_or(0, |t| t.size()) as usize; + super::device_x::record_title_format(ppv, &x); let at = if size > 0 { crate::hle::kernelx::runtime_alloc(size, crate::hle::kernelx::D3D_DISPLAY_TARGET) } else { None }; if let Some(p) = at { note_title_address(*ppv as usize, p); @@ -2351,6 +2377,15 @@ unsafe fn create_display_target(this: *mut c_void, props: usize, desc: usize, st } unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, props: usize, flags: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = create_committed_resource_inner(this, props, flags, desc, state, clear, riid, ppv); + // the format the title named, for a shader view of it that names none (`title_format`) + if hr >= 0 && desc != 0 && crate::gpu::shader::readable(desc, 0x38) { + super::device_x::record_title_format(ppv, &(desc as *const [u8; 0x38]).read_unaligned()); + } + hr +} + +unsafe fn create_committed_resource_inner(this: *mut c_void, props: usize, flags: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { static SEEN: AtomicU64 = AtomicU64::new(0); if desc != 0 && std::env::var_os("XCL_D3D12_TRACE").is_some() && SEEN.fetch_add(1, Ordering::Relaxed) < 8 { let w = |o: usize| *((desc + o) as *const u32); @@ -4663,7 +4698,7 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // --------------------------------------------------------------------------------------- /// The view a render target view without a description has, for a texture `pc_resource_desc` -/// made typeless (an sRGB one with UAVs, an R9G9B9E5 target) – None: the resource's format is +/// made typeless (an sRGB one with UAVs) – None: the resource's format is /// a typed one. fn default_rtv(d: &D3D12_RESOURCE_DESC) -> Option { use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; @@ -5593,9 +5628,9 @@ mod typeless_uav_view_tests { } } - /// A resource the PC holds typeless (an sRGB texture with UAVs, an R9G9B9E5 target) gets a - /// typed UAV desc: the sRGB one's UNORM for shaders that write values, the shared-exponent - /// one's R32_FLOAT or, as the console names it, R32_UINT for the packed 32 bits. + /// A resource the PC holds typeless (an sRGB texture with UAVs, a depth buffer) gets a typed + /// UAV desc: the sRGB one's UNORM for shaders that write values. An R9G9B9E5 target the PC + /// holds as half floats keeps the title's view format as its UAV. #[test] fn typeless_resources_get_typed_uav_descs() { // sRGB typeless: a named sRGB view becomes UNORM, keeping its mip @@ -5609,29 +5644,30 @@ mod typeless_uav_view_tests { assert_eq!((v.Format.0, v.ViewDimension.0), (28, D3D12_UAV_DIMENSION_TEXTURE2DARRAY.0)); assert_eq!(unsafe { v.Anonymous.Texture2DArray }.ArraySize, 3); - // R9G9B9E5 typeless: floats for the console format, the packed bits' format as named - assert_eq!(pc_uav_desc(&rd(39, 1), Some(&uav(67, 0))).map(|v| v.Format.0), Some(41)); - assert_eq!(pc_uav_desc(&rd(39, 1), None).map(|v| v.Format.0), Some(41)); - assert!(pc_uav_desc(&rd(39, 1), Some(&uav(42, 0))).is_none(), "R32_UINT stays R32_UINT"); + // an R9G9B9E5 target the PC holds as half floats: the console's view is half floats too + assert_eq!(pc_uav_desc(&rd(10, 1), Some(&uav(67, 0))).map(|v| v.Format.0), Some(10)); + assert_eq!(pc_uav_desc(&rd(10, 1), None).map(|v| v.Format.0), Some(10)); // a resource that is its own typed format is left as the title made it assert!(pc_uav_desc(&rd(28, 1), Some(&uav(28, 0))).is_none()); assert!(pc_uav_desc(&rd(28, 1), None).is_none()); assert!(pc_uav_desc(&rd(67, 1), Some(&uav(67, 0))).is_none(), "a sampled R9G9B9E5 texture"); - // an SRV of a typeless sRGB resource: its own view is the sRGB one - let s = pc_srv(&rd(27, 1), None).expect("the sRGB texture's own SRV"); + // an SRV of a typeless sRGB resource: its own view is the sRGB one, by the format the + // title created it with and, with none recorded, by its family's + let s = pc_srv(Some(29), &rd(27, 1), None).expect("the sRGB texture's own SRV"); assert_eq!((s.Format.0, s.ViewDimension.0), (29, D3D12_SRV_DIMENSION_TEXTURE2D.0)); - let s = pc_srv(&rd(39, 1), None).expect("an R32_TYPELESS texture's own SRV"); + let s = pc_srv(None, &rd(27, 1), None).expect("the sRGB texture's own SRV, unrecorded"); + assert_eq!(s.Format.0, 29); + let s = pc_srv(None, &rd(39, 1), None).expect("an R32_TYPELESS texture's own SRV"); assert_eq!(s.Format.0, 41); - assert!(pc_srv(&rd(28, 1), None).is_none()); + assert!(pc_srv(None, &rd(28, 1), None).is_none()); + assert!(pc_srv(None, &rd(27, 1), Some(&D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT(27), ..Default::default() })).is_none(), "a typeless SRV format is not one the PC takes"); // the same for an RTV and, with no description, a view of the console's own format let r = default_rtv(&rd(27, 1)).expect("the sRGB texture's own RTV"); assert_eq!((r.Format.0, r.ViewDimension.0), (29, D3D12_RTV_DIMENSION_TEXTURE2D.0)); - let r = default_rtv(&rd(39, 3)).expect("the R9G9B9E5 target's own RTV"); - assert_eq!((r.Format.0, r.ViewDimension.0), (41, D3D12_RTV_DIMENSION_TEXTURE2DARRAY.0)); - assert_eq!(unsafe { r.Anonymous.Texture2DArray }.ArraySize, 3); + assert!(default_rtv(&rd(10, 1)).is_none(), "the half floats are the resource's own format"); assert!(default_rtv(&rd(28, 1)).is_none()); assert!(default_rtv(&rd(44, 1)).is_none(), "a depth buffer's views name it"); } From 9f5877a595852b811f8440447f4b7886b4472153 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:47:14 -0700 Subject: [PATCH 25/34] Write-watch: read large watched sets on a pool of threads GetWriteWatch walks each range in the kernel, one range after another, before every submit; on a newer retail title that walk held the submitting thread for most of each frame (194 s of write-watch in one session, the CPU and GPU both near idle). Large sets are split over up to 8 long-lived threads (XCL_WATCH_THREADS, 1 = the serial loop). Each range is still read and reset by one call, so the dirty set is unchanged. --- crates/xcl/src/hle/d3d12x/title_textures.rs | 132 +++++++++++++++++--- 1 file changed, 118 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d689347..b250def 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -349,6 +349,88 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { own_work(|| refresh_once(queue)); } +/// The write-watch ranges split into at most `WATCH_THREADS` parts of about equal size, or one +/// part when the set is small enough that threads would cost more than they save. +fn watch_parts(ranges: &[(usize, usize)]) -> Vec> { + const MIN_PARALLEL: usize = 256 << 20; + let total: usize = ranges.iter().map(|r| r.1).sum(); + if ranges.len() < 2 || total < MIN_PARALLEL || watch_threads() < 2 { + return vec![ranges.to_vec()]; + } + let k = watch_threads().min(ranges.len()); + let share = total.div_ceil(k); + let mut parts: Vec> = vec![Vec::new()]; + let mut acc = 0usize; + for &r in ranges { + if acc >= share && parts.len() < k { + parts.push(Vec::new()); + acc = 0; + } + parts.last_mut().unwrap().push(r); + acc += r.1; + } + parts +} + +/// `XCL_WATCH_THREADS` (default 8, 1 = the serial loop): threads that read the write-watch. +fn watch_threads() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_WATCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(8).clamp(1, 32)) +} + +/// GetWriteWatch with reset over `ranges`: every written page's address goes to `dirty`. +unsafe fn watch_into(ranges: &[(usize, usize)], buf: &mut Vec<*mut c_void>, dirty: &mut Vec, page: &mut u32) { + if buf.len() < 16384 { + buf.resize(16384, std::ptr::null_mut()); + } + for &(base, size) in ranges { + loop { + let mut n = buf.len(); + if GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, size, buf.as_mut_ptr(), &mut n, page) != 0 { + break; + } + dirty.extend(buf[..n].iter().map(|&p| p as usize)); + if n < buf.len() { + break; + } + } + } +} + +type WatchJob = (Vec<(usize, usize)>, std::sync::mpsc::Sender<(Vec, u32)>); + +/// The write-watch threads: a shared queue of jobs, each answered with (dirty pages, granularity). +struct WatchPool(Mutex>); + +impl WatchPool { + fn send(&self, job: WatchJob) { + let _ = self.0.lock().unwrap().send(job); + } +} + +fn watch_pool() -> &'static WatchPool { + static POOL: std::sync::OnceLock = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + let rx = Arc::new(Mutex::new(rx)); + for i in 0..watch_threads() { + let rx = Arc::clone(&rx); + let _ = std::thread::Builder::new().name(format!("xcl-watch-{i}")).spawn(move || { + let mut buf: Vec<*mut c_void> = Vec::new(); + loop { + let job = rx.lock().unwrap().recv(); + let Ok((ranges, reply)) = job else { return }; + let mut found = Vec::new(); + let mut page = 0u32; + unsafe { watch_into(&ranges, &mut buf, &mut found, &mut page) }; + let _ = reply.send((found, page)); + } + }); + } + WatchPool(Mutex::new(tx)) + }) +} + unsafe fn refresh_once(queue: *mut c_void) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); @@ -361,24 +443,30 @@ unsafe fn refresh_once(queue: *mut c_void) { let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); - WATCH_BUF.with(|wcell| { - let mut buf = wcell.borrow_mut(); - if buf.len() < 16384 { - buf.resize(16384, std::ptr::null_mut()); + let parts = watch_parts(&ranges); + if parts.len() <= 1 { + WATCH_BUF.with(|wcell| watch_into(&ranges, &mut wcell.borrow_mut(), &mut dirty, &mut page)); + } else { + // Large watched sets: GetWriteWatch walks every page of a range in the kernel, one + // range after another, and that walk held the title's submitting thread for most of + // its frame. The ranges are split over a pool of long-lived threads (created once, + // so the title's per-thread setup runs only for them); each range is still read and + // reset by exactly one call, so the dirty set is the same as the serial loop's. + let (tx, rx) = std::sync::mpsc::channel(); + let n = parts.len(); + for part in parts { + watch_pool().send((part, tx.clone())); } - for &(base, size) in ranges.iter() { - loop { - let mut n = buf.len(); - if GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, size, buf.as_mut_ptr(), &mut n, &mut page) != 0 { - break; - } - dirty.extend(buf[..n].iter().map(|&p| p as usize)); - if n < buf.len() { - break; + drop(tx); + for _ in 0..n { + if let Ok((found, g)) = rx.recv() { + dirty.extend(found); + if g != 0 { + page = g; } } } - }); + } dirty.sort_unstable(); dirty.len() }); @@ -795,3 +883,19 @@ mod tests { assert_eq!(watch_ranges(®ions, wanted), vec![(0x1000_0000, 0x8_1000), (0x1100_0000, 0x1000)]); } } + +#[cfg(test)] +mod watch_parts_tests { + use super::watch_parts; + + #[test] + fn small_sets_stay_serial_and_large_ones_split_without_losing_a_range() { + let small = vec![(0x1000usize, 0x10000usize), (0x20000, 0x10000)]; + assert_eq!(watch_parts(&small), vec![small.clone()]); + let big: Vec<(usize, usize)> = (0..40).map(|i| (0x1_0000_0000 + i * (64 << 20), 64 << 20)).collect(); + let parts = watch_parts(&big); + assert!(parts.len() > 1 && parts.len() <= 8, "{} parts", parts.len()); + let flat: Vec<(usize, usize)> = parts.concat(); + assert_eq!(flat, big, "every range exactly once, in order"); + } +} From e2af7acc0febc5eb1a8485f7de48b963e7e7c314 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:48:29 -0700 Subject: [PATCH 26/34] tests: an R9G9B9E5 target's own UAV needs no desc (its format is its own) --- crates/xcl/src/hle/d3d12x/real.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a42fe5f..bc2c867 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5646,7 +5646,7 @@ mod typeless_uav_view_tests { // an R9G9B9E5 target the PC holds as half floats: the console's view is half floats too assert_eq!(pc_uav_desc(&rd(10, 1), Some(&uav(67, 0))).map(|v| v.Format.0), Some(10)); - assert_eq!(pc_uav_desc(&rd(10, 1), None).map(|v| v.Format.0), Some(10)); + assert!(pc_uav_desc(&rd(10, 1), None).is_none(), "the half floats are the resource's own format"); // a resource that is its own typed format is left as the title made it assert!(pc_uav_desc(&rd(28, 1), Some(&uav(28, 0))).is_none()); From 19e4783356e767282f13bdef847a39f6762705d8 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:51:43 -0700 Subject: [PATCH 27/34] Write-watch: read once a frame by default (XCL_WATCH_EVERY_SUBMIT=1: every submit) Measured on a newer retail title: about 15 ms of GetWriteWatch per submit over 2.7 GB of mapped sparse tiles, at about 5 submits a frame. The thread pool did not help (the kernel serialises the walks), so XCL_WATCH_THREADS now defaults to 1. --- crates/xcl/src/hle/d3d12x/title_textures.rs | 24 +++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index b250def..adb2486 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -372,10 +372,11 @@ fn watch_parts(ranges: &[(usize, usize)]) -> Vec> { parts } -/// `XCL_WATCH_THREADS` (default 8, 1 = the serial loop): threads that read the write-watch. +/// `XCL_WATCH_THREADS` (default 1 = the serial loop; the kernel serialises the walks, so more threads +/// measured no faster): threads that read the write-watch. fn watch_threads() -> usize { static N: std::sync::OnceLock = std::sync::OnceLock::new(); - *N.get_or_init(|| std::env::var("XCL_WATCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(8).clamp(1, 32)) + *N.get_or_init(|| std::env::var("XCL_WATCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(1).clamp(1, 32)) } /// GetWriteWatch with reset over `ranges`: every written page's address goes to `dirty`. @@ -431,6 +432,21 @@ fn watch_pool() -> &'static WatchPool { }) } +/// Whether this submit reads the write-watch. GetWriteWatch walks every watched page (gigabytes +/// of mapped sparse tiles on a newer retail title: about 15 ms a call) and a title submits several +/// times a frame, so by default it is read once a frame: at the first submit after a present. +/// A page written between two submits of one frame then reaches video memory at the next frame's +/// first submit. `XCL_WATCH_EVERY_SUBMIT=1` reads it before every submit, as before. +fn scan_this_submit() -> bool { + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + if *EVERY.get_or_init(|| std::env::var("XCL_WATCH_EVERY_SUBMIT").is_ok_and(|v| v != "0")) { + return true; + } + static LAST: AtomicU64 = AtomicU64::new(u64::MAX); + let now = super::present::presents(); + LAST.swap(now, Ordering::Relaxed) != now +} + unsafe fn refresh_once(queue: *mut c_void) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); @@ -440,9 +456,13 @@ unsafe fn refresh_once(queue: *mut c_void) { let watch_t0 = std::time::Instant::now(); let mut page = 0x1000u32; let ranges = cached_watch_ranges(u); + let scan = scan_this_submit(); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); + if !scan { + return 0; + } let parts = watch_parts(&ranges); if parts.len() <= 1 { WATCH_BUF.with(|wcell| watch_into(&ranges, &mut wcell.borrow_mut(), &mut dirty, &mut page)); From fad19799d5c6d1c2955ed58596529b8f4ad87fbe Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:53:52 -0700 Subject: [PATCH 28/34] Drop upstream's CLAUDE.md, CONTRIBUTING.md and scripts/smoke.ps1 again (this fork's rules live in AGENTS.md) --- CLAUDE.md | 16 ---- CONTRIBUTING.md | 199 ---------------------------------------------- scripts/smoke.ps1 | 64 --------------- 3 files changed, 279 deletions(-) delete mode 100644 CLAUDE.md delete mode 100644 CONTRIBUTING.md delete mode 100644 scripts/smoke.ps1 diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index e30885a..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,16 +0,0 @@ -# Claude Code - -The instructions for agents in this repository are in `AGENTS.md`, and the rules for every -contributor are in `CONTRIBUTING.md`. Both apply to you: - -@AGENTS.md -@CONTRIBUTING.md - -Specific to Claude Code: - -- Plan a task that spans more than one subsystem or more than ~400 lines (plan mode), and propose - how to split it into PRs before you write code. -- Run the tests and report the real output; do not stop at "the tests should pass". -- Fill in the **AI use** section of the PR description with Claude Code and your exact model name. -- For a runtime change, run `scripts/smoke.ps1` on main and on the PR's head commit and paste both - `xcl-smoke` blocks; do not write or edit them by hand. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 75e48de..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,199 +0,0 @@ -# Contributing to XCL - -Thanks for helping. XCL gets far more pull requests than one maintainer can read carefully, so -these rules exist to make every PR **cheap to review and safe to merge**. A PR that ignores them -may be closed without a review, however good the code is. - -AI tools are welcome (see [AI-assisted contributions](#ai-assisted-contributions)). The rules are -the same for code written by hand and by an agent. - -## What a PR needs to be merged - -XCL gets more pull requests in an hour than anyone can test by hand, most of them written with AI -tools. So a PR is merged only when it shows that it was tested and that it breaks nothing. These are -checked before anything else; a PR that does not meet them waits (or is closed after a week). - -1. **Both required checks are green:** `CI` (build and tests on Windows, no GPU) and `PR checks` - (the description: the sections below, and the regression runs when they are needed). -2. **The whole suite ran on a GPU**, with the counts in **Tested** - (`cargo test --workspace -- --test-threads=4`: N passed, N failed, N ignored, and the SKIPPED tests). -3. **A PR that changes the runtime** (`crates/xcl/src` outside tests) **has a regression run on a real - title**: `scripts/smoke.ps1 -Game ` built from `main` and built from the PR's head - commit, both `xcl-smoke` blocks pasted under **Regression run**. The PR's block must name its head - commit with no uncommitted changes: rerun it after every push. It must show no device removal and - no crash, at least as many frames as `main` and no much higher peak commit. A run on a title that - does not reach the code the PR changes still counts as a regression check; say what it does not - cover under **Not tested**. -4. **No regression on the maintainer's run.** The maintainer merges in batches: the whole suite and a - retail title run again on the merged tree, on an AMD RDNA4 GPU. A PR that breaks either is taken - out of the batch and gets a comment with what failed. -5. **Up to date and reviewable:** it merges into `main` without conflicts, and keeps to the size and - scope rules below. A PR that duplicates one already merged is closed. - -A test result that was not produced by a real run on the hardware named gets the PR closed. - -## Before you start - -1. **Search open PRs and issues first.** Several PRs have solved the same problem at once and all - but one were closed. If someone is already on it, review or test their PR instead. -2. **Say what you are doing.** For anything bigger than a small fix, comment on the issue (or open - one) with the plan in two or three lines before writing it. That avoids duplicate work and wasted - effort on a direction the maintainer would not take. -3. **One problem per PR.** If you find a second bug while working, it gets its own PR. - -## Pull requests: small and single-purpose - -The smaller the PR, the faster it gets reviewed and merged. - -- **One logical change per PR.** A fix, a feature, a refactor and a test-only change are four PRs, - not one. "While I was here" changes go into a separate PR. -- **Size target: under ~400 changed lines**, not counting generated files and test data. Over ~800 - lines, the description must say why it cannot be split. Most large PRs can be split. -- **How to split** a large piece of work, in roughly this order: - 1. preparation that changes no behaviour (moving code, a new helper, a renamed type), - 2. new code behind a check or not yet called, with its tests, - 3. turning it on, - 4. diagnostics, logging and env-var switches, each on its own. -- **Stacked PRs** are fine when one change depends on another. Open each PR against `main`, say - `Stacked on #N` at the top of the description, and make it clear which commits belong to this PR. - Each PR in the stack must make sense when reviewed on its own. -- **No drive-by reformatting.** The tree is not `rustfmt`-clean. Do not run `cargo fmt` on whole - files or the whole crate: format only the lines you change. Reformatting buries the real diff. -- **No unrelated churn:** no renames, reordering, comment rewrites or dependency bumps the change - does not need. -- Keep the PR up to date by rebasing onto `main`, not by merging `main` into it. -- Open the PR as a **draft** until it builds, its tests pass and you have checked it yourself. - -### PR description - -Use this outline: - -```markdown - - - -**What is in it** -- one bullet per commit or part, with the file it lives in - -**Tested** -- hardware (GPU + driver, CPU), Windows build, Rust version, debug/release -- commands run and their results, e.g. `cargo test --workspace -- --test-threads=4`: 541 passed, 0 failed, 21 ignored -- `SKIPPED` GPU tests on your adapter, if any -- game checked (if any), and what got better, with numbers if you have them - -**Regression run** -- for a runtime change: the two `xcl-smoke` blocks (main, this PR's head) – see above - -**Not tested** -- what you could not check, e.g. AMD / NVIDIA, the retail title, wave32-only GPUs - -**AI use** -- none / which tool and model (e.g. Claude Code with Claude Opus 5.5), and for what (see below) -``` - -"Not tested" is required. An honest "not tested on AMD" is fine. A test you did not run listed as -passing is not, and gets the PR closed. - -## Commits - -History is merged with merge commits, so every commit on a PR ends up in `main`. - -- **Scope prefix + outcome**, as in the existing history: - ``` - Recompiler: round f16 conversions and products to nearest-even by default - VFS: preserve the destination when an overlay rename fails - D3D12.X: draws with untranslated pipelines get the title's root signature - ``` - The prefix is the subsystem: `Recompiler`, `D3D12.X`, `DirectStorage`, `XGameRuntime`, - `kernelx`, `XAudio2`, `VFS`, `Memory`, `TLS`, `PE loader`, `Shaders`, `Frame clock`, `xcl run`, - `Tests`, `e2e`, `Scripts`, `README`, `Docs`, `Issue templates`. Use one that exists already when it fits. - No `fix:` / `feat(...)` style prefixes; this repo does not use Conventional Commits. -- Subject line of about 72 characters or less, saying what the change does, not "update file.rs" or - "fix bug". -- The body (optional for small changes) says **why**, and anything a reviewer could not see from the - diff: the root cause, what was measured, what was ruled out. -- **One logical change per commit.** Each commit builds and passes the tests on its own, so `git bisect` - works. -- **No fixup commits in the final PR**: squash "fix review", "wip", "fmt", "oops" commits into the - commit they fix before asking for review (`git rebase -i`, then force-push). -- Reference issues as `(#123)` in the subject or `Fixes #123` in the body. - -## Tests - -Add or change a test when the change touches logic: a bug fix gets a test that fails before the fix -and passes after it, and new behaviour gets a test that shows it working. Docs, comments, logging -and pure renames need no test. - -- **Unit tests** go in a `#[cfg(test)] mod tests` in the same file, the way the rest of the crate does it. -- **Integration / end-to-end tests** go in `crates/xcl/tests/`. The e2e test drives our own console - title in `tests/testtitle` / `tests/testgamedll`: extend it when a change concerns the path a title - takes. -- **GPU tests** must run without a GPU too: when the adapter cannot run them, call - `gpu::recomp::runner::skip_test("no GPU" | "no DXC" | "no wave64" | "no mesh shaders")` and return. - Never mark a test `#[ignore]` only so that it passes. -- **Tests on game data** read files the contributor owns through the `XCL_SAMPLE_*` variables - (see README / `scripts/test.ps1`), and pass without doing anything when the variable is not set. - **Never commit game data**, console SDK headers or binaries, or output dumped from a game. -- **Recompiler instructions** get a per-instruction GPU test compared against an expected result, - like the existing ones. -- Run the whole suite before opening the PR: - ```powershell - .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace - ``` - XCL builds and runs on Windows only. If you could not run the tests (e.g. you work on macOS or - Linux), say so in **Not tested**; a PR with no Windows test run waits until someone runs one. - -## Licence and provenance - -XCL is **GPL-2.0-only**. - -- Dependencies must be GPL-2.0-compatible (no Apache-2.0-only, no GPL-3.0). New dependencies need a - reason in the PR description; avoid them for a few lines of code. -- Code ported or adapted from another project needs a provenance note in the file (project, URL, - licence) and an entry in `THIRD_PARTY.md` when it is new. -- WinDurango (LGPL-3.0) is a reference only: no code is ported from it. -- Nothing from the console SDK: no headers, no binaries, no copied documentation. -- Generated files (`*_spec.rs`, tables) come with the script in `scripts/` that generates them, and - the PR says how they were generated. Do not edit them by hand. -- Nothing for decrypting or getting around DRM. - -## Docs - -- `README.md` tells users what works. Update it when your change makes something work (or stop - working) for them. -- `HANDOFF.md` and `docs/specs/` are the maintainer's design and status notes. Do not rewrite them in - a feature PR; if your change makes a statement in them wrong, point that out in the PR description. -- Everything in the repository (code, comments, commit messages, docs) is in English. - -## Reviews and test reports - -- **Test results on your GPU** go to [#42](https://github.com/ivall/xcl/issues/42), not a new issue. -- Testing someone else's PR helps the most when it follows the **Tested / Not tested** outline above - and names the exact commit tested. Post one comment and edit it when you rerun the tests; do not - post a new comment for every run. -- **AI-written test reports are welcome** when they come from a real run: the exact commit, the - hardware, the commands and their results. Say which tool and model wrote the report. -- **AI reviews:** check each point yourself, post only what you confirmed, and say that a tool helped. -- Reply to review comments in the thread, push the fix (squashed into the right commit), and mark the - thread resolved only once it is addressed. - -## AI-assisted contributions - -You can use any AI tool. In return: - -- **You are the author and you are responsible.** You have read every line of the diff, you - understand it, and you can answer questions about it without asking the tool again. "The AI wrote it" - is not an answer in a review. -- **Disclose it** in the PR's **AI use** section: the tool, the model, and what it did (wrote the - code, wrote the tests, wrote the description, only reviewed). A trailer in the commit naming the - model, such as `Co-Authored-By: ` or `Assisted-by: ()`, is welcome too. -- **The tests were run, not just written.** Results in the PR come from a run you did, on hardware - you name. -- **A person opens the PR.** No PRs or issues opened by an unattended agent. -- **Keep the description short and true.** Leave out generated filler, marketing tone and claims - nobody measured. A reviewer should be able to read the description in one minute. -- The same size and scope rules apply. An agent can write 2000 lines in an hour, and nobody can - review that in an hour. Split it. - -Agents working in this repository read [`AGENTS.md`](AGENTS.md) (and Claude Code also reads -[`CLAUDE.md`](CLAUDE.md)), which put these rules into instructions for them. diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 deleted file mode 100644 index a4f668a..0000000 --- a/scripts/smoke.ps1 +++ /dev/null @@ -1,64 +0,0 @@ -# Regression run of a title for a pull request: runs it for a fixed time, reads XCL's log and -# prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built -# from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). -# -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] -# -# Networking is off (XCL_NETWORK=0). Build first: cargo build --release -p xcl -param( - [Parameter(Mandatory = $true)][string]$Game, - [int]$Seconds = 60, - [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe') -) -$ErrorActionPreference = 'Stop' - -if (-not (Test-Path $Xcl)) { throw "no $Xcl - build it first (cargo build --release -p xcl)" } -$root = Split-Path $PSScriptRoot -Parent -$commit = (git -C $root rev-parse HEAD).Trim() -$dirty = [bool](git -C $root status --porcelain --untracked-files=no -- crates Cargo.toml Cargo.lock) - -$out = New-TemporaryFile -$err = New-TemporaryFile -$env:XCL_NETWORK = '0' -$env:XCL_RUN_SECONDS = "$Seconds" -$env:XCL_ACTIVITY = '1' -$p = Start-Process -FilePath $Xcl -ArgumentList @('run', "`"$Game`"") -NoNewWindow -PassThru -RedirectStandardOutput $out -RedirectStandardError $err -$null = $p.Handle # (without it ExitCode stays empty) -if (-not $p.WaitForExit(($Seconds + 120) * 1000)) { - Stop-Process -Id $p.Id -Force - $timedOut = $true -} -Remove-Item Env:XCL_RUN_SECONDS, Env:XCL_ACTIVITY - -$stdout = Get-Content $out -Raw -Encoding utf8 -Remove-Item $out, $err -$logLine = ($stdout -split "`n" | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) -if (-not $logLine) { throw "XCL printed no log path; its output:`n$stdout" } -$log = ($logLine -replace '^Log:\s+', '').Trim() -$text = Get-Content $log -Raw -Encoding utf8 - -$frames = if ($text -match '\((\d+) frames shown, (\d+) PresentX calls\)') { "$($Matches[1]) (PresentX $($Matches[2]))" } else { 'none logged (the run did not reach its end)' } -$presents = [regex]::Matches($text, 'activity \(2 s\): (\d+) presents') | ForEach-Object { [int]$_.Groups[1].Value } -$lastPresents = ($presents | Select-Object -Last 3) -join ' ' -$commits = [regex]::Matches($text, 'memory: (\d+) MB committed') | ForEach-Object { [int]$_.Groups[1].Value } -$peak = if ($commits) { ($commits | Measure-Object -Maximum).Maximum } else { 'n/a' } -$removals = ([regex]::Matches($text, 'device removed')).Count -$crashes = ([regex]::Matches($text, 'unhandled exception|process ends with status')).Count -$gpu = (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1).Name -$code = if ($timedOut) { 'killed (no exit)' } else { '0x{0:x}' -f $p.ExitCode } - -@" -`````` -xcl-smoke v1 -commit: $commit$(if ($dirty) { ' (uncommitted changes)' }) -gpu: $gpu -title: $(Split-Path $Game -Leaf) -seconds: $Seconds -exit: $code -frames shown: $frames -presents per 2 s (last 3): $lastPresents -device removals: $removals -crashes: $crashes -peak commit: $peak MB -`````` -"@ From ee4afde91d7eaf988f4d6aeb2c66223068f03167 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:55:42 -0700 Subject: [PATCH 29/34] Title textures: the watch-pool merge's upload tuple takes bink-283's src, not a second va --- crates/xcl/src/hle/d3d12x/title_textures.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 3e1673b..306ccfc 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -593,16 +593,16 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { let mut batch = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; - while let Some((_, (dev, _, _, tex, _))) = todo.peek() { + while let Some((_, (dev, _, tex, _))) = todo.peek() { if !batch.is_empty() && (bytes + tex.size() as usize > BATCH_BYTES || *dev != device) { break; } - let (r, (dev, va, src, tex, states)) = todo.next().unwrap(); + let (r, (dev, src, tex, states)) = todo.next().unwrap(); device = dev; bytes += tex.size() as usize; let subs = subresources(src, &tex); if super::present::trace_frame() { - note_content(va, &r, &subs); + note_content(src, &r, &subs); } batch.push((r, subs, states)); } @@ -660,7 +660,7 @@ pub unsafe fn probe_gpu_content(res: usize) { } g.push(res); } - let Some((device, va, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; + let Some((device, va, src, tex, gpu_written)) = TEXTURES.lock().unwrap().get(&res).map(|e| (e.device, e.va, e.src, Arc::clone(&e.tex), e.gpu_written)) else { return }; let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; From 9c1b2214813013db89eb342d2f3f1f4b20641736 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:56:04 -0700 Subject: [PATCH 30/34] D3D12.X: keep untranslated console graphics and stream shaders out of the driver From ivall/xcl#303 by @pedrocalazans05, squashed. --- crates/xcl/src/hle/d3d12x/real.rs | 156 +++++++++++++++++++++++++++++- 1 file changed, 151 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9ff59f7..15b8ba1 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3814,6 +3814,14 @@ pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, graphics_pso(this, desc, riid, ppv, false) } +/// Whether any shader stage of a graphics pipeline description carries console bytecode. +unsafe fn graphics_has_console_shader(desc: *const c_void) -> bool { + crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) && { + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS].into_iter().any(|b| shader_bytes(b).is_some_and(crate::gpu::recomp::pso::is_console)) + } +} + /// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); @@ -3824,13 +3832,23 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID return hr; } if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) { - return hr; + if hr >= 0 { + return hr; + } } } else if let Some(hr) = translated { - return hr; + if hr >= 0 { + return hr; + } } - let pc = untranslated_stream_desc(desc, stream); - let hr = finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv); + // a console shader the recompiler could not take must not reach the driver: AMD's shader + // compiler crashes on the stripped DXIL (NOBC bitcode) instead of rejecting it + let hr = if graphics_has_console_shader(desc) { + E_INVALIDARG + } else { + let pc = untranslated_stream_desc(desc, stream); + finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv) + }; if hr >= 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return hr; } @@ -4329,6 +4347,16 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { 25 => put(&mut buf, &dm?.0), 12 | 19 => buf[at..at + 16].fill(0), // input layout, cached PSO 7 => buf[at..at + 32].fill(0), // stream output + 15 if psize >= 32 && at + 32 <= buf.len() => { + for k in 0..8 { + let f = super::device_x::pc_target_format(u32::from_le_bytes(buf[at + 4 * k..at + 4 * k + 4].try_into().unwrap())); + buf[at + 4 * k..at + 4 * k + 4].copy_from_slice(&f.to_le_bytes()); + } + } + 16 if psize >= 4 && at + 4 <= buf.len() => { + let f = super::device_x::pc_view_format(u32::from_le_bytes(buf[at..at + 4].try_into().unwrap())); + buf[at..at + 4].copy_from_slice(&f.to_le_bytes()); + } _ => {} } off += (poff + psize + 7) & !7; @@ -4532,6 +4560,17 @@ unsafe fn put(to: &mut T, from: &[u8]) { std::ptr::copy_nonoverlapping(from.as_ptr(), to as *mut T as *mut u8, n); } +/// Whether any shader subobject of a pipeline state stream carries console bytecode. +unsafe fn stream_has_console_shader(desc: *const c_void) -> bool { + crate::gpu::shader::readable(desc as usize, 16) && { + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + crate::gpu::shader::readable(base, size) + && known_subobjects(std::slice::from_raw_parts(base as *const u8, size)) + .into_iter() + .any(|(ty, p)| matches!(ty, 1..=6 | 24 | 25) && payload_shader(p).is_some_and(crate::gpu::recomp::pso::is_console)) + } +} + pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_stream_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); @@ -4551,7 +4590,9 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void StreamPipeline::Compute(d) => return dev_create_compute_pso(this, &*d as *const _ as *const c_void, riid, ppv), StreamPipeline::Unknown => {} } - let hr = finish_pso(this, f, desc, riid, ppv); + // a console shader the recompiler could not take must not reach the driver: AMD's shader + // compiler crashes on the stripped DXIL (NOBC bitcode) instead of rejecting it + let hr = if stream_has_console_shader(desc) { E_INVALIDARG } else { finish_pso(this, f, desc, riid, ppv) }; if hr >= 0 || !crate::gpu::shader::readable(desc as usize, 16) { return hr; } @@ -5623,3 +5664,108 @@ mod console_format_query_tests { } } } + +#[cfg(test)] +mod console_pso_guard_tests { + use super::*; + + /// Minimal synthetic DXBC container with a DXIL part carrying `XDAT` (what `pso::is_console` + /// recognizes as console bytecode). + fn synthetic_console_shader() -> Vec { + let mut dxil = vec![0u8; 28]; + dxil[24..28].copy_from_slice(b"XDAT"); + let part_offset = 36u32; + let total = part_offset as usize + 8 + dxil.len(); + let mut blob = Vec::with_capacity(total); + blob.extend_from_slice(b"DXBC"); + blob.extend_from_slice(&[0u8; 16]); // hash + blob.extend_from_slice(&1u32.to_le_bytes()); // version + blob.extend_from_slice(&(total as u32).to_le_bytes()); + blob.extend_from_slice(&1u32.to_le_bytes()); // part count + blob.extend_from_slice(&part_offset.to_le_bytes()); + blob.extend_from_slice(b"DXIL"); + blob.extend_from_slice(&(dxil.len() as u32).to_le_bytes()); + blob.extend_from_slice(&dxil); + blob + } + + fn push_shader_subobject(stream: &mut Vec, ty: u32, blob: &[u8]) { + stream.extend_from_slice(&ty.to_le_bytes()); + stream.extend_from_slice(&0u32.to_le_bytes()); // 8-byte alignment pad + stream.extend_from_slice(&(blob.as_ptr() as u64).to_le_bytes()); + stream.extend_from_slice(&(blob.len() as u64).to_le_bytes()); + } + + #[test] + fn graphics_desc_detects_console_shader_in_any_stage() { + let console = synthetic_console_shader(); + assert!(crate::gpu::recomp::pso::is_console(&console)); + let pc = dummy().vs.as_slice(); + assert!(!crate::gpu::recomp::pso::is_console(pc)); + + let empty = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + assert!(!unsafe { graphics_has_console_shader(&empty as *const _ as *const c_void) }); + assert!(!unsafe { graphics_has_console_shader(std::ptr::null()) }); + + let pc_only = D3D12_GRAPHICS_PIPELINE_STATE_DESC { VS: bytecode(pc), PS: bytecode(&dummy().ps), ..Default::default() }; + assert!(!unsafe { graphics_has_console_shader(&pc_only as *const _ as *const c_void) }); + + for stage in 0..5 { + let mut d = pc_only.clone(); + match stage { + 0 => d.VS = bytecode(&console), + 1 => d.PS = bytecode(&console), + 2 => d.DS = bytecode(&console), + 3 => d.HS = bytecode(&console), + _ => d.GS = bytecode(&console), + } + assert!(unsafe { graphics_has_console_shader(&d as *const _ as *const c_void) }, "stage {stage}"); + } + } + + #[test] + fn pipeline_stream_detects_console_shader_subobjects() { + let console = synthetic_console_shader(); + let pc = dummy().vs.as_slice(); + + let mut pc_stream = Vec::new(); + push_shader_subobject(&mut pc_stream, 1, pc); + let desc = [pc_stream.len(), pc_stream.as_ptr() as usize]; + assert!(!unsafe { stream_has_console_shader(desc.as_ptr() as *const c_void) }); + assert!(!unsafe { stream_has_console_shader(std::ptr::null()) }); + + for ty in [1u32, 2, 3, 4, 5, 6, 24, 25] { + let mut s = Vec::new(); + push_shader_subobject(&mut s, ty, &console); + let d = [s.len(), s.as_ptr() as usize]; + assert!(unsafe { stream_has_console_shader(d.as_ptr() as *const c_void) }, "subobject {ty}"); + } + } + + #[test] + fn fallback_stream_rewrites_console_rtv_and_dsv_formats() { + let console = synthetic_console_shader(); + let mut s = Vec::new(); + push_shader_subobject(&mut s, 1, &console); + // subobject 15: D3D12_RT_FORMAT_ARRAY (8 × DXGI_FORMAT + NumRenderTargets) + s.extend_from_slice(&15u32.to_le_bytes()); + let rtv_off = s.len(); + for f in [116u32, 117, 86, 115, 28, 0, 0, 0, 5] { + s.extend_from_slice(&f.to_le_bytes()); + } + // subobject 16: DSVFormat = D16_UNORM_S8_UINT (118) + s.extend_from_slice(&16u32.to_le_bytes()); + let dsv_off = s.len(); + s.extend_from_slice(&118u32.to_le_bytes()); + + let desc = [s.len(), s.as_ptr() as usize]; + let (out, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("fallback stream"); + let vs_ptr = u64::from_le_bytes(out[8..16].try_into().unwrap()) as usize; + assert_eq!(vs_ptr, dummy().vs.as_ptr() as usize, "console VS replaced with dummy VS"); + + let rtv: [u32; 8] = std::array::from_fn(|k| u32::from_le_bytes(out[rtv_off + 4 * k..rtv_off + 4 * k + 4].try_into().unwrap())); + assert_eq!(rtv, [10, 10, 28, 28, 28, 0, 0, 0]); + let dsv = u32::from_le_bytes(out[dsv_off..dsv_off + 4].try_into().unwrap()); + assert_eq!(dsv, 45); + } +} From 15b6197c4317cc26b89ac2f222c0d94a6815c16e Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 15:56:08 -0700 Subject: [PATCH 31/34] Recompiler: the mesh pass-through budget accounts DXC's vertex chunks From ivall/xcl#304 by @ryosen0, squashed. --- crates/xcl/src/gpu/recomp/emit.rs | 13 +++++-- crates/xcl/src/gpu/recomp/tests.rs | 56 ++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 57a6499..6f65c37 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5021,15 +5021,24 @@ pub fn mesh_passthrough_for(ms: &MsInterface, ps_inputs: Option<&[SigElement]>) /// D3D12's limit on what one mesh shader group outputs (vertex + primitive attributes). const MESH_OUTPUT_BYTES: u32 = 32768; +/// Vertices the pass-through puts in one mesh group: the vertex output budget divided by the +/// stride, and DXC accounts whole chunks of 32 vertices even when fewer are declared (78 +/// vertices with 22 rows are accounted as 96). Measured with dxc 1.8.2502 (ms_6_6): every +/// boundary from 9 to 26 float4 rows agrees. +fn passthrough_max_vertices(vbytes: u32) -> u32 { + (MESH_OUTPUT_BYTES / vbytes).min(256) / 32 * 32 +} + /// Mesh groups the pass-through spends on one record: 1 when the record's vertices fit the /// mesh output limit as they are, else the triangles are split into runs whose own vertex /// copies (3 per triangle) fit. `elements`: output elements besides SV_Position. pub fn passthrough_split(ms: &MsInterface, elements: usize) -> u32 { let vbytes = 16 * (1 + elements as u32); - if vbytes * ms.max_vertices <= MESH_OUTPUT_BYTES { + let cap = passthrough_max_vertices(vbytes); + if ms.max_vertices <= cap { return 1; } - let ppg = (MESH_OUTPUT_BYTES / (3 * vbytes)).max(1); + let ppg = (cap / 3).max(1); ms.max_primitives.max(1).div_ceil(ppg) } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index f58f1e5..a140186 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3925,6 +3925,62 @@ fn gpu_mesh_mode_two_passes() { assert!(px16 == px, "split pass-through draws the same pixels"); } +/// The mesh output budget with wide vertices: DXC accounts whole chunks of 32 vertices even +/// when fewer are declared, so 78 vertices with 22 float4 rows are accounted as 96 (33792 B > +/// 32768) and the record must go out in split groups. A retail title's NGG transform programs +/// have this shape (128 vertices / 128 primitives, 21 params + SV_ClipDistance0); the previous +/// budget (32768 / stride) emitted verts[78] and DXC refused every one of them. +#[test] +fn mesh_split_accounts_vertex_chunks() { + use super::emit::{mesh_passthrough, passthrough_elements, passthrough_split}; + use super::MsInterface; + if super::dxc::location().is_err() { + println!("no DXC – skipping"); + runner::skip_test("no DXC"); + return; + } + let sig = |name: &str, sv: u32, reg: u32, index: u32| crate::gpu::dxbc::SigElement { + name: name.into(), + index, + system_value: sv, + component_type: 3, + register: reg, + mask: 0xF, + rw_mask: 0xF, + stream: 0, + }; + let mut outputs = vec![sig("SV_Position", 1, 0, 0)]; + for k in 0..20u32 { + outputs.push(sig("TEXCOORD", 0, k + 1, k)); + } + outputs.push(sig("SV_ClipDistance", 2, 21, 0)); + let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128 }; + let elems = passthrough_elements(&ms, None); + assert_eq!(elems, 21); + // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit (96 would be 33792 B), so at + // most 21 triangles' worth of copies per group, ceil(128/21) = 7 groups of 19 + let split = passthrough_split(&ms, elems); + assert_eq!(split, 7, "chunks of 32: 78 verts are accounted as 96 and refused"); + let pass = mesh_passthrough(&ms); + assert!(pass.contains("verts[57]"), "19 triangles per group:\n{pass}"); + super::dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); + // 20 rows * 16 B = 320 B/vertex: 96 accounted vertices fit (30720 B), but a whole record + // is 128 vertices (40960 B) – 4 groups of 32 triangles, 96 vertices each + let mut ms20 = ms.clone(); + ms20.outputs.pop(); + assert_eq!(passthrough_split(&ms20, passthrough_elements(&ms20, None)), 4); + let pass20 = mesh_passthrough(&ms20); + assert!(pass20.contains("verts[96]"), "96 vertices per group:\n{pass20}"); + super::dxc::compile(&pass20, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass20}")); + // 8 rows * 16 B = 128 B/vertex: 128 vertices are 16384 B – the record stays whole + let mut ms8 = ms.clone(); + ms8.outputs.truncate(8); + assert_eq!(passthrough_split(&ms8, passthrough_elements(&ms8, None)), 1); + let pass8 = mesh_passthrough(&ms8); + assert!(pass8.contains("verts[128]"), "whole record:\n{pass8}"); + super::dxc::compile(&pass8, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass8}")); +} + /// DXC optimisation levels on a saved HLSL file (`XCL_TIME_HLSL=path`, profile in `XCL_TIME_PROFILE`). #[test] #[ignore] From 6bbef9f4215331b26e006b1d6b08c3bf0b4ae44c Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 16:02:04 -0700 Subject: [PATCH 32/34] Write-watch: every submit by default again; once a frame only with XCL_WATCH_PER_FRAME=1 gpu_sparse_vram_descriptors_buffers_and_xmem showed the cost: descriptors written between two submits of one frame missed the second submit. The parts test takes the thread count as an argument instead of the environment. (cherry picked from commit b2677070ac82b5b84fc71835f335bb5eb0972bd2) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 30 ++++++++++++--------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 306ccfc..2987efe 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -362,12 +362,16 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { /// The write-watch ranges split into at most `WATCH_THREADS` parts of about equal size, or one /// part when the set is small enough that threads would cost more than they save. fn watch_parts(ranges: &[(usize, usize)]) -> Vec> { + split_watch(ranges, watch_threads()) +} + +fn split_watch(ranges: &[(usize, usize)], threads: usize) -> Vec> { const MIN_PARALLEL: usize = 256 << 20; let total: usize = ranges.iter().map(|r| r.1).sum(); - if ranges.len() < 2 || total < MIN_PARALLEL || watch_threads() < 2 { + if ranges.len() < 2 || total < MIN_PARALLEL || threads < 2 { return vec![ranges.to_vec()]; } - let k = watch_threads().min(ranges.len()); + let k = threads.min(ranges.len()); let share = total.div_ceil(k); let mut parts: Vec> = vec![Vec::new()]; let mut acc = 0usize; @@ -442,14 +446,15 @@ fn watch_pool() -> &'static WatchPool { }) } -/// Whether this submit reads the write-watch. GetWriteWatch walks every watched page (gigabytes -/// of mapped sparse tiles on a newer retail title: about 15 ms a call) and a title submits several -/// times a frame, so by default it is read once a frame: at the first submit after a present. -/// A page written between two submits of one frame then reaches video memory at the next frame's -/// first submit. `XCL_WATCH_EVERY_SUBMIT=1` reads it before every submit, as before. +/// Whether this submit reads the write-watch. By default every submit does: a page the CPU wrote +/// between two submits (descriptors, buffers in sparse windows) must reach video memory before the +/// second one. GetWriteWatch walks every watched page, though (gigabytes of mapped sparse tiles on a +/// newer retail title: about 15 ms a call, several submits a frame), so `XCL_WATCH_PER_FRAME=1` +/// reads it only at the first submit after a present: faster, but a write made between two submits +/// of one frame reaches video memory one frame late. fn scan_this_submit() -> bool { - static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); - if *EVERY.get_or_init(|| std::env::var("XCL_WATCH_EVERY_SUBMIT").is_ok_and(|v| v != "0")) { + static PER_FRAME: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*PER_FRAME.get_or_init(|| std::env::var("XCL_WATCH_PER_FRAME").is_ok_and(|v| v != "0")) { return true; } static LAST: AtomicU64 = AtomicU64::new(u64::MAX); @@ -916,14 +921,15 @@ mod tests { #[cfg(test)] mod watch_parts_tests { - use super::watch_parts; + use super::split_watch; #[test] fn small_sets_stay_serial_and_large_ones_split_without_losing_a_range() { let small = vec![(0x1000usize, 0x10000usize), (0x20000, 0x10000)]; - assert_eq!(watch_parts(&small), vec![small.clone()]); + assert_eq!(split_watch(&small, 8), vec![small.clone()]); let big: Vec<(usize, usize)> = (0..40).map(|i| (0x1_0000_0000 + i * (64 << 20), 64 << 20)).collect(); - let parts = watch_parts(&big); + assert_eq!(split_watch(&big, 1), vec![big.clone()], "one thread: the serial loop"); + let parts = split_watch(&big, 8); assert!(parts.len() > 1 && parts.len() <= 8, "{} parts", parts.len()); let flat: Vec<(usize, usize)> = parts.concat(); assert_eq!(flat, big, "every range exactly once, in order"); From 955eda1d95d4e61fa63f7138e2cb07aad16a60c6 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 16:08:06 -0700 Subject: [PATCH 33/34] Write-watch: fewer, larger calls and a buffer that holds the range GetWriteWatch costs a fixed part per call and a part per page. Measured on a 2 GiB write-watched reservation on the RTX 4090 machine: about 6.9 us a call plus 0.35 us a MiB (512 MiB in one call: 0.28 ms; the same bytes in 512 calls of 1 MiB: 3.79 ms). A look over 3 GiB of tiles in hundreds of ranges is therefore mostly call overhead. WATCH_GAP rises from 1 MiB to 16 MiB, under the break-even gap of about 19 MiB, so a gap is walked only where that is cheaper than the call it removes. A call whose output buffer fills leaves the rest dirty and the next call walks the whole range again; the buffer now grows (4x, up to 4M entries) so one call holds what a range has. The timing line now prints ranges and bytes watched, and a Windows test runs watch_into with more dirty pages than the buffer starts with. --- crates/xcl/src/hle/d3d12x/sparse.rs | 13 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 177 +++++++++++++++++++- 2 files changed, 181 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 8acd3d8..5c269c7 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1345,14 +1345,17 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { s.runs.clone().unwrap_or_default() } -/// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line -static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// time spent, pages found, ranges read and bytes watched by the write-watch scans +/// (`refresh_once`), for the timing line +static WATCH: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; /// [lock wait, chunk scan, upload] in µs, runs uploaded static PHASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; -pub fn note_watch(t: std::time::Duration, pages: usize) { +pub fn note_watch(t: std::time::Duration, pages: usize, ranges: usize, bytes: usize) { WATCH[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); + WATCH[2].fetch_add(ranges as u64, Ordering::Relaxed); + WATCH[3].fetch_add(bytes as u64, Ordering::Relaxed); } /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB @@ -1422,9 +1425,11 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len()); let ms = |x: &AtomicU64| x.load(Ordering::Relaxed) / 1000; crate::xlog_info!( - "sparse windows timing: write-watch {} ms ({} dirty pages), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)", + "sparse windows timing: write-watch {} ms ({} dirty pages, {} ranges, {} MB watched), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)", ms(&WATCH[0]), WATCH[1].load(Ordering::Relaxed), + WATCH[2].load(Ordering::Relaxed), + WATCH[3].load(Ordering::Relaxed) >> 20, ms(&PHASES[0]), ms(&PHASES[1]), ms(&PHASES[2]), diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2987efe..f83a653 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -394,7 +394,15 @@ fn watch_threads() -> usize { } /// GetWriteWatch with reset over `ranges`: every written page's address goes to `dirty`. +/// +/// When the buffer fills, the call reports the pages that fitted and leaves the rest dirty, and +/// the next call walks the whole range again from its base (measured: a 2 GiB range with 100k +/// dirty pages and a 16384-entry buffer costs one walk per bufferful). A look that finds more +/// pages than the buffer holds therefore costs several walks; the buffer grows to hold what the +/// range has, up to `MAX_WATCH_BUF` entries. unsafe fn watch_into(ranges: &[(usize, usize)], buf: &mut Vec<*mut c_void>, dirty: &mut Vec, page: &mut u32) { + /// 4M pages (16 GiB of 4 KiB pages) held as 32 MiB of pointers + const MAX_WATCH_BUF: usize = 4 << 20; if buf.len() < 16384 { buf.resize(16384, std::ptr::null_mut()); } @@ -408,6 +416,9 @@ unsafe fn watch_into(ranges: &[(usize, usize)], buf: &mut Vec<*mut c_void>, dirt if n < buf.len() { break; } + if buf.len() < MAX_WATCH_BUF { + buf.resize((buf.len() * 4).min(MAX_WATCH_BUF), std::ptr::null_mut()); + } } } } @@ -505,7 +516,12 @@ unsafe fn refresh_once(queue: *mut c_void) { dirty.sort_unstable(); dirty.len() }); - super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + super::sparse::note_watch( + watch_t0.elapsed(), + dirty_len, + if scan { ranges.len() } else { 0 }, + if scan { ranges.iter().map(|r| r.1).sum() } else { 0 }, + ); if super::present::trace_frame() { // every 600th look: what the CPU's view of a few textures holds now (does the title's // data reach the address at all, and is the texture still kept in step?) @@ -753,9 +769,12 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result Self { + let p = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; + assert!(!p.is_null(), "VirtualAlloc({len}, MEM_WRITE_WATCH) failed"); + Watched(p, len) + } + + /// write one byte of `pages` 4 KiB pages, spread over the range + fn touch(&self, pages: usize) { + let step = (self.1 / pages.max(1) & !0xFFF).max(0x1000); + for k in 0..pages { + unsafe { std::ptr::write_volatile((self.0 as *mut u8).add(k * step), 1) }; + } + } + } + + impl Drop for Watched { + fn drop(&mut self) { + unsafe { VirtualFree(self.0, 0, MEM_RELEASE) }; + } + } + + fn mb() -> usize { + std::env::var("XCL_BENCH_WATCH_MB").ok().and_then(|v| v.parse().ok()).unwrap_or(512).clamp(16, 2048) + } + + /// More dirty pages than the buffer starts with: `watch_into` grows the buffer and returns + /// every page without a second walk over the range. + #[test] + fn more_dirty_pages_than_the_buffer_holds_are_all_returned() { + let w = Watched::new(128 << 20); + let pages = 20_000usize; + w.touch(pages); + let mut buf: Vec<*mut c_void> = Vec::new(); + let mut dirty: Vec = Vec::new(); + let mut gran = 0u32; + unsafe { watch_into(&[(w.0 as usize, w.1)], &mut buf, &mut dirty, &mut gran) }; + dirty.sort_unstable(); + dirty.dedup(); + assert_eq!(dirty.len(), pages, "every written page reported once"); + assert!(buf.len() >= pages, "the buffer grew to hold the range's pages ({} entries)", buf.len()); + } + + #[test] + #[ignore = "bench: up to 2 GiB, cost by bytes and by dirty pages"] + fn get_write_watch_cost_by_bytes_and_dirty_pages() { + let mb = mb(); + let w = Watched::new(mb << 20); + let mut buf = vec![std::ptr::null_mut::(); 1 << 16]; + for &dirty in &[0usize, 16, 1024, 16384] { + w.touch(dirty); + let t = std::time::Instant::now(); + let (mut n, mut gran) = (buf.len(), 0u32); + let r = unsafe { GetWriteWatch(WRITE_WATCH_FLAG_RESET, w.0, w.1, buf.as_mut_ptr(), &mut n, &mut gran) }; + let d = t.elapsed().as_secs_f64(); + assert_eq!(r, 0, "GetWriteWatch failed"); + assert_eq!(n, dirty, "{dirty} pages written, {n} reported"); + println!( + "watched {mb} MiB ({:.0} pages), {n} dirty: {:.2} ms ({:.2} ns/page, {:.3} µs/dirty page)", + w.1 as f64 / 4096.0, + d * 1e3, + d * 1e9 / (w.1 as f64 / 4096.0), + d * 1e6 / n.max(1) as f64 + ); + } + } + + /// The same bytes in one call and in many: the fixed cost of a call. + #[test] + #[ignore = "bench: 512 MiB in 1 call vs calls of 1, 4 and 16 MiB"] + fn cost_of_many_small_ranges() { + let len = mb() << 20; + let w = Watched::new(len); + let mut buf = vec![std::ptr::null_mut::(); 1 << 16]; + for chunk in [len, 16 << 20, 4 << 20, 1 << 20] { + w.touch(64); + let mut got = 0usize; + let t = std::time::Instant::now(); + for base in (0..len).step_by(chunk) { + let (mut n, mut gran) = (buf.len(), 0u32); + let r = unsafe { GetWriteWatch(WRITE_WATCH_FLAG_RESET, (w.0 as *const u8).add(base) as *const c_void, chunk, buf.as_mut_ptr(), &mut n, &mut gran) }; + assert_eq!(r, 0); + got += n; + } + let d = t.elapsed().as_secs_f64(); + println!( + "{} MiB in {} calls of {} MiB: {:.2} ms, {got} pages ({:.1} µs a call)", + len >> 20, + len / chunk, + chunk >> 20, + d * 1e3, + d * 1e6 / (len / chunk) as f64 + ); + assert_eq!(got, 64); + } + } + + /// A buffer that fills: the call reports what fitted and the rest stay dirty, so the next + /// call walks the whole range again (why `watch_into` grows the buffer). + #[test] + #[ignore = "bench: 2 GiB, 100k dirty pages, small vs grown buffer"] + fn a_full_buffer_costs_one_walk_per_bufferful() { + let w = Watched::new(2048 << 20); + let dirty = 100_000usize; + for entries in [16384usize, 0] { + w.touch(dirty); + let mut buf = vec![std::ptr::null_mut::(); if entries == 0 { dirty + 1024 } else { entries }]; + let t = std::time::Instant::now(); + let (mut got, mut calls, mut gran) = (0usize, 0usize, 0u32); + loop { + let mut n = buf.len(); + let r = unsafe { GetWriteWatch(WRITE_WATCH_FLAG_RESET, w.0, w.1, buf.as_mut_ptr(), &mut n, &mut gran) }; + assert_eq!(r, 0); + got += n; + calls += 1; + if n < buf.len() { + break; + } + } + println!("buffer {} entries: {calls} calls, {got} of {dirty} pages, {:.2} ms", buf.len(), t.elapsed().as_secs_f64() * 1e3); + assert_eq!(got, dirty); + } + } +} From 33bd352d9b3b5b53b4041d8ce6a9300347cf3b31 Mon Sep 17 00:00:00 2001 From: T-Crypt Date: Mon, 23 Nov 2026 16:10:07 -0700 Subject: [PATCH 34/34] Write-watch range test: gaps under and over WATCH_GAP --- crates/xcl/src/hle/d3d12x/title_textures.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index f83a653..bdefc2c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -932,9 +932,9 @@ mod tests { let regions = [(0x10000, 0x10000), (0x40000, 0x10000), (0x1000_0000, 0x1000_0000)]; let wanted = vec![(0x12000, 0x13000), (0x11000, 0x12800), (0x1F000, 0x41000), (0x60000, 0x61000)]; assert_eq!(watch_ranges(®ions, wanted), vec![(0x11000, 0xF000), (0x40000, 0x10000)]); - // ranges a gap of 512 KiB apart: one scan; 240 MiB apart: two - let wanted = vec![(0x1000_0000, 0x1000_1000), (0x1008_0000, 0x1008_1000), (0x1100_0000, 0x1100_1000)]; - assert_eq!(watch_ranges(®ions, wanted), vec![(0x1000_0000, 0x8_1000), (0x1100_0000, 0x1000)]); + // ranges a gap of 512 KiB apart: one scan; 47 MiB apart: two + let wanted = vec![(0x1000_0000, 0x1000_1000), (0x1008_0000, 0x1008_1000), (0x1300_0000, 0x1300_1000)]; + assert_eq!(watch_ranges(®ions, wanted), vec![(0x1000_0000, 0x8_1000), (0x1300_0000, 0x1000)]); // a call costs more than the walk over a gap of up to `WATCH_GAP`: 8 MiB merges, 40 MiB not let wanted = vec![(0x1000_0000, 0x1000_1000), (0x1080_1000, 0x1080_2000)]; assert_eq!(watch_ranges(®ions, wanted), vec![(0x1000_0000, 0x80_2000)]);